From 9118cb6ecd240feae67464e1fdb225a691ea3003 Mon Sep 17 00:00:00 2001 From: Tony Arnold Date: Sun, 16 Jun 2019 21:46:45 +1000 Subject: [PATCH] Update generate_appcast command line tool to support ed25519 signatures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This code has been ported directly from `master`. Co-authored-by: Kornel LesiƄski # Conflicts: # Sparkle.xcodeproj/project.pbxproj --- Sparkle.xcodeproj/project.pbxproj | 13 ++- Sparkle/SUConstants.h | 3 + Sparkle/SUConstants.m | 3 + generate_appcast/Appcast-Bridging-Header.h | 1 + generate_appcast/Appcast.swift | 89 +++++++++++++++---- generate_appcast/ArchiveItem.swift | 51 +++++++---- generate_appcast/FeedXML.swift | 59 +++++------- .../{DSASignature.swift => Signatures.swift} | 46 ++++++++-- generate_appcast/Unarchive.swift | 9 +- generate_appcast/main.swift | 67 +++++++++----- 10 files changed, 231 insertions(+), 110 deletions(-) rename generate_appcast/{DSASignature.swift => Signatures.swift} (69%) diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index 7fef0fd5..f6915b64 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -96,7 +96,7 @@ 7205C4411E13049400E370AE /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7205C4401E13049400E370AE /* main.swift */; }; 7205C44C1E1304CE00E370AE /* Appcast.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7205C4471E1304CE00E370AE /* Appcast.swift */; }; 7205C44D1E1304CE00E370AE /* ArchiveItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7205C4481E1304CE00E370AE /* ArchiveItem.swift */; }; - 7205C44E1E1304CE00E370AE /* DSASignature.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7205C4491E1304CE00E370AE /* DSASignature.swift */; }; + 7205C44E1E1304CE00E370AE /* Signatures.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7205C4491E1304CE00E370AE /* Signatures.swift */; }; 7205C44F1E1304CE00E370AE /* FeedXML.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7205C44A1E1304CE00E370AE /* FeedXML.swift */; }; 7205C4501E1304CE00E370AE /* Unarchive.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7205C44B1E1304CE00E370AE /* Unarchive.swift */; }; 7205C4561E13060D00E370AE /* SUStandardVersionComparator.m in Sources */ = {isa = PBXBuildFile; fileRef = 61A225A30D1C4AC000430CCD /* SUStandardVersionComparator.m */; }; @@ -448,6 +448,7 @@ EA1E285322B66115004AA304 /* fixedint.h in Copy Headers */ = {isa = PBXBuildFile; fileRef = EA1E284122B660ED004AA304 /* fixedint.h */; }; EA1E285422B66115004AA304 /* sc.h in Copy Headers */ = {isa = PBXBuildFile; fileRef = EA1E284322B660ED004AA304 /* sc.h */; }; EA1E285522B66115004AA304 /* ge.h in Copy Headers */ = {isa = PBXBuildFile; fileRef = EA1E284422B660ED004AA304 /* ge.h */; }; + EA1E285622B6619B004AA304 /* libed25519.a in Frameworks */ = {isa = PBXBuildFile; fileRef = EA1E282D22B660BE004AA304 /* libed25519.a */; }; F8761EB11ADC5068000C9034 /* SUCodeSigningVerifierTest.m in Sources */ = {isa = PBXBuildFile; fileRef = F8761EB01ADC5068000C9034 /* SUCodeSigningVerifierTest.m */; }; F8761EB31ADC50EB000C9034 /* SparkleTestCodeSignApp.zip in Resources */ = {isa = PBXBuildFile; fileRef = F8761EB21ADC50EB000C9034 /* SparkleTestCodeSignApp.zip */; }; /* End PBXBuildFile section */ @@ -1009,7 +1010,7 @@ 7205C4461E1304C300E370AE /* Appcast-Bridging-Header.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "Appcast-Bridging-Header.h"; sourceTree = ""; }; 7205C4471E1304CE00E370AE /* Appcast.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Appcast.swift; sourceTree = ""; }; 7205C4481E1304CE00E370AE /* ArchiveItem.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ArchiveItem.swift; sourceTree = ""; }; - 7205C4491E1304CE00E370AE /* DSASignature.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DSASignature.swift; sourceTree = ""; }; + 7205C4491E1304CE00E370AE /* Signatures.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Signatures.swift; sourceTree = ""; }; 7205C44A1E1304CE00E370AE /* FeedXML.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FeedXML.swift; sourceTree = ""; }; 7205C44B1E1304CE00E370AE /* Unarchive.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Unarchive.swift; sourceTree = ""; }; 7205C4511E13053500E370AE /* ConfigSwiftDebug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ConfigSwiftDebug.xcconfig; sourceTree = ""; }; @@ -1358,6 +1359,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + EA1E285622B6619B004AA304 /* libed25519.a in Frameworks */, EA1E281A22B645F4004AA304 /* libbsdiff.a in Frameworks */, 7205C4641E1306BE00E370AE /* libbz2.tbd in Frameworks */, 7205C4631E1306B500E370AE /* libxar.tbd in Frameworks */, @@ -1905,9 +1907,9 @@ 7205C4461E1304C300E370AE /* Appcast-Bridging-Header.h */, 7205C4471E1304CE00E370AE /* Appcast.swift */, 7205C4481E1304CE00E370AE /* ArchiveItem.swift */, - 7205C4491E1304CE00E370AE /* DSASignature.swift */, 7205C44A1E1304CE00E370AE /* FeedXML.swift */, 7205C4401E13049400E370AE /* main.swift */, + 7205C4491E1304CE00E370AE /* Signatures.swift */, 7205C44B1E1304CE00E370AE /* Unarchive.swift */, ); path = generate_appcast; @@ -3163,7 +3165,7 @@ 72464F7C1E2097F600FB341C /* SUOperatingSystem.m in Sources */, 7205C44C1E1304CE00E370AE /* Appcast.swift in Sources */, 7205C44D1E1304CE00E370AE /* ArchiveItem.swift in Sources */, - 7205C44E1E1304CE00E370AE /* DSASignature.swift in Sources */, + 7205C44E1E1304CE00E370AE /* Signatures.swift in Sources */, 7205C44F1E1304CE00E370AE /* FeedXML.swift in Sources */, 7205C4411E13049400E370AE /* main.swift in Sources */, 7205C45F1E13066F00E370AE /* SUBinaryDeltaApply.m in Sources */, @@ -3951,7 +3953,6 @@ isa = XCBuildConfiguration; baseConfigurationReference = 7205C4541E13054900E370AE /* ConfigGenerateAppcastDebug.xcconfig */; buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; CODE_SIGN_IDENTITY = "-"; }; name = Debug; @@ -3960,7 +3961,6 @@ isa = XCBuildConfiguration; baseConfigurationReference = 7205C4541E13054900E370AE /* ConfigGenerateAppcastDebug.xcconfig */; buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; CODE_SIGN_IDENTITY = "-"; }; name = Coverage; @@ -3969,7 +3969,6 @@ isa = XCBuildConfiguration; baseConfigurationReference = 7205C4551E13054900E370AE /* ConfigGenerateAppcastRelease.xcconfig */; buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; CODE_SIGN_IDENTITY = "-"; }; name = Release; diff --git a/Sparkle/SUConstants.h b/Sparkle/SUConstants.h index 02725898..abf13893 100644 --- a/Sparkle/SUConstants.h +++ b/Sparkle/SUConstants.h @@ -43,8 +43,10 @@ extern NSString *const SUSkippedVersionKey; extern NSString *const SUScheduledCheckIntervalKey; extern NSString *const SULastCheckTimeKey; extern NSString *const SUExpectsDSASignatureKey; +extern NSString *const SUExpectsEDSignatureKey; extern NSString *const SUPublicDSAKeyKey; extern NSString *const SUPublicDSAKeyFileKey; +extern NSString *const SUPublicEDKeyKey; extern NSString *const SUAutomaticallyUpdateKey; extern NSString *const SUAllowsAutomaticUpdatesKey; extern NSString *const SUEnableAutomaticChecksKey; @@ -66,6 +68,7 @@ extern NSString *const SURelaunchToolNameKey __attribute__((deprecated("This key extern NSString *const SUAppcastAttributeDeltaFrom; extern NSString *const SUAppcastAttributeDSASignature; +extern NSString *const SUAppcastAttributeEDSignature; extern NSString *const SUAppcastAttributeShortVersionString; extern NSString *const SUAppcastAttributeVersion; extern NSString *const SUAppcastAttributeOsType; diff --git a/Sparkle/SUConstants.m b/Sparkle/SUConstants.m index d6bf46b8..b74537ca 100644 --- a/Sparkle/SUConstants.m +++ b/Sparkle/SUConstants.m @@ -38,8 +38,10 @@ NSString *const SUSkippedVersionKey = @"SUSkippedVersion"; NSString *const SUScheduledCheckIntervalKey = @"SUScheduledCheckInterval"; NSString *const SULastCheckTimeKey = @"SULastCheckTime"; NSString *const SUExpectsDSASignatureKey = @"SUExpectsDSASignature"; +NSString *const SUExpectsEDSignatureKey = @"SUExpectsEDSignatureKey"; NSString *const SUPublicDSAKeyKey = @"SUPublicDSAKey"; NSString *const SUPublicDSAKeyFileKey = @"SUPublicDSAKeyFile"; +NSString *const SUPublicEDKeyKey = @"SUPublicEDKey"; NSString *const SUAutomaticallyUpdateKey = @"SUAutomaticallyUpdate"; NSString *const SUAllowsAutomaticUpdatesKey = @"SUAllowsAutomaticUpdates"; NSString *const SUEnableSystemProfilingKey = @"SUEnableSystemProfiling"; @@ -59,6 +61,7 @@ NSString *const SURelaunchToolNameKey = @"SURelaunchToolName"; NSString *const SUAppcastAttributeDeltaFrom = @"sparkle:deltaFrom"; NSString *const SUAppcastAttributeDSASignature = @"sparkle:dsaSignature"; +NSString *const SUAppcastAttributeEDSignature = @"sparkle:edSignature"; NSString *const SUAppcastAttributeShortVersionString = @"sparkle:shortVersionString"; NSString *const SUAppcastAttributeVersion = @"sparkle:version"; NSString *const SUAppcastAttributeOsType = @"sparkle:os"; diff --git a/generate_appcast/Appcast-Bridging-Header.h b/generate_appcast/Appcast-Bridging-Header.h index 916d1e79..4b8b160e 100644 --- a/generate_appcast/Appcast-Bridging-Header.h +++ b/generate_appcast/Appcast-Bridging-Header.h @@ -6,3 +6,4 @@ #import "SUUnarchiver.h" #import "SUBinaryDeltaUnarchiver.h" #import "SUBinaryDeltaCreate.h" +#import "ed25519.h" // Run `git submodule update --init` if you get an error here diff --git a/generate_appcast/Appcast.swift b/generate_appcast/Appcast.swift index 686e7372..0f4ff293 100644 --- a/generate_appcast/Appcast.swift +++ b/generate_appcast/Appcast.swift @@ -14,10 +14,11 @@ func makeError(code: SUError, _ description: String) -> NSError { ]); } -func makeAppcast(archivesSourceDir: URL, privateKey: SecKey, verbose: Bool) throws -> [String:[ArchiveItem]] { +func makeAppcast(archivesSourceDir: URL, keys: PrivateKeys, verbose: Bool) throws -> [String:[ArchiveItem]] { + let cacheDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("Sparkle_generate_appcast"); let comparator = SUStandardVersionComparator(); - let allUpdates = (try unarchiveUpdates(archivesSourceDir: archivesSourceDir, verbose:verbose)) + let allUpdates = (try unarchiveUpdates(archivesSourceDir: archivesSourceDir, archivesDestDir: cacheDir, verbose:verbose)) .sorted(by: { .orderedDescending == comparator.compareVersion($0.version, toVersion:$1.version) }) @@ -33,11 +34,31 @@ func makeAppcast(archivesSourceDir: URL, privateKey: SecKey, verbose: Bool) thro for update in allUpdates { group.enter(); DispatchQueue.global().async { - do { - update.dsaSignature = try dsaSignature(path: update.archivePath, privateKey: privateKey); - } catch { - print(update, error); + if let privateDSAKey = keys.privateDSAKey { + do { + update.dsaSignature = try dsaSignature(path: update.archivePath, privateDSAKey: privateDSAKey); + } catch { + print(update, error); + } + } else if update.supportsDSA { + print("Note: did not sign with legacy DSA \(update.archivePath.path) because private DSA key file was not specified"); } + if let publicEdKey = update.publicEdKey { + if let privateEdKey = keys.privateEdKey, let expectedPublicKey = keys.publicEdKey { + if publicEdKey == expectedPublicKey { + do { + update.edSignature = try edSignature(path: update.archivePath, publicEdKey: publicEdKey, privateEdKey: privateEdKey); + } catch { + print(update, error); + } + } else { + print("Warning: SUPublicEDKey in the app \(update.archivePath.path) does not match key EdDSA in the Keychain. Run generate_keys and update Info.plist to match"); + } + } else { + print("Warning: could not sign \(update.archivePath.path) due to lack of private EdDSA key"); + } + } + group.leave(); } @@ -63,16 +84,29 @@ func makeAppcast(archivesSourceDir: URL, privateKey: SecKey, verbose: Bool) thro var numDeltas = 0; let appBaseName = latestItem.appPath.deletingPathExtension().lastPathComponent; for item in updates { + if numDeltas > maxDeltas { + break; + } + // No downgrades if .orderedAscending != comparator.compareVersion(item.version, toVersion: latestItem.version) { continue; } + // Old version will not be able to verify the new version + if !item.supportsDSA && item.publicEdKey == nil { + continue; + } let deltaBaseName = appBaseName + latestItem.version + "-" + item.version; let deltaPath = archivesSourceDir.appendingPathComponent(deltaBaseName).appendingPathExtension("delta"); var delta:DeltaUpdate; - if !FileManager.default.fileExists(atPath: deltaPath.path) { + let ignoreMarkerPath = cacheDir.appendingPathComponent(deltaPath.lastPathComponent).appendingPathExtension(".ignore"); + let fm = FileManager.default; + if fm.fileExists(atPath: ignoreMarkerPath.path) { + continue; + } + if !fm.fileExists(atPath: deltaPath.path) { do { delta = try DeltaUpdate.create(from: item, to: latestItem, archivePath: deltaPath); } catch { @@ -83,23 +117,37 @@ func makeAppcast(archivesSourceDir: URL, privateKey: SecKey, verbose: Bool) thro delta = DeltaUpdate(fromVersion: item.version, archivePath: deltaPath); } - // Require delta to be a bit smaller - if delta.fileSize / 7 < latestItem.fileSize / 8 { - numDeltas += 1; - if numDeltas > maxDeltas { - break; - } + numDeltas += 1; - group.enter(); - DispatchQueue.global().async { + // Require delta to be a bit smaller + if delta.fileSize / 7 > latestItem.fileSize / 8 { + markDeltaAsIgnored(delta: delta, markerPath: ignoreMarkerPath) + continue; + } + + group.enter(); + DispatchQueue.global().async { + if item.supportsDSA, let privateDSAKey = keys.privateDSAKey { do { - delta.dsaSignature = try dsaSignature(path: deltaPath, privateKey: privateKey); - latestItem.deltas.append(delta); + delta.dsaSignature = try dsaSignature(path: deltaPath, privateDSAKey: privateDSAKey); } catch { print(delta.archivePath.lastPathComponent, error); } - group.leave(); } + if let publicEdKey = item.publicEdKey, let privateEdKey = keys.privateEdKey { + do { + delta.edSignature = try edSignature(path: deltaPath, publicEdKey: publicEdKey, privateEdKey: privateEdKey); + } catch { + print(delta.archivePath.lastPathComponent, error); + } + } + if delta.dsaSignature != nil || delta.edSignature != nil { + latestItem.deltas.append(delta); + } else { + markDeltaAsIgnored(delta: delta, markerPath: ignoreMarkerPath) + print("Delta \(delta.archivePath.path) ignored, because it could not be signed"); + } + group.leave(); } } } @@ -109,3 +157,8 @@ func makeAppcast(archivesSourceDir: URL, privateKey: SecKey, verbose: Bool) thro return updatesByAppcast; } + +func markDeltaAsIgnored(delta: DeltaUpdate, markerPath: URL) { + let _ = try? FileManager.default.removeItem(at: delta.archivePath) + let _ = try? Data.init().write(to: markerPath); // 0-sized file +} diff --git a/generate_appcast/ArchiveItem.swift b/generate_appcast/ArchiveItem.swift index 4cee60bf..5fb4aa29 100644 --- a/generate_appcast/ArchiveItem.swift +++ b/generate_appcast/ArchiveItem.swift @@ -9,6 +9,7 @@ class DeltaUpdate { let fromVersion: String; let archivePath: URL; var dsaSignature: String?; + var edSignature: String?; init(fromVersion: String, archivePath: URL) { self.archivePath = archivePath; @@ -38,41 +39,57 @@ class ArchiveItem: CustomStringConvertible { let archivePath: URL; let appPath: URL; let feedURL: URL?; + let publicEdKey: Data?; + let supportsDSA: Bool; let archiveFileAttributes: [FileAttributeKey:Any]; var deltas: [DeltaUpdate]; var dsaSignature: String?; + var edSignature: String?; - init(version: String, shortVersion: String?, feedURL: URL?, minimumSystemVersion: String?, appPath: URL, archivePath: URL) throws { + init(version: String, shortVersion: String?, feedURL: URL?, minimumSystemVersion: String?, publicEdKey: String?, supportsDSA: Bool, appPath: URL, archivePath: URL) throws { self.version = version; self._shortVersion = shortVersion; self.feedURL = feedURL; self.minimumSystemVersion = minimumSystemVersion ?? "10.7"; self.archivePath = archivePath; self.appPath = appPath; + self.supportsDSA = supportsDSA; + if let publicEdKey = publicEdKey { + self.publicEdKey = Data(base64Encoded: publicEdKey); + } else { + self.publicEdKey = nil; + } self.archiveFileAttributes = try FileManager.default.attributesOfItem(atPath: self.archivePath.path); self.deltas = []; } convenience init(fromArchive archivePath: URL, unarchivedDir: URL) throws { - let items = try FileManager.default.contentsOfDirectory(atPath: unarchivedDir.path) - .filter({ !$0.hasPrefix(".") }) - .map({ unarchivedDir.appendingPathComponent($0) }) + let resourceKeys = [URLResourceKey.typeIdentifierKey] + let items = try FileManager.default.contentsOfDirectory(at: unarchivedDir, includingPropertiesForKeys: resourceKeys, options: .skipsHiddenFiles) - let apps = items.filter({ $0.pathExtension == "app" }); - if apps.count > 0 { - if apps.count > 1 { - throw makeError(code: .unarchivingError, "Too many apps in \(unarchivedDir.path) \(apps)"); + let bundles = items.filter({ + if let resourceValues = try? $0.resourceValues(forKeys: Set(resourceKeys)) { + return UTTypeConformsTo(resourceValues.typeIdentifier! as CFString, kUTTypeBundle) + } else { + return false + } + }); + if bundles.count > 0 { + if bundles.count > 1 { + throw makeError(code: .unarchivingError, "Too many bundles in \(unarchivedDir.path) \(bundles)"); } - let appPath = apps[0]; + let appPath = bundles[0]; guard let infoPlist = NSDictionary(contentsOf: appPath.appendingPathComponent("Contents/Info.plist")) else { throw makeError(code: .unarchivingError, "No plist \(appPath.path)"); } guard let version = infoPlist[kCFBundleVersionKey] as? String else { - throw makeError(code: .unarchivingError, "No Version \(kCFBundleVersionKey) \(appPath)"); + throw makeError(code: .unarchivingError, "No Version \(kCFBundleVersionKey as String? ?? "missing kCFBundleVersionKey") \(appPath)"); } let shortVersion = infoPlist["CFBundleShortVersionString"] as? String; + let publicEdKey = infoPlist[SUPublicEDKeyKey] as? String; + let supportsDSA = infoPlist[SUPublicDSAKeyKey] != nil || infoPlist[SUPublicDSAKeyFileKey] != nil; var feedURL:URL? = nil; if let feedURLStr = infoPlist["SUFeedURL"] as? String { @@ -80,11 +97,13 @@ class ArchiveItem: CustomStringConvertible { } try self.init(version: version, - shortVersion: shortVersion, - feedURL: feedURL, - minimumSystemVersion: infoPlist["LSMinimumSystemVersion"] as? String, - appPath: appPath, - archivePath: archivePath); + shortVersion: shortVersion, + feedURL: feedURL, + minimumSystemVersion: infoPlist["LSMinimumSystemVersion"] as? String, + publicEdKey: publicEdKey, + supportsDSA: supportsDSA, + appPath: appPath, + archivePath: archivePath); } else { throw makeError(code: .missingUpdateError, "No supported items in \(unarchivedDir) \(items) [note: only .app bundles are supported]"); } @@ -118,7 +137,7 @@ class ArchiveItem: CustomStringConvertible { var fileSize : Int64 { return (self.archiveFileAttributes[.size] as! NSNumber).int64Value; } - + private var releaseNotesPath : URL? { var basename = self.archivePath.deletingPathExtension(); if basename.pathExtension == "tar" { // tar.gz diff --git a/generate_appcast/FeedXML.swift b/generate_appcast/FeedXML.swift index 29e95266..84e3011f 100644 --- a/generate_appcast/FeedXML.swift +++ b/generate_appcast/FeedXML.swift @@ -23,7 +23,6 @@ func findOrCreateElement(name: String, parent: XMLElement) -> XMLElement { return element; } let element = XMLElement(name: name); - linebreak(parent); parent.addChild(element); return element; } @@ -32,10 +31,6 @@ func text(_ text: String) -> XMLNode { return XMLNode.text(withStringValue: text) as! XMLNode } -func linebreak(_ element: XMLElement) { - element.addChild(text("\n")); -} - func writeAppcast(appcastDestPath: URL, updates: [ArchiveItem]) throws { let appBaseName = updates[0].appPath.deletingPathExtension().lastPathComponent; @@ -70,9 +65,7 @@ func writeAppcast(appcastDestPath: URL, updates: [ArchiveItem]) throws { channel = channelNodes[0] as! XMLElement; } else { channel = XMLElement(name: "channel"); - linebreak(channel); channel.addChild(XMLElement.element(withName: "title", stringValue: appBaseName) as! XMLElement); - linebreak(root); root.addChild(channel); } @@ -90,18 +83,15 @@ func writeAppcast(appcastDestPath: URL, updates: [ArchiveItem]) throws { if createNewItem { item = XMLElement.element(withName: "item") as! XMLElement; - linebreak(channel); channel.addChild(item); } else { item = existingItems[0] as! XMLElement; } if nil == findElement(name: "title", parent: item) { - linebreak(item); item.addChild(XMLElement.element(withName: "title", stringValue: update.shortVersion) as! XMLElement); } if nil == findElement(name: "pubDate", parent: item) { - linebreak(item); item.addChild(XMLElement.element(withName: "pubDate", stringValue: update.pubDate) as! XMLElement); } @@ -112,28 +102,25 @@ func writeAppcast(appcastDestPath: URL, updates: [ArchiveItem]) throws { descElement.setChildren([cdata]); } - var minVer = findElement(name: "sparkle:minimumSystemVersion", parent: item); + var minVer = findElement(name: SUAppcastElementMinimumSystemVersion, parent: item); if nil == minVer { - minVer = XMLElement.element(withName: "sparkle:minimumSystemVersion", uri: sparkleNS) as? XMLElement; - linebreak(item); + minVer = XMLElement.element(withName: SUAppcastElementMinimumSystemVersion, uri: sparkleNS) as? XMLElement; item.addChild(minVer!); } minVer?.setChildren([text(update.minimumSystemVersion)]); - let relElement = findElement(name: "sparkle:releaseNotesLink", parent: item); + let relElement = findElement(name: SUAppcastElementReleaseNotesLink, parent: item); if let url = update.releaseNotesURL { if nil == relElement { - linebreak(item); - item.addChild(XMLElement.element(withName:"sparkle:releaseNotesLink", stringValue: url.absoluteString) as! XMLElement); + item.addChild(XMLElement.element(withName: SUAppcastElementReleaseNotesLink, stringValue: url.absoluteString) as! XMLElement); } } else if let childIndex = relElement?.index { item.removeChild(at: childIndex); } - + var enclosure = findElement(name: "enclosure", parent: item); if nil == enclosure { enclosure = XMLElement.element(withName: "enclosure") as? XMLElement; - linebreak(item); item.addChild(enclosure!); } @@ -142,21 +129,23 @@ func writeAppcast(appcastDestPath: URL, updates: [ArchiveItem]) throws { }; var attributes = [ XMLNode.attribute(withName: "url", stringValue: archiveURL) as! XMLNode, - XMLNode.attribute(withName: "sparkle:version", uri: sparkleNS, stringValue: update.version) as! XMLNode, - XMLNode.attribute(withName: "sparkle:shortVersionString", uri: sparkleNS, stringValue: update.shortVersion) as! XMLNode, + XMLNode.attribute(withName: SUAppcastAttributeVersion, uri: sparkleNS, stringValue: update.version) as! XMLNode, + XMLNode.attribute(withName: SUAppcastAttributeShortVersionString, uri: sparkleNS, stringValue: update.shortVersion) as! XMLNode, XMLNode.attribute(withName: "length", stringValue: String(update.fileSize)) as! XMLNode, XMLNode.attribute(withName: "type", stringValue: update.mimeType) as! XMLNode, ]; + if let sig = update.edSignature { + attributes.append(XMLNode.attribute(withName: SUAppcastAttributeEDSignature, uri: sparkleNS, stringValue: sig) as! XMLNode); + } if let sig = update.dsaSignature { - attributes.append(XMLNode.attribute(withName: "sparkle:dsaSignature", uri: sparkleNS, stringValue: sig) as! XMLNode); + attributes.append(XMLNode.attribute(withName: SUAppcastAttributeDSASignature, uri: sparkleNS, stringValue: sig) as! XMLNode); } enclosure!.attributes = attributes; if update.deltas.count > 0 { - var deltas = findElement(name: "sparkle:deltas", parent: item); + var deltas = findElement(name: SUAppcastElementDeltas, parent: item); if nil == deltas { - deltas = XMLElement.element(withName: "sparkle:deltas", uri: sparkleNS) as? XMLElement; - linebreak(item); + deltas = XMLElement.element(withName: SUAppcastElementDeltas, uri: sparkleNS) as? XMLElement; item.addChild(deltas!); } else { deltas!.setChildren([]); @@ -164,26 +153,24 @@ func writeAppcast(appcastDestPath: URL, updates: [ArchiveItem]) throws { for delta in update.deltas { var attributes = [ XMLNode.attribute(withName: "url", stringValue: URL(string: delta.archivePath.lastPathComponent.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlPathAllowed)!, relativeTo: update.archiveURL)!.absoluteString) as! XMLNode, - XMLNode.attribute(withName: "sparkle:version", uri: sparkleNS, stringValue: update.version) as! XMLNode, - XMLNode.attribute(withName: "sparkle:shortVersionString", uri: sparkleNS, stringValue: update.shortVersion) as! XMLNode, - XMLNode.attribute(withName: "sparkle:deltaFrom", uri: sparkleNS, stringValue: delta.fromVersion) as! XMLNode, + XMLNode.attribute(withName: SUAppcastAttributeVersion, uri: sparkleNS, stringValue: update.version) as! XMLNode, + XMLNode.attribute(withName: SUAppcastAttributeShortVersionString, uri: sparkleNS, stringValue: update.shortVersion) as! XMLNode, + XMLNode.attribute(withName: SUAppcastAttributeDeltaFrom, uri: sparkleNS, stringValue: delta.fromVersion) as! XMLNode, XMLNode.attribute(withName: "length", stringValue: String(delta.fileSize)) as! XMLNode, XMLNode.attribute(withName: "type", stringValue: "application/octet-stream") as! XMLNode, - ]; - if let sig = delta.dsaSignature { - attributes.append(XMLNode.attribute(withName: "sparkle:dsaSignature", uri: sparkleNS, stringValue: sig) as! XMLNode); + ]; + if let sig = delta.edSignature { + attributes.append(XMLNode.attribute(withName: SUAppcastAttributeEDSignature, uri: sparkleNS, stringValue: sig) as! XMLNode); + } + if let sig = delta.dsaSignature { + attributes.append(XMLNode.attribute(withName: SUAppcastAttributeDSASignature, uri: sparkleNS, stringValue: sig) as! XMLNode); } - linebreak(deltas!); deltas!.addChild(XMLNode.element(withName: "enclosure", children: nil, attributes: attributes) as! XMLElement); } } - if createNewItem { - linebreak(item); - linebreak(channel); - } } - let options = XMLNode.Options.nodeCompactEmptyElement; + let options: XMLNode.Options = [.nodeCompactEmptyElement, .nodePrettyPrint]; let docData = doc.xmlData(options:options); let _ = try XMLDocument(data: docData, options:XMLNode.Options()); // Verify that it was generated correctly, which does not always happen! try docData.write(to: appcastDestPath); diff --git a/generate_appcast/DSASignature.swift b/generate_appcast/Signatures.swift similarity index 69% rename from generate_appcast/DSASignature.swift rename to generate_appcast/Signatures.swift index 7040d54c..2a4b8594 100644 --- a/generate_appcast/DSASignature.swift +++ b/generate_appcast/Signatures.swift @@ -5,7 +5,19 @@ import Foundation -func loadPrivateKey(at privateKeyURL: URL) throws -> SecKey { +struct PrivateKeys { + var privateDSAKey: SecKey?; + var privateEdKey: Data?; + var publicEdKey: Data?; + + init(privateDSAKey: SecKey?, privateEdKey: Data?, publicEdKey: Data?) { + self.privateDSAKey = privateDSAKey; + self.privateEdKey = privateEdKey; + self.publicEdKey = publicEdKey; + } +} + +func loadPrivateDSAKey(at privateKeyURL: URL) throws -> SecKey { let data = try Data(contentsOf: privateKeyURL); var cfitems: CFArray? = nil; @@ -25,13 +37,13 @@ func loadPrivateKey(at privateKeyURL: URL) throws -> SecKey { return (cfitems! as NSArray)[0] as! SecKey; } -func loadPrivateKey(named keyName: String, fromKeychainAt keychainURL: URL) throws -> SecKey { +func loadPrivateDSAKey(named keyName: String, fromKeychainAt keychainURL: URL) throws -> SecKey { var keychain: SecKeychain? = nil - + guard SecKeychainOpen(keychainURL.path, &keychain) == errSecSuccess, keychain != nil else { throw NSError(domain: SUSparkleErrorDomain, code: Int(OSStatus(SUError.signatureError.rawValue)), userInfo: nil) } - + let query: [CFString: CFTypeRef] = [ kSecClass: kSecClassKey, kSecAttrKeyClass: kSecAttrKeyClassPrivate, @@ -40,16 +52,16 @@ func loadPrivateKey(named keyName: String, fromKeychainAt keychainURL: URL) thro kSecUseKeychain: keychain!, kSecReturnRef: kCFBooleanTrue ] - + var item: CFTypeRef? = nil guard SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess, item != nil else { throw NSError(domain: SUSparkleErrorDomain, code: Int(OSStatus(SUError.signatureError.rawValue)), userInfo: nil) } - + return item! as! SecKey } -func dsaSignature(path: URL, privateKey: SecKey) throws -> String { +func dsaSignature(path: URL, privateDSAKey: SecKey) throws -> String { var error: Unmanaged?; @@ -57,7 +69,7 @@ func dsaSignature(path: URL, privateKey: SecKey) throws -> String { let dataReadTransform = SecTransformCreateReadTransformWithReadStream(stream); let dataDigestTransform = SecDigestTransformCreate(kSecDigestSHA1, 20, nil); - guard let dataSignTransform = SecSignTransformCreate(privateKey, &error) else { + guard let dataSignTransform = SecSignTransformCreate(privateDSAKey, &error) else { print("can't use the key"); throw error!.takeRetainedValue(); } @@ -82,3 +94,21 @@ func dsaSignature(path: URL, privateKey: SecKey) throws -> String { } return resultData.base64EncodedString(); } + +func edSignature(path: URL, publicEdKey: Data, privateEdKey: Data) throws -> String { + assert(publicEdKey.count == 32) + assert(privateEdKey.count == 64) + let data = try Data.init(contentsOf: path, options: .mappedIfSafe); + let len = data.count; + var output = Data(count: 64); + output.withUnsafeMutableBytes({ (output: UnsafeMutablePointer) in + data.withUnsafeBytes({ (data: UnsafePointer) in + publicEdKey.withUnsafeBytes({ (publicEdKey: UnsafePointer) in + privateEdKey.withUnsafeBytes({ (privateEdKey: UnsafePointer) in + ed25519_sign(output, data, len, publicEdKey, privateEdKey) + }); + }); + }) + }); + return output.base64EncodedString(); +} diff --git a/generate_appcast/Unarchive.swift b/generate_appcast/Unarchive.swift index 3cd01b67..aa1e9729 100644 --- a/generate_appcast/Unarchive.swift +++ b/generate_appcast/Unarchive.swift @@ -13,7 +13,11 @@ func unarchive(itemPath:URL, archiveDestDir: URL, callback: @escaping (Error?) - _ = try? fileManager.createDirectory(at: tempDir, withIntermediateDirectories: true, attributes: [:]); do { - try fileManager.linkItem(at: itemPath, to: itemCopy); + do { + try fileManager.linkItem(at: itemPath, to: itemCopy); + } catch { + try fileManager.copyItem(at: itemPath, to: itemCopy); + } if let unarchiver = SUUnarchiver.unarchiver(forPath: itemCopy.path, updatingHostBundlePath:nil, decryptionPassword:nil) { unarchiver.unarchive(completionBlock: { (error: Error?) in if error != nil { @@ -39,8 +43,7 @@ func unarchive(itemPath:URL, archiveDestDir: URL, callback: @escaping (Error?) - } } -func unarchiveUpdates(archivesSourceDir: URL, verbose: Bool) throws -> [ArchiveItem] { - let archivesDestDir = archivesSourceDir.appendingPathComponent(".tmp"); +func unarchiveUpdates(archivesSourceDir: URL, archivesDestDir: URL, verbose: Bool) throws -> [ArchiveItem] { if verbose { print("Unarchiving to temp directory", archivesDestDir.path); } diff --git a/generate_appcast/main.swift b/generate_appcast/main.swift index 57ae99f2..a97d7ea6 100644 --- a/generate_appcast/main.swift +++ b/generate_appcast/main.swift @@ -12,50 +12,72 @@ var verbose = false; func printUsage() { let command = URL(fileURLWithPath: CommandLine.arguments.first!).lastPathComponent; - print("Generate appcast from a directory of Sparkle updates\n", - "Usage:\n", - " \(command) < -f private key path | -k keychain_path -n key_name > \n", - " e.g. \(command) -k ~/Library/Keychains/login.keychain -n 'My Private Key' archives/\n", - "\nOR (legacy)\n\n", - " \(command) \n", + print("Generate appcast from a directory of Sparkle update archives\n", + "Usage:\n", + " \(command) \n", + " e.g. \(command) ./my-app-release-zipfiles/\n", + "\nOR for old apps that have a DSA keys (deprecated):\n", + " \(command) \n", " e.g. \(command) dsa_priv.pem archives/\n", "\n", - " Appcast files and deltas will be written to the archives directory.\n", - " Note that pkg-based updates are not supported.\n" + "Appcast files and deltas will be written to the archives directory.\n", + "Note that pkg-based updates are not supported.\n" ) } +func loadPrivateKeys(_ privateDSAKey: SecKey?) -> PrivateKeys { + var privateEdKey: Data?; + var publicEdKey: Data?; + var item: CFTypeRef?; + let res = SecItemCopyMatching([ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: "https://sparkle-project.org", + kSecAttrAccount as String: "ed25519", + kSecAttrProtocol as String: kSecAttrProtocolSSH, + kSecReturnData as String: kCFBooleanTrue, + ] as CFDictionary, &item); + if res == errSecSuccess, let encoded = item as? Data, let keys = Data(base64Encoded: encoded) { + privateEdKey = keys[0..<64]; + publicEdKey = keys[64...]; + } else { + print("Warning: Private key not found in the Keychain (\(res)). Please run the generate_keys tool"); + } + return PrivateKeys(privateDSAKey: privateDSAKey, privateEdKey: privateEdKey, publicEdKey: publicEdKey); +} + func main() { let args = CommandLine.arguments; - if args.count < 3 { + if args.count < 2 { printUsage() exit(1) } - - let privateKey: SecKey - + + var privateDSAKey: SecKey? = nil; + + // this was typical usage for DSA keys if args.count == 3 || (args.count == 4 && args[1] == "-f") { // private key specified by filename let privateKeyURL = URL(fileURLWithPath: args.count == 3 ? args[1] : args[2]) - + do { - privateKey = try loadPrivateKey(at: privateKeyURL) + privateDSAKey = try loadPrivateDSAKey(at: privateKeyURL) } catch { print("Unable to load DSA private key from", privateKeyURL.path, "\n", error) exit(1) } } + // this is legacy for DSA keychain; probably very rarely used else if args.count == 6 && (args[1] == "-n" || args[1] == "-k") { // private key specified by keychain + key name let keyName: String let keychainURL: URL - + if args[1] == "-n" { if args[3] != "-k" { printUsage() exit(1) } - + keyName = args[2] keychainURL = URL(fileURLWithPath: args[4]) } @@ -64,28 +86,29 @@ func main() { printUsage() exit(1) } - + keyName = args[4] keychainURL = URL(fileURLWithPath: args[2]) } do { - privateKey = try loadPrivateKey(named: keyName, fromKeychainAt: keychainURL) + privateDSAKey = try loadPrivateDSAKey(named: keyName, fromKeychainAt: keychainURL) } catch { print("Unable to load DSA private key '\(keyName)' from keychain at", keychainURL.path, "\n", error) exit(1) } } - else { + else if args.count != 2 { printUsage() exit(1) } - + let archivesSourceDir = URL(fileURLWithPath: args.last!, isDirectory: true) + let keys = loadPrivateKeys(privateDSAKey) do { - let allUpdates = try makeAppcast(archivesSourceDir: archivesSourceDir, privateKey: privateKey, verbose:verbose); - + let allUpdates = try makeAppcast(archivesSourceDir: archivesSourceDir, keys: keys, verbose:verbose); + for (appcastFile, updates) in allUpdates { let appcastDestPath = URL(fileURLWithPath: appcastFile, relativeTo: archivesSourceDir); try writeAppcast(appcastDestPath:appcastDestPath, updates:updates);