From 4fdd01052b0e08f0dd20f05650468000875c0039 Mon Sep 17 00:00:00 2001 From: Zorg Date: Sat, 23 Jan 2021 01:43:41 -0800 Subject: [PATCH 1/2] Add option to store a specified private+public key pair directly This is useful for migrating keys from one machine to another. --- generate_keys/main.swift | 118 +++++++++++++++++++++++++++++---------- 1 file changed, 87 insertions(+), 31 deletions(-) diff --git a/generate_keys/main.swift b/generate_keys/main.swift index cca1dca9..783656b5 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 [ @@ -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())", @@ -120,7 +126,7 @@ func generateKeyPair() -> Data { 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,98 @@ 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] [-s key-pair] + + This tool uses the macOS Keychain to store a public/private key pair 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. + -s key-pair + Stores the specified key-pair to your keychain instead of generating a new key. + If you want to migrate keys from another machine, find \"\(PRIVATE_KEY_LABEL)\" + in Keychain Access from your previous machine and retrieve its password, + which is the key-pair to specify here. Any existing keys in Keychain Access + may need to be removed 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 pubKey = findPublicKey() { print(pubKey.base64EncodedString()) + } else { + failure("No existing signing key found!") + } + case .some("-s"): + /// Store mode - store the specifed key-pair + guard arguments.count > 2 else { + failure("key-pair was not specified") + } - /// Existing key found, normal mode - print instructions blurb and pubkey - case (.some(let pubKey), false): + let privateAndPublicBase64Key = arguments[2] + print(privateAndPublicBase64Key) + + guard let privateAndPublicKey = Data(base64Encoded: privateAndPublicBase64Key, options: .init()) else { + failure("Failed to decode private+public key data from: \(privateAndPublicBase64Key)") + } + + guard privateAndPublicKey.count == 64 + 32 else { + failure("Specified private+public key must be 96 bytes decoded. Instead it is \(privateAndPublicKey.count) bytes decoded.") + } + + print("Storing signing key..") + + let publicKey = privateAndPublicKey[64...] + let privateKey = privateAndPublicKey[0..<64] + + storeKeyPair(publicEdKey: publicKey, privateEdKey: privateKey) + + printNewPublicKeyUsage(publicKey) + + 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 pubKey = findPublicKey() { print(""" A pre-existing signing key was found. This is how it should appear in your Info.plist: @@ -172,26 +240,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) + } } } From d85c1df752201c52c6e87d3dd79744c44bd243b7 Mon Sep 17 00:00:00 2001 From: Zorg Date: Sat, 23 Jan 2021 07:51:32 -0800 Subject: [PATCH 2/2] Add options to export and import private/public key pair --- generate_keys/main.swift | 78 ++++++++++++++++++++++++++++------------ 1 file changed, 55 insertions(+), 23 deletions(-) diff --git a/generate_keys/main.swift b/generate_keys/main.swift index 783656b5..feb0350c 100644 --- a/generate_keys/main.swift +++ b/generate_keys/main.swift @@ -39,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. @@ -49,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! @@ -120,7 +120,7 @@ func storeKeyPair(publicEdKey: Data, privateEdKey: 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 @@ -166,10 +166,11 @@ func entryPoint() { /// If not in any mode, give an intro blurb. if mode == nil { print(""" - Usage: \(programName) [-p] [-s key-pair] + Usage: \(programName) [-p] [-x private-key-file] [-f private-key-file] - This tool uses the macOS Keychain to store a public/private key pair for signing app updates which - will be distributed via Sparkle. This key will be associated with your user account. + 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. @@ -180,13 +181,16 @@ func entryPoint() { 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. - -s key-pair - Stores the specified key-pair to your keychain instead of generating a new key. - If you want to migrate keys from another machine, find \"\(PRIVATE_KEY_LABEL)\" - in Keychain Access from your previous machine and retrieve its password, - which is the key-pair to specify here. Any existing keys in Keychain Access - may need to be removed first before proceeding. + -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. ---------------------------------------------------------------------------------------------------- @@ -196,29 +200,35 @@ func entryPoint() { switch mode { case .some("-p"): /// Lookup mode - print just the pubkey and exit - if let pubKey = findPublicKey() { + if let keyPair = findKeyPair() { + let pubKey = keyPair[64...] print(pubKey.base64EncodedString()) } else { failure("No existing signing key found!") } - case .some("-s"): - /// Store mode - store the specifed key-pair + case .some("-f"): + /// Import mode - import the specifed key-pair file guard arguments.count > 2 else { - failure("key-pair was not specified") + failure("private-key-file was not specified") } - let privateAndPublicBase64Key = arguments[2] - print(privateAndPublicBase64Key) + 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, options: .init()) else { - failure("Failed to decode private+public key data from: \(privateAndPublicBase64Key)") + 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("Specified private+public key must be 96 bytes decoded. Instead it is \(privateAndPublicKey.count) bytes decoded.") + failure("Imported key must be 96 bytes decoded. Instead it is \(privateAndPublicKey.count) bytes decoded.") } - print("Storing signing key..") + print("Importing signing key..") let publicKey = privateAndPublicKey[64...] let privateKey = privateAndPublicKey[0..<64] @@ -227,12 +237,34 @@ func entryPoint() { 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 pubKey = findPublicKey() { + 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: