diff --git a/Autoupdate/SUSignatureVerifier.h b/Autoupdate/SUSignatureVerifier.h index 2b027691..68193d25 100644 --- a/Autoupdate/SUSignatureVerifier.h +++ b/Autoupdate/SUSignatureVerifier.h @@ -24,14 +24,19 @@ NS_ASSUME_NONNULL_BEGIN SPU_OBJC_DIRECT_MEMBERS @interface SUSignatureVerifier : NSObject +// Helper for verifying downloaded updates + (BOOL)validatePath:(NSString *)path withSignatures:(SUSignatures *)signatures withPublicKeys:(SUPublicKeys *)pkeys verifierInformation:(SPUVerifierInformation * _Nullable)verifierInformation error:(NSError * __autoreleasing *)error; - (instancetype)init NS_UNAVAILABLE; - (instancetype)initWithPublicKeys:(SUPublicKeys *)pkeys; +// Used for verifying downloaded updates - (BOOL)verifyFileAtPath:(NSString *)path signatures:(SUSignatures *)signatures verifierInformation:(SPUVerifierInformation * _Nullable)verifierInformation error:(NSError * __autoreleasing *)error; +// Used for verifying non-update data (like release notes) +- (BOOL)verifyData:(NSData *)data signatures:(SUSignatures *)signatures fileKind:(NSString *)fileKind verifierInformation:(SPUVerifierInformation * _Nullable)verifierInformation error:(NSError * __autoreleasing *)error; + @end NS_ASSUME_NONNULL_END diff --git a/Autoupdate/SUSignatureVerifier.m b/Autoupdate/SUSignatureVerifier.m index 6110f6f9..d962e995 100644 --- a/Autoupdate/SUSignatureVerifier.m +++ b/Autoupdate/SUSignatureVerifier.m @@ -34,14 +34,6 @@ + (BOOL)validatePath:(NSString *)path withSignatures:(SUSignatures *)signatures withPublicKeys:(SUPublicKeys *)pkeys verifierInformation:(SPUVerifierInformation * _Nullable)verifierInformation error:(NSError * __autoreleasing *)error { SUSignatureVerifier *verifier = [(SUSignatureVerifier *)[self alloc] initWithPublicKeys:pkeys]; - - if (verifier == nil) { - if (error != NULL) { - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to create SUSignatureVerifier instance" }]; - } - return NO; - } - return [verifier verifyFileAtPath:path signatures:signatures verifierInformation:verifierInformation error:error]; } @@ -94,16 +86,45 @@ - (BOOL)verifyFileAtPath:(NSString *)path signatures:(SUSignatures *)signatures verifierInformation:(SPUVerifierInformation * _Nullable)verifierInformation error:(NSError * __autoreleasing *)error { - if (!path || !path.length) { - if (error != NULL) { - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"Path passed to verify has zero length and is not valid" }]; + // Data is used only in the case where ed25519 signature is present + NSData *data; + if (signatures.ed25519SignatureStatus != SUSigningInputStatusPresent) { + data = nil; + } else { + NSError *dataError = nil; + data = [NSData dataWithContentsOfFile:path options:NSDataReadingMappedIfSafe error:&dataError]; + + if (data == nil || data.length == 0) { + SULog(SULogLevelError, @"Failed to load file %@: %@", path, dataError); + + if (error != NULL) { + NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + userInfo[NSLocalizedDescriptionKey] = [NSString stringWithFormat:@"Failed to load file: %@", path]; + if (dataError != nil) { + userInfo[NSUnderlyingErrorKey] = dataError; + } + + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:[userInfo copy]]; + } + + return NO; } - return NO; } + + return [self verifyData:data signatures:signatures fileKind:@"update" fromPath:path verifierInformation:verifierInformation error:error]; +} +- (BOOL)verifyData:(NSData *)data signatures:(SUSignatures *)signatures fileKind:(NSString *)fileKind verifierInformation:(SPUVerifierInformation * _Nullable)verifierInformation error:(NSError * __autoreleasing *)error +{ + return [self verifyData:data signatures:signatures fileKind:fileKind fromPath:nil verifierInformation:verifierInformation error:error]; +} + +// Note the path must be provided for verifying update archives +- (BOOL)verifyData:(NSData * _Nullable)data signatures:(SUSignatures *)signatures fileKind:(NSString *)fileKind fromPath:(NSString * _Nullable)path verifierInformation:(SPUVerifierInformation * _Nullable)verifierInformation error:(NSError * __autoreleasing *)error SPU_OBJC_DIRECT +{ if (!signatures) { if (error != NULL) { - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"No signatures given to verifyFileAtPath" }]; + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"No signatures given to verify data for %@", fileKind] }]; } return NO; } @@ -111,12 +132,12 @@ switch (_pubKeys.ed25519PubKeyStatus) { case SUSigningInputStatusAbsent: if (signatures.ed25519SignatureStatus != SUSigningInputStatusAbsent) { - SULog(SULogLevelDefault, @"The update has an EdDSA signature, but it won't be used, because the old app doesn't have an EdDSA public key"); + SULog(SULogLevelDefault, @"The %@ has an EdDSA signature, but it won't be used, because the old app doesn't have an EdDSA public key", fileKind); } break; case SUSigningInputStatusInvalid: if (signatures.ed25519SignatureStatus != SUSigningInputStatusAbsent) { - NSString *message = @"The update has an EdDSA signature, but the app has an invalid EdDSA public key, so the update will automatically be rejected."; + NSString *message = [NSString stringWithFormat:@"The %@ has an EdDSA signature, but the app has an invalid EdDSA public key, so the %@ will automatically be rejected.", fileKind, fileKind]; SULog(SULogLevelError, @"%@", message); if (error != NULL) { @@ -125,12 +146,12 @@ return NO; } - SULog(SULogLevelDefault, @"The app has an invalid EdDSA public key, but there is no EdDSA signature in the update. Falling back to DSA."); + SULog(SULogLevelDefault, @"The app has an invalid EdDSA public key, but there is no EdDSA signature in the %@. Falling back to DSA.", fileKind); break; case SUSigningInputStatusPresent: switch (signatures.ed25519SignatureStatus) { case SUSigningInputStatusAbsent: { - NSString *message = @"The app has an EdDSA public key, but there is no EdDSA signature in the update, so the update will be rejected."; + NSString *message = [NSString stringWithFormat:@"The app has an EdDSA public key, but there is no EdDSA signature in the %@, so the %@ will be rejected.", fileKind, fileKind]; SULog(SULogLevelError, @"%@", message); if (error != NULL) { @@ -140,7 +161,7 @@ return NO; } case SUSigningInputStatusInvalid: { - NSString *message = @"The update has an EdDSA signature, but it's invalid, so the update will automatically be rejected."; + NSString *message = [NSString stringWithFormat:@"The %@ has an EdDSA signature, but it's invalid, so the %@ will automatically be rejected.", fileKind, fileKind]; SULog(SULogLevelError, @"%@", message); @@ -150,23 +171,7 @@ return NO; } case SUSigningInputStatusPresent: { - NSError *dataError = nil; - NSData *data = [NSData dataWithContentsOfFile:path options:NSDataReadingMappedAlways error:&dataError]; - if (!data || !data.length) { - SULog(SULogLevelError, @"Failed to load file %@: %@", path, dataError); - - if (error != NULL) { - NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; - userInfo[NSLocalizedDescriptionKey] = [NSString stringWithFormat:@"Failed to load file: %@", path]; - if (dataError != nil) { - userInfo[NSUnderlyingErrorKey] = dataError; - } - - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:[userInfo copy]]; - } - - return NO; - } + assert(data != nil); if (ed25519_verify(signatures.ed25519Signature, data.bytes, data.length, _pubKeys.ed25519PubKey)) { SULog(SULogLevelDefault, @"OK: EdDSA signature is correct"); #if SPARKLE_BUILD_LEGACY_DSA_SUPPORT @@ -178,34 +183,38 @@ return YES; } } else { - NSMutableString *message = [NSMutableString stringWithString:@"EdDSA signature does not match. Data of the update file being checked is different than data that has been signed, or the public key and the private key are not from the same set."]; + NSMutableString *message = [NSMutableString stringWithFormat:@"EdDSA signature does not match. Data of the %@ being checked is different than data that has been signed, or the public key and the private key are not from the same set.", fileKind]; // Elaborate on the error message if we have more information about the download archive + // If there is verifierInformation it must be for a downloaded update (rather than feed or release notes) if (verifierInformation != nil) { BOOL reportedDiscrepancy = NO; + NSString *downloadedFileDescription = (path != nil) ? [NSString stringWithFormat:@"%@ (%@)", fileKind, path.lastPathComponent] : fileKind; + if (verifierInformation.expectedContentLength > 0 && verifierInformation.actualContentLength > 0) { if (verifierInformation.expectedContentLength != verifierInformation.actualContentLength) { - [message appendFormat:@" The downloaded update (%@) is likely different than the signed archive because the expected content length from the appcast item (%llu bytes) differs from the downloaded archive length (%llu bytes).", path.lastPathComponent, verifierInformation.expectedContentLength, verifierInformation.actualContentLength]; + [message appendFormat:@" The downloaded %@ is likely different than the signed file because the expected content length from the appcast item (%llu bytes) differs from the downloaded file length (%llu bytes).", downloadedFileDescription, verifierInformation.expectedContentLength, verifierInformation.actualContentLength]; reportedDiscrepancy = YES; } } NSString *actualVersion = verifierInformation.actualVersion; if (actualVersion != nil && ![verifierInformation.expectedVersion isEqualToString:actualVersion]) { - [message appendFormat:@" The downloaded update (%@) also has a CFBundleVersion (%@) which differs from the %@ in the appcast item (%@).", path.lastPathComponent, actualVersion, SUAppcastAttributeVersion, verifierInformation.expectedVersion]; + [message appendFormat:@" The downloaded %@ also has a CFBundleVersion (%@) which differs from the %@ in the appcast item (%@).", downloadedFileDescription, actualVersion, SUAppcastAttributeVersion, verifierInformation.expectedVersion]; reportedDiscrepancy = YES; } if (!reportedDiscrepancy && verifierInformation.expectedContentLength > 0) { - [message appendFormat:@" The downloaded update (%@) is likely not signed correctly because the archive has the expected content length (%llu bytes)%@ which matches the appcast item.", path.lastPathComponent, verifierInformation.actualContentLength, (actualVersion == nil ? @"" : [NSString stringWithFormat:@" and CFBundleVersion (%@)", actualVersion])]; + [message appendFormat:@" The downloaded %@ is likely not signed correctly because the file has the expected content length (%llu bytes)%@ which matches the appcast item.", downloadedFileDescription, verifierInformation.actualContentLength, (actualVersion == nil ? @"" : [NSString stringWithFormat:@" and CFBundleVersion (%@)", actualVersion])]; } } SULog(SULogLevelError, @"%@", [message copy]); #if SPARKLE_BUILD_LEGACY_DSA_SUPPORT - if (signatures.dsaSignatureStatus != SUSigningInputStatusAbsent) { + // Legacy DSA verification is only applicable if archive file path is provided + if (signatures.dsaSignatureStatus != SUSigningInputStatusAbsent && path != nil) { SULog(SULogLevelDefault, @"DSA signature won't be checked, because EdDSA verification has already failed"); } #endif @@ -222,14 +231,15 @@ } #if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + // Legacy DSA verification is only for downloaded updates switch (_pubKeys.dsaPubKeyStatus) { case SUSigningInputStatusAbsent: - if (signatures.dsaSignatureStatus != SUSigningInputStatusAbsent) { + if (signatures.dsaSignatureStatus != SUSigningInputStatusAbsent && path != nil) { SULog(SULogLevelDefault, @"The update has a DSA signature, but it can't be used, because the old app doesn't have a DSA public key"); } break; case SUSigningInputStatusInvalid: - if (signatures.dsaSignatureStatus != SUSigningInputStatusAbsent) { + if (signatures.dsaSignatureStatus != SUSigningInputStatusAbsent && path != nil) { // We will have already logged an error for this failure when the public key was read in, so just do an informational log here. NSString *message = @"The update has a DSA signature, but the app has an invalid DSA public key, so the update will automatically be rejected."; @@ -260,7 +270,7 @@ return NO; } case SUSigningInputStatusPresent: { - NSInputStream *dataInputStream = [NSInputStream inputStreamWithFileAtPath:path]; + NSInputStream *dataInputStream = (path != nil) ? [NSInputStream inputStreamWithFileAtPath:(NSString * _Nonnull)path] : nil; return [self verifyDSASignatureOfStream:dataInputStream dsaSignature:signatures.dsaSignature error:error]; } } @@ -283,7 +293,7 @@ if (error != NULL) { // Use generic failure - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"EdDSA and DSA verification for the update has failed" }]; + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"EdDSA and DSA verification for the %@ has failed", fileKind] }]; } return NO; diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index 79a491ae..5817eff9 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -117,7 +117,6 @@ 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 /* 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 */; }; @@ -243,9 +242,9 @@ 725F97841C8AA90000265BE4 /* SUPopUpTitlebarUserDriver.m in Sources */ = {isa = PBXBuildFile; fileRef = 725F97831C8AA90000265BE4 /* SUPopUpTitlebarUserDriver.m */; }; 725F97A51C8B304D00265BE4 /* SUInstallUpdateViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 725F97A31C8B304D00265BE4 /* SUInstallUpdateViewController.m */; }; 725F97A61C8B304D00265BE4 /* SUInstallUpdateViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 725F97A41C8B304D00265BE4 /* SUInstallUpdateViewController.xib */; }; - 72666DC62B0B28F4001511B0 /* secret.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72666DC52B0B28F4001511B0 /* secret.swift */; }; - 72666DC72B0B28F4001511B0 /* secret.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72666DC52B0B28F4001511B0 /* secret.swift */; }; - 72666DC82B0B28F4001511B0 /* secret.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72666DC52B0B28F4001511B0 /* secret.swift */; }; + 72666DC62B0B28F4001511B0 /* Secret.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72666DC52B0B28F4001511B0 /* Secret.swift */; }; + 72666DC72B0B28F4001511B0 /* Secret.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72666DC52B0B28F4001511B0 /* Secret.swift */; }; + 72666DC82B0B28F4001511B0 /* Secret.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72666DC52B0B28F4001511B0 /* Secret.swift */; }; 7267E5751D3D895B00D1BF90 /* SUBinaryDeltaApply.m in Sources */ = {isa = PBXBuildFile; fileRef = 7267E56F1D3D895B00D1BF90 /* SUBinaryDeltaApply.m */; }; 7267E5761D3D895B00D1BF90 /* SUBinaryDeltaApply.m in Sources */ = {isa = PBXBuildFile; fileRef = 7267E56F1D3D895B00D1BF90 /* SUBinaryDeltaApply.m */; }; 7267E5771D3D895B00D1BF90 /* SUBinaryDeltaCommon.m in Sources */ = {isa = PBXBuildFile; fileRef = 7267E5711D3D895B00D1BF90 /* SUBinaryDeltaCommon.m */; }; @@ -394,6 +393,22 @@ 72B767E71C9CFD7200A07552 /* SPUAutomaticUpdateDriver.m in Sources */ = {isa = PBXBuildFile; fileRef = 72B767E51C9CFD7200A07552 /* SPUAutomaticUpdateDriver.m */; }; 72BC6C3D275027BF0083F14B /* SparkleTestCodeSign_apfs.dmg in Resources */ = {isa = PBXBuildFile; fileRef = 72BC6C3C275027BF0083F14B /* SparkleTestCodeSign_apfs.dmg */; }; 72BEBFEF1D7287570019146B /* SUSpotlightImporterTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72BEBFEE1D7287560019146B /* SUSpotlightImporterTest.swift */; }; + 72C56E042EFB45B10005A484 /* SUSignatureVerifier.m in Sources */ = {isa = PBXBuildFile; fileRef = 7267E59B1D3D8A5A00D1BF90 /* SUSignatureVerifier.m */; }; + 72C56E052EFB45BD0005A484 /* SPUVerifierInformation.m in Sources */ = {isa = PBXBuildFile; fileRef = 72D04F3C2B094C8400A6DEAA /* SPUVerifierInformation.m */; }; + 72C56E062EFB45C80005A484 /* libed25519.a in Frameworks */ = {isa = PBXBuildFile; fileRef = EA1E282D22B660BE004AA304 /* libed25519.a */; }; + 72C56E092EFDFB850005A484 /* SPUExtractAppcast.m in Sources */ = {isa = PBXBuildFile; fileRef = 72C56E082EFDFB850005A484 /* SPUExtractAppcast.m */; }; + 72C56E0A2EFDFB850005A484 /* SPUExtractAppcast.m in Sources */ = {isa = PBXBuildFile; fileRef = 72C56E082EFDFB850005A484 /* SPUExtractAppcast.m */; }; + 72C56E0B2EFDFB850005A484 /* SPUExtractAppcast.m in Sources */ = {isa = PBXBuildFile; fileRef = 72C56E082EFDFB850005A484 /* SPUExtractAppcast.m */; }; + 72C56E0C2EFDFB850005A484 /* SPUExtractAppcast.h in Headers */ = {isa = PBXBuildFile; fileRef = 72C56E072EFDFB850005A484 /* SPUExtractAppcast.h */; }; + 72C56E0D2EFE002D0005A484 /* SPUExtractAppcast.m in Sources */ = {isa = PBXBuildFile; fileRef = 72C56E082EFDFB850005A484 /* SPUExtractAppcast.m */; }; + 72C56E0E2EFEEF8B0005A484 /* SPUExtractAppcast.m in Sources */ = {isa = PBXBuildFile; fileRef = 72C56E082EFDFB850005A484 /* SPUExtractAppcast.m */; }; + 72C56E102EFEF10B0005A484 /* Signing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72C56E0F2EFEF10B0005A484 /* Signing.swift */; }; + 72C56E112EFEF10B0005A484 /* Signing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72C56E0F2EFEF10B0005A484 /* Signing.swift */; }; + 72C56E122EFEF10B0005A484 /* Signing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72C56E0F2EFEF10B0005A484 /* Signing.swift */; }; + 72C56E192F04343D0005A484 /* SPUAppcastSigningValidationStatus.h in Headers */ = {isa = PBXBuildFile; fileRef = 72C56E182F04343D0005A484 /* SPUAppcastSigningValidationStatus.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 72C56E1F2F04AC890005A484 /* SUFeedSignatureVerifierTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72C56E1E2F04AC890005A484 /* SUFeedSignatureVerifierTest.swift */; }; + 72C56E202F04B3760005A484 /* Signing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72C56E0F2EFEF10B0005A484 /* Signing.swift */; }; + 72C56E262F04C28B0005A484 /* testreleasenotes.html in Resources */ = {isa = PBXBuildFile; fileRef = 72C56E212F04C28B0005A484 /* testreleasenotes.html */; }; 72CCDEBE27421FD500B53718 /* SparkleTestCodeSignApp_bad_header.zip in Resources */ = {isa = PBXBuildFile; fileRef = 72CCDEBD27421FD500B53718 /* SparkleTestCodeSignApp_bad_header.zip */; }; 72D04F3D2B094C8400A6DEAA /* SPUVerifierInformation.m in Sources */ = {isa = PBXBuildFile; fileRef = 72D04F3C2B094C8400A6DEAA /* SPUVerifierInformation.m */; }; 72D04F3E2B097D4300A6DEAA /* SPUVerifierInformation.m in Sources */ = {isa = PBXBuildFile; fileRef = 72D04F3C2B094C8400A6DEAA /* SPUVerifierInformation.m */; }; @@ -1029,7 +1044,6 @@ 7205C4461E1304C300E370AE /* Bridging-Header.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "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 /* 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 = ""; }; @@ -1192,7 +1206,7 @@ 725F97A21C8B304D00265BE4 /* SUInstallUpdateViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUInstallUpdateViewController.h; sourceTree = ""; }; 725F97A31C8B304D00265BE4 /* SUInstallUpdateViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUInstallUpdateViewController.m; sourceTree = ""; }; 725F97A41C8B304D00265BE4 /* SUInstallUpdateViewController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = SUInstallUpdateViewController.xib; sourceTree = ""; }; - 72666DC52B0B28F4001511B0 /* secret.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = secret.swift; sourceTree = ""; }; + 72666DC52B0B28F4001511B0 /* Secret.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Secret.swift; sourceTree = ""; }; 7267E56E1D3D895B00D1BF90 /* SUBinaryDeltaApply.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SUBinaryDeltaApply.h; path = Autoupdate/SUBinaryDeltaApply.h; sourceTree = SOURCE_ROOT; }; 7267E56F1D3D895B00D1BF90 /* SUBinaryDeltaApply.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SUBinaryDeltaApply.m; path = Autoupdate/SUBinaryDeltaApply.m; sourceTree = SOURCE_ROOT; }; 7267E5701D3D895B00D1BF90 /* SUBinaryDeltaCommon.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SUBinaryDeltaCommon.h; path = Autoupdate/SUBinaryDeltaCommon.h; sourceTree = SOURCE_ROOT; }; @@ -1334,6 +1348,12 @@ 72B767E51C9CFD7200A07552 /* SPUAutomaticUpdateDriver.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SPUAutomaticUpdateDriver.m; sourceTree = ""; }; 72BC6C3C275027BF0083F14B /* SparkleTestCodeSign_apfs.dmg */ = {isa = PBXFileReference; lastKnownFileType = file; path = SparkleTestCodeSign_apfs.dmg; sourceTree = ""; }; 72BEBFEE1D7287560019146B /* SUSpotlightImporterTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SUSpotlightImporterTest.swift; sourceTree = ""; }; + 72C56E072EFDFB850005A484 /* SPUExtractAppcast.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SPUExtractAppcast.h; sourceTree = ""; }; + 72C56E082EFDFB850005A484 /* SPUExtractAppcast.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SPUExtractAppcast.m; sourceTree = ""; }; + 72C56E0F2EFEF10B0005A484 /* Signing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Signing.swift; sourceTree = ""; }; + 72C56E182F04343D0005A484 /* SPUAppcastSigningValidationStatus.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SPUAppcastSigningValidationStatus.h; sourceTree = ""; }; + 72C56E1E2F04AC890005A484 /* SUFeedSignatureVerifierTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SUFeedSignatureVerifierTest.swift; sourceTree = ""; }; + 72C56E212F04C28B0005A484 /* testreleasenotes.html */ = {isa = PBXFileReference; lastKnownFileType = text.html; path = testreleasenotes.html; sourceTree = ""; }; 72CCDEBD27421FD500B53718 /* SparkleTestCodeSignApp_bad_header.zip */ = {isa = PBXFileReference; lastKnownFileType = archive.zip; path = SparkleTestCodeSignApp_bad_header.zip; sourceTree = ""; }; 72D04F3B2B094C8400A6DEAA /* SPUVerifierInformation.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SPUVerifierInformation.h; sourceTree = ""; }; 72D04F3C2B094C8400A6DEAA /* SPUVerifierInformation.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SPUVerifierInformation.m; sourceTree = ""; }; @@ -1594,6 +1614,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 72C56E062EFB45C80005A484 /* libed25519.a in Frameworks */, 725B81FC2781CDC20041746F /* libcompression.tbd in Frameworks */, 1495006F195FCE1800BC5B5B /* Foundation.framework in Frameworks */, ); @@ -1831,6 +1852,7 @@ 5A5DD41B249F0F4B0045EB3E /* test-relative-urls.xml */, 729F7EAB27366353004592DC /* test-links.xml */, 723AD12E29922B5F006BB02F /* test-dangerous-link.xml */, + 72C56E212F04C28B0005A484 /* testreleasenotes.html */, 5A5DD40324958AFF0045EB3E /* SUUpdateValidatorTest */, ); path = Resources; @@ -1910,6 +1932,7 @@ 142E0E0819A83AAC00E4312B /* SUBinaryDeltaTest.m */, F8761EB01ADC5068000C9034 /* SUCodeSigningVerifierTest.m */, 5AF9DC3B1981DBEE001EA135 /* SUSignatureVerifierTest.m */, + 72C56E1E2F04AC890005A484 /* SUFeedSignatureVerifierTest.swift */, 72A4A23F1BB6567D00E7820D /* SUFileManagerTest.swift */, 5AF6C74C1AEA40760014A3AB /* SUInstallerTest.m */, 72BEBFEE1D7287560019146B /* SUSpotlightImporterTest.swift */, @@ -1928,6 +1951,7 @@ 721AB11626C777D900D34A86 /* SPUDownloadDataPrivate.h */, 72F9EC431D5E9ED8004AC8B6 /* SPUDownloadData.m */, 7214B8851D45AD9A00CB5CED /* SPUInstallationType.h */, + 72C56E182F04343D0005A484 /* SPUAppcastSigningValidationStatus.h */, 61B5FB9409C4F04600B25A18 /* SUAppcast.h */, 725DED72263D10C400E7FA8F /* SUAppcast+Private.h */, 61B5FB9509C4F04600B25A18 /* SUAppcast.m */, @@ -2058,6 +2082,8 @@ 7267E5991D3D8A5A00D1BF90 /* SUCodeSigningVerifier.m */, 7267E59A1D3D8A5A00D1BF90 /* SUSignatureVerifier.h */, 7267E59B1D3D8A5A00D1BF90 /* SUSignatureVerifier.m */, + 72C56E072EFDFB850005A484 /* SPUExtractAppcast.h */, + 72C56E082EFDFB850005A484 /* SPUExtractAppcast.m */, 72D04F3B2B094C8400A6DEAA /* SPUVerifierInformation.h */, 72D04F3C2B094C8400A6DEAA /* SPUVerifierInformation.m */, ); @@ -2123,7 +2149,6 @@ 7205C4481E1304CE00E370AE /* ArchiveItem.swift */, 7205C44A1E1304CE00E370AE /* FeedXML.swift */, 7205C4401E13049400E370AE /* main.swift */, - 7205C4491E1304CE00E370AE /* Signatures.swift */, 7205C44B1E1304CE00E370AE /* Unarchive.swift */, FA30773E24CBC3E9007BA37D /* URL+Hashing.swift */, ); @@ -2228,7 +2253,8 @@ 72666DC42B0B28D4001511B0 /* common_cli */ = { isa = PBXGroup; children = ( - 72666DC52B0B28F4001511B0 /* secret.swift */, + 72666DC52B0B28F4001511B0 /* Secret.swift */, + 72C56E0F2EFEF10B0005A484 /* Signing.swift */, ); path = common_cli; sourceTree = ""; @@ -2492,6 +2518,7 @@ 7267E5B61D3D8AEE00D1BF90 /* SPUInstallationInfo.h in Headers */, 7245495C2ECA648000ABA991 /* SPUUpdaterSettings+Debug.h in Headers */, 72EE181926DAE70900C58B19 /* SPUUpdateCheck.h in Headers */, + 72C56E192F04343D0005A484 /* SPUAppcastSigningValidationStatus.h in Headers */, 72B767CE1C9B924900A07552 /* SPUInstallerDriver.h in Headers */, 723ABF30259D062F00BDB4FA /* SULegacyWebView.h in Headers */, 721BC20E1D1CDE55002BC71E /* SPULocalCacheDirectory.h in Headers */, @@ -2512,6 +2539,7 @@ 72EF30BE2675CF38008CE987 /* SPUAppcastItemStateResolver.h in Headers */, 72EF30C7267C716A008CE987 /* SUAppcastItem+Private.h in Headers */, 72EE17FB26D1CC8800C58B19 /* SUInstallerLauncher+Private.h in Headers */, + 72C56E0C2EFDFB850005A484 /* SPUExtractAppcast.h in Headers */, 61299A5C09CA6D4500B7442F /* SUConstants.h in Headers */, 726DF88E1C84277600188804 /* SPUUserUpdateState.h in Headers */, 72B767DA1C9CD2E400A07552 /* SPUUIBasedUpdateDriver.h in Headers */, @@ -3115,6 +3143,7 @@ files = ( 725B3A82263FBF0C0041AB8E /* testappcast_minimumAutoupdateVersion.xml in Resources */, 14958C6E19AEBC950061B14F /* signed-test-file.txt in Resources */, + 72C56E262F04C28B0005A484 /* testreleasenotes.html in Resources */, 723AD12F29922B5F006BB02F /* test-dangerous-link.xml in Resources */, 72EB736129BEB36100FBCEE7 /* DevSignedAppVersion2.zip in Resources */, 723EDC3F26885A8E000BCBA4 /* testappcast_channels.xml in Resources */, @@ -3324,6 +3353,8 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 72C56E202F04B3760005A484 /* Signing.swift in Sources */, + 72C56E1F2F04AC890005A484 /* SUFeedSignatureVerifierTest.swift in Sources */, 72D04F3E2B097D4300A6DEAA /* SPUVerifierInformation.m in Sources */, 72266A8C29464D0200645376 /* SUSignatures.m in Sources */, 72266A8B29464CEA00645376 /* SUHost.m in Sources */, @@ -3361,6 +3392,7 @@ 7210C7681B9A9A1500EB90AC /* SUUnarchiverTest.swift in Sources */, 5AE459001C34118500E3BB47 /* SUUpdaterTest.m in Sources */, 5AE459021C34118500E3BB47 /* SUVersionComparisonTest.m in Sources */, + 72C56E092EFDFB850005A484 /* SPUExtractAppcast.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -3387,6 +3419,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 72C56E0E2EFEEF8B0005A484 /* SPUExtractAppcast.m in Sources */, 729743AB279D1BD2009910B2 /* SUCodeSigningVerifier.m in Sources */, 725EE489277D39B400D820CE /* SPUDeltaArchive.m in Sources */, 725EE48A277D39B400D820CE /* SPUXarDeltaArchive.m in Sources */, @@ -3394,13 +3427,13 @@ 72464F7C1E2097F600FB341C /* SUOperatingSystem.m in Sources */, 7205C44C1E1304CE00E370AE /* Appcast.swift in Sources */, 7205C44D1E1304CE00E370AE /* ArchiveItem.swift in Sources */, - 7205C44E1E1304CE00E370AE /* Signatures.swift in Sources */, 7205C44F1E1304CE00E370AE /* FeedXML.swift in Sources */, 7205C4411E13049400E370AE /* main.swift in Sources */, 728ED34D277DA23400D9238F /* SPUSparkleDeltaArchive.m in Sources */, 7205C45F1E13066F00E370AE /* SUBinaryDeltaApply.m in Sources */, 7205C4621E1306A600E370AE /* SUBinaryDeltaCommon.m in Sources */, FA30773F24CBC3E9007BA37D /* URL+Hashing.swift in Sources */, + 72C56E102EFEF10B0005A484 /* Signing.swift in Sources */, 7205C4611E13069000E370AE /* SUBinaryDeltaCreate.m in Sources */, 7205C45B1E13064C00E370AE /* SUBinaryDeltaUnarchiver.m in Sources */, 7205C45D1E13065F00E370AE /* SUConstants.m in Sources */, @@ -3412,7 +3445,7 @@ 7205C4571E13061F00E370AE /* SUUnarchiver.m in Sources */, 7205C4581E13061F00E370AE /* SUUnarchiverNotifier.m in Sources */, 7205C4501E1304CE00E370AE /* Unarchive.swift in Sources */, - 72666DC62B0B28F4001511B0 /* secret.swift in Sources */, + 72666DC62B0B28F4001511B0 /* Secret.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -3546,6 +3579,7 @@ 7267E5C31D3D8B2700D1BF90 /* SUInstaller.m in Sources */, 5A6DD17123FE1FFC000AEF33 /* SUSignatures.m in Sources */, 721D5A8525C65D3F00D23BEA /* SUFlatPackageUnarchiver.m in Sources */, + 72C56E0A2EFDFB850005A484 /* SPUExtractAppcast.m in Sources */, 7267E5CE1D3D8C7500D1BF90 /* SULog.m in Sources */, 7267E5871D3D89B300D1BF90 /* SUPipedUnarchiver.m in Sources */, 7267E5C51D3D8B2700D1BF90 /* SUPlainInstaller.m in Sources */, @@ -3571,6 +3605,9 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 72C56E0B2EFDFB850005A484 /* SPUExtractAppcast.m in Sources */, + 72C56E052EFB45BD0005A484 /* SPUVerifierInformation.m in Sources */, + 72C56E042EFB45B10005A484 /* SUSignatureVerifier.m in Sources */, 723ABF31259D062F00BDB4FA /* SULegacyWebView.m in Sources */, 72B767E71C9CFD7200A07552 /* SPUAutomaticUpdateDriver.m in Sources */, 72B767D71C9C8B5C00A07552 /* SPUBasicUpdateDriver.m in Sources */, @@ -3670,8 +3707,9 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 72C56E122EFEF10B0005A484 /* Signing.swift in Sources */, EA1E286122B66487004AA304 /* main.swift in Sources */, - 72666DC72B0B28F4001511B0 /* secret.swift in Sources */, + 72666DC72B0B28F4001511B0 /* Secret.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -3679,8 +3717,10 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 72C56E0D2EFE002D0005A484 /* SPUExtractAppcast.m in Sources */, EA1E287922B666EB004AA304 /* main.swift in Sources */, - 72666DC82B0B28F4001511B0 /* secret.swift in Sources */, + 72666DC82B0B28F4001511B0 /* Secret.swift in Sources */, + 72C56E112EFEF10B0005A484 /* Signing.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/Sparkle/Base.lproj/Sparkle.strings b/Sparkle/Base.lproj/Sparkle.strings index a78436d7..75546cb2 100644 --- a/Sparkle/Base.lproj/Sparkle.strings +++ b/Sparkle/Base.lproj/Sparkle.strings @@ -61,6 +61,9 @@ /* No comment provided by engineer. */ "An error occurred while downloading the update. Please try again later." = "An error occurred while downloading the update. Please try again later."; +/* No comment provided by engineer. */ +"An error occurred while downloading the release notes." = "An error occurred while downloading the release notes."; + /* No comment provided by engineer. */ "An error occurred while extracting the archive. Please try again later." = "An error occurred while extracting the archive. Please try again later."; @@ -166,6 +169,12 @@ /* No comment provided by engineer. */ "The update is improperly signed and could not be validated. Please try again later or contact the app developer." = "The update is improperly signed and could not be validated. Please try again later or contact the app developer."; +/* No comment provided by engineer. */ +"The update feed is improperly signed and could not be validated. Please try again later or contact the app developer." = "The update feed is improperly signed and could not be validated. Please try again later or contact the app developer."; + +/* No comment provided by engineer. */ +"The release notes is improperly signed and could not be validated. Please contact the app developer for more information." = "The release notes is improperly signed and could not be validated. Please contact the app developer for more information."; + /* No comment provided by engineer. */ "Unable to Check For Updates" = "Unable to Check For Updates"; diff --git a/Sparkle/SPUAppcastSigningValidationStatus.h b/Sparkle/SPUAppcastSigningValidationStatus.h new file mode 100644 index 00000000..daaa9bc7 --- /dev/null +++ b/Sparkle/SPUAppcastSigningValidationStatus.h @@ -0,0 +1,32 @@ +// +// SPUAppcastSigningValidationStatus.h +// Sparkle +// +// Created on 12/30/25. +// Copyright © 2025 Sparkle Project. All rights reserved. +// + +#ifndef SPUAppcastSigningValidationStatus_h +#define SPUAppcastSigningValidationStatus_h + +typedef NS_ENUM(NSInteger, SPUAppcastSigningValidationStatus) +{ + /** + The bundle does not opt into requiring appcast signing and no validation of the appcast feed is done. + */ + SPUAppcastSigningValidationStatusSkipped = 0, + + /** + The appcast is signed and validation has passed succesfully. + */ + SPUAppcastSigningValidationStatusSucceeded, + + /** + The appcast is signed and validation has failed. In this case, appcast items operate in a 'safe' fallback mode + meaning that they cannot be marked as a critical update, cannot be marked as informational update, + and will not have any release note or link references. + */ + SPUAppcastSigningValidationStatusFailed, +}; + +#endif /* SPUAppcastSigningValidationStatus_h */ diff --git a/Sparkle/SPUAutomaticUpdateDriver.m b/Sparkle/SPUAutomaticUpdateDriver.m index 920b20d1..bcb5fb0e 100644 --- a/Sparkle/SPUAutomaticUpdateDriver.m +++ b/Sparkle/SPUAutomaticUpdateDriver.m @@ -78,11 +78,17 @@ SULog(SULogLevelError, @"Error: resumeDownloadedUpdate: called on SPUAutomaticUpdateDriver"); } +// Note: critical updates can be downloaded automatically first before needing user attention +static BOOL SPUUpdateRequiresUserAttentionBeforeDownloading(SUAppcastItem *updateItem) +{ + return (updateItem.isInformationOnlyUpdate || updateItem.majorUpgrade || updateItem.signingValidationStatus == SPUAppcastSigningValidationStatusFailed); +} + - (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem { _updateItem = updateItem; - if (updateItem.isInformationOnlyUpdate || updateItem.majorUpgrade) { + if (SPUUpdateRequiresUserAttentionBeforeDownloading(updateItem)) { [_coreDriver deferInformationalUpdate:updateItem secondaryUpdate:secondaryUpdateItem]; [self abortUpdate]; } else { @@ -139,7 +145,9 @@ - (void)abortUpdateWithError:(NSError *)error { - BOOL showNextUpdateImmediately = (error == nil || error.code == SUInstallationAuthorizeLaterError) && (!_installerDidFinishPreparation || _updateItem.criticalUpdate || _updateItem.isInformationOnlyUpdate); + // It should not be necessary to include properties from SPUUpdateRequiresUserAttentionBeforeDownloading() because _installerDidFinishPreparation should be NO in those cases, + // but we'll include the check anyway + BOOL showNextUpdateImmediately = (error == nil || error.code == SUInstallationAuthorizeLaterError) && (!_installerDidFinishPreparation || _updateItem.criticalUpdate || SPUUpdateRequiresUserAttentionBeforeDownloading(_updateItem)); [_coreDriver abortUpdateAndShowNextUpdateImmediately:showNextUpdateImmediately error:error]; } diff --git a/Sparkle/SPUExtractAppcast.h b/Sparkle/SPUExtractAppcast.h new file mode 100644 index 00000000..59b82dce --- /dev/null +++ b/Sparkle/SPUExtractAppcast.h @@ -0,0 +1,16 @@ +// +// SPUExtractAppcast.h +// Sparkle +// +// Created on 12/25/25. +// Copyright © 2025 Sparkle Project. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +// Extracts content from an appcast without the signing block, optionally returning back the signed signature & expected content length +NSData *SPUExtractAppcastContent(NSData *appcastData, NSString * _Nullable __autoreleasing * _Nullable outEdSignatureBase64, uint64_t * _Nullable outContentLength); + +NS_ASSUME_NONNULL_END diff --git a/Sparkle/SPUExtractAppcast.m b/Sparkle/SPUExtractAppcast.m new file mode 100644 index 00000000..43e89836 --- /dev/null +++ b/Sparkle/SPUExtractAppcast.m @@ -0,0 +1,60 @@ +// +// SPUExtractAppcast.m +// Sparkle +// +// Created on 12/25/25. +// Copyright © 2025 Sparkle Project. All rights reserved. +// + +#import "SPUExtractAppcast.h" + +NSData *SPUExtractAppcastContent(NSData *appcastData, NSString * _Nullable __autoreleasing * _Nullable outEdSignatureBase64, uint64_t * _Nullable outContentLength) +{ + static char feedSigningPrefix[] = ""; + + NSUInteger appcastDataLength = appcastData.length; + + NSRange prefixRange = [appcastData rangeOfData:[NSData dataWithBytesNoCopy:feedSigningPrefix length:sizeof(feedSigningPrefix) - 1 freeWhenDone:NO] options:NSDataSearchBackwards range:NSMakeRange(0, appcastDataLength)]; + + if (prefixRange.location == NSNotFound) { + return appcastData; + } + + NSData *contentFeedData = [appcastData subdataWithRange:NSMakeRange(0, prefixRange.location)]; + + NSRange suffixRange = [appcastData rangeOfData:[NSData dataWithBytesNoCopy:feedSigningSuffix length:sizeof(feedSigningSuffix) - 1 freeWhenDone:NO] options:0 range:NSMakeRange(NSMaxRange(prefixRange), appcastDataLength - NSMaxRange(prefixRange))]; + + if (suffixRange.location == NSNotFound) { + return appcastData; + } + + NSData *signingBlockData = [appcastData subdataWithRange:NSMakeRange(NSMaxRange(prefixRange), suffixRange.location - NSMaxRange(prefixRange))]; + + NSString *signingBlockString = [[NSString alloc] initWithData:signingBlockData encoding:NSUTF8StringEncoding]; + if (signingBlockString == nil) { + return appcastData; + } + + __block NSString *edSignatureBase64 = nil; + __block uint64_t contentLength = 0; + static NSString *edSignatureKey = @"edSignature:"; + static NSString *lengthKey = @"length:"; + [signingBlockString enumerateLinesUsingBlock:^(NSString * _Nonnull line, BOOL * _Nonnull __unused stop) { + if ([line hasPrefix:edSignatureKey]) { + edSignatureBase64 = [[line substringFromIndex:edSignatureKey.length] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]; + } else if ([line hasPrefix:lengthKey]) { + contentLength = (uint64_t)[[[line substringFromIndex:lengthKey.length] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet] longLongValue]; + } + }]; + + if (outEdSignatureBase64 != nil) { + *outEdSignatureBase64 = [edSignatureBase64 copy]; + } + + if (outContentLength != NULL) { + *outContentLength = contentLength; + } + + return contentFeedData; +} diff --git a/Sparkle/SPUStandardUserDriver.m b/Sparkle/SPUStandardUserDriver.m index b20e9a05..ed30fef5 100644 --- a/Sparkle/SPUStandardUserDriver.m +++ b/Sparkle/SPUStandardUserDriver.m @@ -461,7 +461,7 @@ // I don't want to expose SULog here because it's more of a user driver facing error // For our purposes we just ignore it and continue on.. NSLog(@"Failed to download release notes with error: %@", error); - [_activeUpdateAlert showReleaseNotesFailedToDownload]; + [_activeUpdateAlert showReleaseNotesFailedToDownloadWithError:error]; } - (void)showUpdateInFocus diff --git a/Sparkle/SPUUIBasedUpdateDriver.m b/Sparkle/SPUUIBasedUpdateDriver.m index 596deba6..cbe8f50f 100644 --- a/Sparkle/SPUUIBasedUpdateDriver.m +++ b/Sparkle/SPUUIBasedUpdateDriver.m @@ -19,6 +19,11 @@ #import "SPUDownloadDriver.h" #import "SPUSkippedUpdate.h" #import "SPUUserUpdateState+Private.h" +#import "SUAppcastItem+Private.h" +#import "SUSignatures.h" +#import "SUSignatureVerifier.h" +#import "SPUVerifierInformation.h" +#import "SULocalizations.h" #include "AppKitPrevention.h" @@ -30,14 +35,21 @@ @implementation SPUReleaseNotesDriver { SPUDownloadDriver *_downloadDriver; + SUHost *_host; + SUSignatures *_signatures; void (^_completionHandler)(SPUDownloadData * _Nullable, NSError * _Nullable); + + uint64_t _contentLength; } -- (instancetype)initWithReleaseNotesURL:(NSURL *)releaseNotesURL httpHeaders:(NSDictionary * _Nullable)httpHeaders userAgent:(NSString * _Nullable)userAgent host:(SUHost *)host completionHandler:(void (^)(SPUDownloadData * _Nullable, NSError * _Nullable))completionHandler SPU_OBJC_DIRECT +- (instancetype)initWithReleaseNotesURL:(NSURL *)releaseNotesURL contentLength:(uint64_t)contentLength signatures:(SUSignatures * _Nullable)signatures httpHeaders:(NSDictionary * _Nullable)httpHeaders userAgent:(NSString * _Nullable)userAgent host:(SUHost *)host completionHandler:(void (^)(SPUDownloadData * _Nullable, NSError * _Nullable))completionHandler SPU_OBJC_DIRECT { self = [super init]; if (self != nil) { + _host = host; + _signatures = signatures; + _contentLength = contentLength; _downloadDriver = [[SPUDownloadDriver alloc] initWithRequestURL:releaseNotesURL host:host userAgent:userAgent httpHeaders:httpHeaders inBackground:NO delegate:self]; _completionHandler = [completionHandler copy]; } else { @@ -54,7 +66,27 @@ - (void)downloadDriverDidDownloadData:(SPUDownloadData *)downloadData { if (_completionHandler != nil) { - _completionHandler(downloadData, nil); + if (_host.requiresSignedAppcast) { + SUSignatureVerifier *signatureVerifier = [[SUSignatureVerifier alloc] initWithPublicKeys:_host.publicKeys]; + SPUVerifierInformation *verifierInformation = [[SPUVerifierInformation alloc] initWithExpectedVersion:nil expectedContentLength:_contentLength]; + verifierInformation.actualContentLength = downloadData.data.length; + + NSError *verifierError = nil; + if (![signatureVerifier verifyData:downloadData.data signatures:_signatures fileKind:@"release notes" verifierInformation:verifierInformation error:&verifierError]) { + NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{NSLocalizedDescriptionKey:SULocalizedStringFromTableInBundle(@"The release notes is improperly signed and could not be validated. Please contact the app developer for more information.", SPARKLE_TABLE, SUSparkleBundle(), nil)}]; + + if (verifierError != nil) { + [userInfo setObject:verifierError forKey:NSUnderlyingErrorKey]; + } + + _completionHandler(nil, [NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:userInfo]); + } else { + _completionHandler(downloadData, nil); + } + } else { + _completionHandler(downloadData, nil); + } + _completionHandler = nil; } } @@ -62,7 +94,13 @@ - (void)downloadDriverDidFailToDownloadFileWithError:(nonnull NSError *)error { if (_completionHandler != nil) { - _completionHandler(nil, error); + NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{NSLocalizedDescriptionKey:SULocalizedStringFromTableInBundle(@"An error occurred while downloading the release notes.", SPARKLE_TABLE, SUSparkleBundle(), nil)}]; + + if (error != nil) { + [userInfo setObject:error forKey:NSUnderlyingErrorKey]; + } + + _completionHandler(nil, [NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:userInfo]); _completionHandler = nil; } } @@ -171,8 +209,8 @@ id delegate = _delegate; SPUUserUpdateStage stage; - // Major upgrades and information only updates are not downloaded automatically - if (_resumingDownloadedInfoOrUpdate && !updateItem.majorUpgrade && !updateItem.informationOnlyUpdate) { + // Major upgrades and information only updates are not downloaded automatically, as well as feeds that failed signing validation + if (_resumingDownloadedInfoOrUpdate && !updateItem.majorUpgrade && !updateItem.informationOnlyUpdate && updateItem.signingValidationStatus != SPUAppcastSigningValidationStatusFailed) { stage = SPUUserUpdateStageDownloaded; } else if (_resumingInstallingUpdate) { stage = SPUUserUpdateStageInstalling; @@ -268,7 +306,7 @@ if (updateItem.releaseNotesURL != nil && (![updaterDelegate respondsToSelector:@selector(updater:shouldDownloadReleaseNotesForUpdate:)] || [updaterDelegate updater:_updater shouldDownloadReleaseNotesForUpdate:updateItem])) { __weak __typeof__(self) weakSelf = self; - _releaseNotesDriver = [[SPUReleaseNotesDriver alloc] initWithReleaseNotesURL:updateItem.releaseNotesURL httpHeaders:_httpHeaders userAgent:_userAgent host:_host completionHandler:^(SPUDownloadData * _Nullable downloadData, NSError * _Nullable error) { + _releaseNotesDriver = [[SPUReleaseNotesDriver alloc] initWithReleaseNotesURL:updateItem.releaseNotesURL contentLength:updateItem.releaseNotesContentLength signatures:updateItem.releaseNotesSignatures httpHeaders:_httpHeaders userAgent:_userAgent host:_host completionHandler:^(SPUDownloadData * _Nullable downloadData, NSError * _Nullable error) { __typeof__(self) strongSelf = weakSelf; if (strongSelf != nil) { id userDriver = strongSelf->_userDriver; diff --git a/Sparkle/SPUUpdater.m b/Sparkle/SPUUpdater.m index 056c85a4..416162da 100644 --- a/Sparkle/SPUUpdater.m +++ b/Sparkle/SPUUpdater.m @@ -367,6 +367,21 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification } } + // This is a policy decision + // If developers want greater security by signing appcasts, we can also enforce greater security + // in validating updates before extracting them. + BOOL requiresSignedFeed = [_host boolForInfoDictionaryKey:SURequireSignedFeedKey]; + if (requiresSignedFeed) { + BOOL verifyBeforeExtraction = [_host boolForInfoDictionaryKey:SUVerifyUpdateBeforeExtractionKey]; + if (!verifyBeforeExtraction) { + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInvalidUpdaterError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"For security reasons, %@ needs to also be enabled if %@ is enabled for %@. Visit Sparkle's documentation for more information: https://sparkle-project.org/documentation/customization/", SUVerifyUpdateBeforeExtractionKey, SURequireSignedFeedKey, hostName] }]; + } + + return NO; + } + } + if (_updatingMainBundle) { if (!_loggedUpdateSecurityPolicyWarning && mainBundleHost.hasUpdateSecurityPolicy) { SULog(SULogLevelDefault, @"Warning: %@ has a custom NSUpdateSecurityPolicy in its Info.plist. This may cause issues when installing updates. Please consider removing this key for your builds using Sparkle if you do not really require a custom update security policy.", hostName); diff --git a/Sparkle/SPUUserDriver.h b/Sparkle/SPUUserDriver.h index d0cc98e6..46c4a47f 100644 --- a/Sparkle/SPUUserDriver.h +++ b/Sparkle/SPUUserDriver.h @@ -78,6 +78,8 @@ SU_EXPORT @protocol SPUUserDriver * * @c appcastItem.criticalUpdate indicates if the update is a critical update. * + * @c appcastItem.signingValidationStatus indicates the signing validation status of the appcast, which may be applicable if appcast signing is required. + * * A reply of `SPUUserUpdateChoiceInstall` begins or resumes downloading, extracting, or installing the update. * If the state.stage is `SPUUserUpdateStateInstalling`, this may send a quit event to the application and relaunch it immediately (in this state, this behaves as a fast "install and Relaunch"). * If the state.stage is `SPUUpdateStateNotDownloaded` or `SPUUpdateStateDownloaded` the user may be presented an authorization prompt to install the update after `-showDownloadDidStartExtractingUpdate` is called if authorization is required for installation. For example, this may occur if the update on disk is owned by a different user (e.g. root or admin for non-admin users), or if the update is a package install. diff --git a/Sparkle/SUAppcast+Private.h b/Sparkle/SUAppcast+Private.h index a472a87c..65363aee 100644 --- a/Sparkle/SUAppcast+Private.h +++ b/Sparkle/SUAppcast+Private.h @@ -13,9 +13,11 @@ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" #import "SUAppcast.h" +#import "SPUAppcastSigningValidationStatus.h" #pragma clang diagnostic pop #else #import +#import #endif NS_ASSUME_NONNULL_BEGIN @@ -24,7 +26,7 @@ NS_ASSUME_NONNULL_BEGIN @interface SUAppcast (Private) -- (nullable instancetype)initWithXMLData:(NSData *)xmlData relativeToURL:(NSURL * _Nullable)relativeURL stateResolver:(SPUAppcastItemStateResolver *)stateResolver error:(NSError * __autoreleasing *)error; +- (nullable instancetype)initWithXMLData:(NSData *)xmlData relativeToURL:(NSURL * _Nullable)relativeURL stateResolver:(SPUAppcastItemStateResolver *)stateResolver signingValidationStatus:(SPUAppcastSigningValidationStatus)signingValidationStatus error:(NSError * __autoreleasing *)error; - (SUAppcast *)copyByFilteringItems:(BOOL (^)(SUAppcastItem *))filterBlock; diff --git a/Sparkle/SUAppcast.h b/Sparkle/SUAppcast.h index 4f8e3cb1..319733cc 100644 --- a/Sparkle/SUAppcast.h +++ b/Sparkle/SUAppcast.h @@ -15,9 +15,11 @@ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" #import "SUExport.h" +#import "SPUAppcastSigningValidationStatus.h" #pragma clang diagnostic pop #else #import +#import #endif NS_ASSUME_NONNULL_BEGIN @@ -38,6 +40,13 @@ SU_EXPORT @interface SUAppcast : NSObject */ @property (readonly, nonatomic, copy) NSArray *items; +/** + The appcast signing validation status. + + Please see documentation of @c SPUAppcastSigningValidationStatus values for more information. + */ +@property (nonatomic, readonly) SPUAppcastSigningValidationStatus signingValidationStatus; + @end NS_ASSUME_NONNULL_END diff --git a/Sparkle/SUAppcast.m b/Sparkle/SUAppcast.m index c242613f..d20641cb 100644 --- a/Sparkle/SUAppcast.m +++ b/Sparkle/SUAppcast.m @@ -24,12 +24,14 @@ @implementation SUAppcast @synthesize items = _items; +@synthesize signingValidationStatus = _signingValidationStatus; -- (nullable instancetype)initWithXMLData:(NSData *)xmlData relativeToURL:(NSURL * _Nullable)relativeURL stateResolver:(SPUAppcastItemStateResolver *)stateResolver error:(NSError * __autoreleasing *)error +- (nullable instancetype)initWithXMLData:(NSData *)xmlData relativeToURL:(NSURL * _Nullable)relativeURL stateResolver:(SPUAppcastItemStateResolver *)stateResolver signingValidationStatus:(SPUAppcastSigningValidationStatus)signingValidationStatus error:(NSError * __autoreleasing *)error { self = [super init]; if (self != nil) { - _items = [self parseAppcastItemsFromXMLData:xmlData relativeToURL:relativeURL stateResolver:stateResolver error:error]; + _signingValidationStatus = signingValidationStatus; + _items = [self parseAppcastItemsFromXMLData:xmlData relativeToURL:relativeURL stateResolver:stateResolver signingValidationStatus:signingValidationStatus error:error]; if (_items == nil) { return nil; } @@ -68,7 +70,7 @@ } } --(NSArray *)parseAppcastItemsFromXMLData:(NSData *)appcastData relativeToURL:(NSURL * _Nullable)appcastURL stateResolver:(SPUAppcastItemStateResolver *)stateResolver error:(NSError *__autoreleasing*)errorp SPU_OBJC_DIRECT +-(NSArray *)parseAppcastItemsFromXMLData:(NSData *)appcastData relativeToURL:(NSURL * _Nullable)appcastURL stateResolver:(SPUAppcastItemStateResolver *)stateResolver signingValidationStatus:(SPUAppcastSigningValidationStatus)signingValidationStatus error:(NSError *__autoreleasing*)errorp SPU_OBJC_DIRECT { if (errorp) { *errorp = nil; @@ -142,6 +144,26 @@ [dict setObject:descriptionDict forKey:SURSSElementDescription]; } + } else if ([name isEqualToString:SUAppcastElementReleaseNotesLink]) { + NSString *releaseNotesLink = node.stringValue; + if (releaseNotesLink != nil) { + NSDictionary *attributes = [self attributesOfNode:(NSXMLElement *)node]; + + NSMutableDictionary *linkDict = [NSMutableDictionary dictionary]; + [linkDict setObject:releaseNotesLink forKey:@"content"]; + + NSString *edSignature = attributes[SUAppcastAttributeEDSignature]; + if (edSignature != nil) { + [linkDict setObject:edSignature forKey:SUAppcastAttributeEDSignature]; + } + + NSString *length = attributes[SUAppcastAttributeLength]; + if (length != nil) { + [linkDict setObject:length forKey:SUAppcastAttributeLength]; + } + + [dict setObject:linkDict forKey:SUAppcastElementReleaseNotesLink]; + } } else if ([name isEqualToString:SUAppcastElementDeltas]) { NSMutableArray *deltas = [NSMutableArray array]; NSEnumerator *childEnum = [[node children] objectEnumerator]; @@ -189,16 +211,21 @@ } NSString *errString; - SUAppcastItem *anItem = [[SUAppcastItem alloc] initWithDictionary:dict relativeToURL:appcastURL stateResolver:stateResolver failureReason:&errString]; + SUAppcastItem *anItem = [[SUAppcastItem alloc] initWithDictionary:dict relativeToURL:appcastURL stateResolver:stateResolver signingValidationStatus:signingValidationStatus failureReason:&errString]; - if (anItem) { + if (anItem != nil) { [appcastItems addObject:anItem]; } else { - SULog(SULogLevelError, @"Sparkle Updater: Failed to parse appcast item: %@.\nAppcast dictionary was: %@", errString, dict); - if (errorp) *errorp = [NSError errorWithDomain:SUSparkleErrorDomain - code:SUAppcastParseError - userInfo:@{NSLocalizedDescriptionKey: errString}]; - return nil; + // An info-only update item could fail to be created when signing validation fails + // Let's just resume creating the other appcast items in that case. + if (signingValidationStatus != SPUAppcastSigningValidationStatusFailed) { + SULog(SULogLevelError, @"Sparkle Updater: Failed to parse appcast item: %@.\nAppcast dictionary was: %@", errString, dict); + if (errorp) *errorp = [NSError errorWithDomain:SUSparkleErrorDomain + code:SUAppcastParseError + userInfo:@{NSLocalizedDescriptionKey: errString}]; + + return nil; + } } } @@ -258,6 +285,7 @@ } other->_items = newItems; + other->_signingValidationStatus = _signingValidationStatus; return other; } diff --git a/Sparkle/SUAppcastDriver.m b/Sparkle/SUAppcastDriver.m index 43f83f15..129f0583 100644 --- a/Sparkle/SUAppcastDriver.m +++ b/Sparkle/SUAppcastDriver.m @@ -26,10 +26,18 @@ #import "SPUAppcastItemStateResolver.h" #import "SPUAppcastItemStateResolver+Private.h" #import "SPUAppcastItemState.h" +#import "SUSignatureVerifier.h" +#import "SPUExtractAppcast.h" +#import "SUSignatures.h" +#import "SPUVerifierInformation.h" #include "AppKitPrevention.h" +#define SUInitialFailedFeedSigningValidationDateKey @"SUInitialFailedFeedSigningValidationDate" + +#define DEFAULT_APPCAST_FAILURE_EXPIRATION_INTERVAL 1728000 // 20 days + @interface SUAppcastDriver () @end @@ -73,21 +81,203 @@ - (void)downloadDriverDidDownloadData:(SPUDownloadData *)downloadData { SPUAppcastItemStateResolver *stateResolver = [[SPUAppcastItemStateResolver alloc] initWithHostVersion:_host.version applicationVersionComparator:[self versionComparator] standardVersionComparator:[SUStandardVersionComparator defaultComparator]]; + + NSData *downloadedAppcastData = downloadData.data; + + id delegate = _delegate; + + NSDate *currentDate = [NSDate date]; + + // Verify feed if appcast signing is required + SPUAppcastSigningValidationStatus appcastSigningValidationStatus; + NSData *verifiedAppcastData; + NSError *verifyAppcastDataFailureError = nil; + if (_host.requiresSignedAppcast) { + // Extract appcast content without signing information and prepare verification information + SUSignatureVerifier *signatureVerifier = [[SUSignatureVerifier alloc] initWithPublicKeys:_host.publicKeys]; + + NSString *edSignatureBase64 = nil; + uint64_t contentLength = 0; + verifiedAppcastData = SPUExtractAppcastContent(downloadedAppcastData, &edSignatureBase64, &contentLength); + + SUSignatures *signatures = [[SUSignatures alloc] initWithEd:edSignatureBase64 +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + dsa:nil +#endif + ]; + + SPUVerifierInformation *verifierInformation = [[SPUVerifierInformation alloc] initWithExpectedVersion:nil expectedContentLength:contentLength]; + verifierInformation.actualContentLength = verifiedAppcastData.length; + + // If signature verification fails, we will record the initial date it failed + // If a significant period of time passes with verification still failing, we may operate in a 'safe' mode as fallback + // and allow an app to be updated through key rotation + + // If main bundle and host bundle differ, use the main bundle (updater) with a host bundle identifier to record the validation failure date + // This ensures external updaters record this date separately from an app updating itself. + SUHost *hostForFailedSigningValidationDate; + + NSString *initialFailedFeedSigningValidationDateKey; + NSBundle *mainBundle = NSBundle.mainBundle; + if ([mainBundle isEqual:_host.bundle]) { + hostForFailedSigningValidationDate = _host; + initialFailedFeedSigningValidationDateKey = SUInitialFailedFeedSigningValidationDateKey; + } else { + hostForFailedSigningValidationDate = [[SUHost alloc] initWithBundle:mainBundle]; + + NSString *hostBundleIdentifier = _host.bundle.bundleIdentifier; + initialFailedFeedSigningValidationDateKey = (hostBundleIdentifier != nil) ? [SUInitialFailedFeedSigningValidationDateKey"_" stringByAppendingString:hostBundleIdentifier] : nil; + } + + NSError *verifyAppcastDataInnerError = nil; + if (![signatureVerifier verifyData:verifiedAppcastData signatures:signatures fileKind:@"appcast" verifierInformation:verifierInformation error:&verifyAppcastDataInnerError]) { + // Feed validation failed. Proceed to check if we can operate in safe mode if feed failure expiration interval has passed. + + NSNumber *failureExpirationIntervalSetting = [_host doubleNumberForInfoDictionaryKey:SUSignedFeedFailureExpirationIntervalKey]; + + NSTimeInterval failureExpirationInterval = (failureExpirationIntervalSetting == nil) ? DEFAULT_APPCAST_FAILURE_EXPIRATION_INTERVAL : failureExpirationIntervalSetting.doubleValue; + + BOOL canRecoverFromSigningValidationFailure; + if (initialFailedFeedSigningValidationDateKey == nil || fpclassify(failureExpirationInterval) == FP_ZERO) { + canRecoverFromSigningValidationFailure = NO; + } else { + NSDate *firstFailedSigningValidationDate = [hostForFailedSigningValidationDate objectForUserDefaultsKey:initialFailedFeedSigningValidationDateKey ofClass:NSDate.class]; + + if (firstFailedSigningValidationDate == nil) { + // Record first signing validation date + [hostForFailedSigningValidationDate setObject:currentDate forUserDefaultsKey:initialFailedFeedSigningValidationDateKey]; + canRecoverFromSigningValidationFailure = NO; + } else { + canRecoverFromSigningValidationFailure = ([currentDate timeIntervalSinceDate:firstFailedSigningValidationDate] >= failureExpirationInterval); + } + } + + NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:SULocalizedStringFromTableInBundle(@"The update feed is improperly signed and could not be validated. Please try again later or contact the app developer.", SPARKLE_TABLE, SUSparkleBundle(), nil) forKey:NSLocalizedDescriptionKey]; + + if (verifyAppcastDataInnerError != nil) { + [userInfo setObject:verifyAppcastDataInnerError forKey:NSUnderlyingErrorKey]; + } + + verifyAppcastDataFailureError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAppcastParseError userInfo:userInfo]; + + // If we can recover from signing validation failure for now, still hold onto failureVerifyAppcastDataError + // because we will use it later on if there's no actual new update to report + if (!canRecoverFromSigningValidationFailure) { + [delegate didFailToFetchAppcastWithError:verifyAppcastDataFailureError]; + return; + } + + appcastSigningValidationStatus = SPUAppcastSigningValidationStatusFailed; + } else { + // Feed validation passes + if (initialFailedFeedSigningValidationDateKey != nil) { + [hostForFailedSigningValidationDate setObject:nil forUserDefaultsKey:initialFailedFeedSigningValidationDateKey]; + } + + appcastSigningValidationStatus = SPUAppcastSigningValidationStatusSucceeded; + } + } else { + verifiedAppcastData = downloadedAppcastData; + appcastSigningValidationStatus = SPUAppcastSigningValidationStatusSkipped; + } NSError *appcastError = nil; - SUAppcast *appcast = [[SUAppcast alloc] initWithXMLData:downloadData.data relativeToURL:downloadData.URL stateResolver:stateResolver error:&appcastError]; + SUAppcast *loadedAppcast = [[SUAppcast alloc] initWithXMLData:verifiedAppcastData relativeToURL:downloadData.URL stateResolver:stateResolver signingValidationStatus:appcastSigningValidationStatus error:&appcastError]; - if (appcast == nil) { + if (loadedAppcast == nil) { NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:SULocalizedStringFromTableInBundle(@"An error occurred while parsing the update feed.", SPARKLE_TABLE, SUSparkleBundle(), nil) forKey:NSLocalizedDescriptionKey]; if (appcastError != nil) { [userInfo setObject:appcastError forKey:NSUnderlyingErrorKey]; } - [_delegate didFailToFetchAppcastWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUAppcastParseError userInfo:userInfo]]; - } else { - [self appcastDidFinishLoading:appcast inBackground:_downloadDriver.inBackground]; + [delegate didFailToFetchAppcastWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUAppcastParseError userInfo:userInfo]]; + + return; } + + // Now process the loaded appcast and find a suitable update item + + [delegate didFinishLoadingAppcast:loadedAppcast]; + + id updater = _updater; + if (updater != nil) { + NSDictionary *userInfo = @{ SUUpdaterAppcastNotificationKey: loadedAppcast }; + [[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidFinishLoadingAppCastNotification object:updater userInfo:userInfo]; + } + + NSSet *allowedChannels; + id updaterDelegate = _updaterDelegate; + if (updater != nil && [updaterDelegate respondsToSelector:@selector(allowedChannelsForUpdater:)]) { + allowedChannels = [updaterDelegate allowedChannelsForUpdater:updater]; + if (allowedChannels == nil) { + SULog(SULogLevelError, @"Error: -allowedChannelsForUpdater: cannot return nil. Treating this as an empty set."); + allowedChannels = [NSSet set]; + } + } else { + allowedChannels = [NSSet set]; + } + + SUAppcast *macOSAppcast = [SUAppcastDriver filterAppcast:loadedAppcast forMacOSAndAllowedChannels:allowedChannels]; + + id applicationVersionComparator = [self versionComparator]; + + BOOL background = _downloadDriver.inBackground; + NSNumber *phasedUpdateGroup = background ? @([SUPhasedUpdateGroupInfo updateGroupForHost:_host]) : nil; + + SPUSkippedUpdate *skippedUpdate = background ? [SPUSkippedUpdate skippedUpdateForHost:_host] : nil; + + // First filter out min/max OS version and see if there's an update that passes + // the minimum autoupdate version. We filter out updates that fail the minimum + // autoupdate version test because we have a preference over minor updates that can be + // downloaded and installed with less disturbance + SUAppcast *passesMinimumAutoupdateAppcast = [SUAppcastDriver filterSupportedAppcast:macOSAppcast phasedUpdateGroup:phasedUpdateGroup skippedUpdate:skippedUpdate currentDate:currentDate hostVersion:_host.version versionComparator:applicationVersionComparator testMinimumSystemRequirements:YES testMinimumAutoupdateVersion:YES]; + + SUAppcastItem *secondaryItemPassesMinimumAutoupdate = nil; + SUAppcastItem *primaryItemPassesMinimumAutoupdate = [self retrieveBestAppcastItemFromAppcast:passesMinimumAutoupdateAppcast versionComparator:applicationVersionComparator secondaryUpdate:&secondaryItemPassesMinimumAutoupdate]; + + // If we weren't able to find a valid update, try to find an update that + // doesn't pass the minimum autoupdate version + SUAppcastItem *finalPrimaryItem; + SUAppcastItem *finalSecondaryItem = nil; + if (![self isItemNewer:primaryItemPassesMinimumAutoupdate]) { + SUAppcast *failsMinimumAutoupdateAppcast = [SUAppcastDriver filterSupportedAppcast:macOSAppcast phasedUpdateGroup:phasedUpdateGroup skippedUpdate:skippedUpdate currentDate:currentDate hostVersion:_host.version versionComparator:applicationVersionComparator testMinimumSystemRequirements:YES testMinimumAutoupdateVersion:NO]; + + finalPrimaryItem = [self retrieveBestAppcastItemFromAppcast:failsMinimumAutoupdateAppcast versionComparator:applicationVersionComparator secondaryUpdate:&finalSecondaryItem]; + } else { + finalPrimaryItem = primaryItemPassesMinimumAutoupdate; + finalSecondaryItem = secondaryItemPassesMinimumAutoupdate; + } + + // Check if we found a new suitable update + if ([self isItemNewer:finalPrimaryItem]) { + [delegate didFindValidUpdateWithAppcastItem:finalPrimaryItem secondaryAppcastItem:finalSecondaryItem]; + return; + } + + // If we're trying to recover from a failed signing validation of the feed, show an error rather than + // showing why there isn't a new update, which we should be cautious about + if (appcastSigningValidationStatus == SPUAppcastSigningValidationStatusFailed && verifyAppcastDataFailureError != nil) { + [delegate didFailToFetchAppcastWithError:verifyAppcastDataFailureError]; + return; + } + + // Find the latest appcast item that we can report to the user and updater delegates + // This may include updates that fail due to OS version requirements. + // This excludes newer backgrounded updates that fail because they are skipped or not in current phased rollout group + + SUAppcast *notFoundAppcast = [SUAppcastDriver filterSupportedAppcast:macOSAppcast phasedUpdateGroup:phasedUpdateGroup skippedUpdate:skippedUpdate currentDate:currentDate hostVersion:_host.version versionComparator:applicationVersionComparator testMinimumSystemRequirements:NO testMinimumAutoupdateVersion:NO]; + + SUAppcastItem *notFoundPrimaryItem = [self retrieveBestAppcastItemFromAppcast:notFoundAppcast versionComparator:applicationVersionComparator secondaryUpdate:nil]; + + NSComparisonResult hostToLatestAppcastItemComparisonResult; + if (notFoundPrimaryItem != nil) { + hostToLatestAppcastItemComparisonResult = [applicationVersionComparator compareVersion:_host.version toVersion:notFoundPrimaryItem.versionString]; + } else { + hostToLatestAppcastItemComparisonResult = 0; + } + + [delegate didNotFindUpdateWithLatestAppcastItem:notFoundPrimaryItem hostToLatestAppcastItemComparisonResult:hostToLatestAppcastItemComparisonResult background:background]; } - (void)downloadDriverDidFailToDownloadFileWithError:(nonnull NSError *)error @@ -269,83 +459,6 @@ return [self preferredUpdateForRegularAppcastItem:regularItem secondaryUpdate:secondaryAppcastItem]; } -- (void)appcastDidFinishLoading:(SUAppcast *)loadedAppcast inBackground:(BOOL)background SPU_OBJC_DIRECT -{ - id delegate = _delegate; - [delegate didFinishLoadingAppcast:loadedAppcast]; - - id updater = _updater; - if (updater != nil) { - NSDictionary *userInfo = @{ SUUpdaterAppcastNotificationKey: loadedAppcast }; - [[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidFinishLoadingAppCastNotification object:updater userInfo:userInfo]; - } - - NSSet *allowedChannels; - id updaterDelegate = _updaterDelegate; - if (updater != nil && [updaterDelegate respondsToSelector:@selector(allowedChannelsForUpdater:)]) { - allowedChannels = [updaterDelegate allowedChannelsForUpdater:updater]; - if (allowedChannels == nil) { - SULog(SULogLevelError, @"Error: -allowedChannelsForUpdater: cannot return nil. Treating this as an empty set."); - allowedChannels = [NSSet set]; - } - } else { - allowedChannels = [NSSet set]; - } - - SUAppcast *macOSAppcast = [SUAppcastDriver filterAppcast:loadedAppcast forMacOSAndAllowedChannels:allowedChannels]; - - id applicationVersionComparator = [self versionComparator]; - - NSNumber *phasedUpdateGroup = background ? @([SUPhasedUpdateGroupInfo updateGroupForHost:_host]) : nil; - - SPUSkippedUpdate *skippedUpdate = background ? [SPUSkippedUpdate skippedUpdateForHost:_host] : nil; - - NSDate *currentDate = [NSDate date]; - - // First filter out min/max OS version and see if there's an update that passes - // the minimum autoupdate version. We filter out updates that fail the minimum - // autoupdate version test because we have a preference over minor updates that can be - // downloaded and installed with less disturbance - SUAppcast *passesMinimumAutoupdateAppcast = [SUAppcastDriver filterSupportedAppcast:macOSAppcast phasedUpdateGroup:phasedUpdateGroup skippedUpdate:skippedUpdate currentDate:currentDate hostVersion:_host.version versionComparator:applicationVersionComparator testMinimumSystemRequirements:YES testMinimumAutoupdateVersion:YES]; - - SUAppcastItem *secondaryItemPassesMinimumAutoupdate = nil; - SUAppcastItem *primaryItemPassesMinimumAutoupdate = [self retrieveBestAppcastItemFromAppcast:passesMinimumAutoupdateAppcast versionComparator:applicationVersionComparator secondaryUpdate:&secondaryItemPassesMinimumAutoupdate]; - - // If we weren't able to find a valid update, try to find an update that - // doesn't pass the minimum autoupdate version - SUAppcastItem *finalPrimaryItem; - SUAppcastItem *finalSecondaryItem = nil; - if (![self isItemNewer:primaryItemPassesMinimumAutoupdate]) { - SUAppcast *failsMinimumAutoupdateAppcast = [SUAppcastDriver filterSupportedAppcast:macOSAppcast phasedUpdateGroup:phasedUpdateGroup skippedUpdate:skippedUpdate currentDate:currentDate hostVersion:_host.version versionComparator:applicationVersionComparator testMinimumSystemRequirements:YES testMinimumAutoupdateVersion:NO]; - - finalPrimaryItem = [self retrieveBestAppcastItemFromAppcast:failsMinimumAutoupdateAppcast versionComparator:applicationVersionComparator secondaryUpdate:&finalSecondaryItem]; - } else { - finalPrimaryItem = primaryItemPassesMinimumAutoupdate; - finalSecondaryItem = secondaryItemPassesMinimumAutoupdate; - } - - if ([self isItemNewer:finalPrimaryItem]) { - // We found a suitable update - [delegate didFindValidUpdateWithAppcastItem:finalPrimaryItem secondaryAppcastItem:finalSecondaryItem]; - } else { - // Find the latest appcast item that we can report to the user and updater delegates - // This may include updates that fail due to OS version requirements. - // This excludes newer backgrounded updates that fail because they are skipped or not in current phased rollout group - SUAppcast *notFoundAppcast = [SUAppcastDriver filterSupportedAppcast:macOSAppcast phasedUpdateGroup:phasedUpdateGroup skippedUpdate:skippedUpdate currentDate:currentDate hostVersion:_host.version versionComparator:applicationVersionComparator testMinimumSystemRequirements:NO testMinimumAutoupdateVersion:NO]; - - SUAppcastItem *notFoundPrimaryItem = [self retrieveBestAppcastItemFromAppcast:notFoundAppcast versionComparator:applicationVersionComparator secondaryUpdate:nil]; - - NSComparisonResult hostToLatestAppcastItemComparisonResult; - if (notFoundPrimaryItem != nil) { - hostToLatestAppcastItemComparisonResult = [applicationVersionComparator compareVersion:_host.version toVersion:notFoundPrimaryItem.versionString]; - } else { - hostToLatestAppcastItemComparisonResult = 0; - } - - [delegate didNotFindUpdateWithLatestAppcastItem:notFoundPrimaryItem hostToLatestAppcastItemComparisonResult:hostToLatestAppcastItemComparisonResult background:background]; - } -} - // Note: This method is used by unit tests + (SUAppcast *)filterAppcast:(SUAppcast *)appcast forMacOSAndAllowedChannels:(NSSet *)allowedChannels #ifndef BUILDING_SPARKLE_TESTS diff --git a/Sparkle/SUAppcastItem+Private.h b/Sparkle/SUAppcastItem+Private.h index ab49b417..9941d139 100644 --- a/Sparkle/SUAppcastItem+Private.h +++ b/Sparkle/SUAppcastItem+Private.h @@ -26,13 +26,23 @@ NS_ASSUME_NONNULL_BEGIN This initializer method is intended to be marked "private" and discouraged from public usage. This method is available however. Talk to us to describe your use case and if you need to construct appcast items yourself. */ -- (nullable instancetype)initWithDictionary:(NSDictionary *)dict relativeToURL:(NSURL * _Nullable)appcastURL stateResolver:(SPUAppcastItemStateResolver *)stateResolver failureReason:(NSString * _Nullable __autoreleasing *_Nullable)error; +- (nullable instancetype)initWithDictionary:(NSDictionary *)dict relativeToURL:(NSURL * _Nullable)appcastURL stateResolver:(SPUAppcastItemStateResolver *)stateResolver signingValidationStatus:(SPUAppcastSigningValidationStatus)signingValidationStatus failureReason:(NSString * _Nullable __autoreleasing *_Nullable)error; /** - The EdDSA and DSA signatures along with their statuses. + The EdDSA and DSA signatures of the update along with their statuses. */ @property (readonly, nonatomic, nullable) SUSignatures *signatures; +/** + The EdDSA signature of the external release notes along with its status. + */ +@property (readonly, nonatomic, nullable) SUSignatures *releaseNotesSignatures; + +/** + The expected content length of the release notes file. + */ +@property (readonly, nonatomic) uint64_t releaseNotesContentLength; + @end NS_ASSUME_NONNULL_END diff --git a/Sparkle/SUAppcastItem.h b/Sparkle/SUAppcastItem.h index 2fe72b48..24569d35 100644 --- a/Sparkle/SUAppcastItem.h +++ b/Sparkle/SUAppcastItem.h @@ -16,9 +16,11 @@ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" #import "SUExport.h" +#import "SPUAppcastSigningValidationStatus.h" #pragma clang diagnostic pop #else #import +#import #endif NS_ASSUME_NONNULL_BEGIN @@ -283,6 +285,13 @@ SU_EXPORT @interface SUAppcastItem : NSObject */ @property (nonatomic, copy, readonly) NSString *installationType; +/** + The appcast signing validation status that this appcast item came from. + + Please see documentation of @c SPUAppcastSigningValidationStatus values for more information. + */ +@property (readonly, nonatomic) SPUAppcastSigningValidationStatus signingValidationStatus; + /** The phased rollout interval of the update item in seconds if provided. diff --git a/Sparkle/SUAppcastItem.m b/Sparkle/SUAppcastItem.m index f4e9e620..da145a01 100644 --- a/Sparkle/SUAppcastItem.m +++ b/Sparkle/SUAppcastItem.m @@ -24,9 +24,11 @@ static NSString *SUAppcastItemDeltaUpdatesKey = @"deltaUpdates"; static NSString *SUAppcastItemDisplayVersionStringKey = @"displayVersionString"; static NSString *SUAppcastItemSignaturesKey = @"signatures"; +static NSString *SUAppcastItemReleaseNotesSignaturesKey = @"releaseNotesSignatures"; static NSString *SUAppcastItemFileURLKey = @"fileURL"; static NSString *SUAppcastItemInfoURLKey = @"infoURL"; static NSString *SUAppcastItemContentLengthKey = @"contentLength"; +static NSString *SUAppcastItemLinkLengthKey = @"linkLength"; static NSString *SUAppcastItemDescriptionKey = @"itemDescription"; static NSString *SUAppcastItemDescriptionFormatKey = @"itemDescriptionFormat"; static NSString *SUAppcastItemMaximumSystemVersionKey = @"maximumSystemVersion"; @@ -41,10 +43,13 @@ static NSString *SUAppcastItemInstallationTypeKey = @"SUAppcastItemInstallationT static NSString *SUAppcastItemStateKey = @"SUAppcastItemState"; static NSString *SUAppcastItemDeltaFromSparkleExecutableSizeKey = @"SUAppcastItemDeltaFromSparkleExecutableSize"; static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaFromSparkleLocales"; +static NSString *SUAppcastItemSigningValidationStatusKey = @"SUAppcastItemSigningValidationStatus"; @interface SUAppcastItem () @property (readonly, nonatomic, nullable) SUSignatures *signatures; +@property (readonly, nonatomic, nullable) SUSignatures *releaseNotesSignatures; +@property (readonly, nonatomic) uint64_t releaseNotesContentLength; @end @@ -66,6 +71,8 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF @synthesize deltaUpdates = _deltaUpdates; @synthesize displayVersionString = _displayVersionString; @synthesize signatures = _signatures; +@synthesize releaseNotesSignatures = _releaseNotesSignatures; +@synthesize releaseNotesContentLength = _releaseNotesContentLength; @synthesize fileURL = _fileURL; @synthesize contentLength = _contentLength; @synthesize infoURL = _infoURL; @@ -88,6 +95,7 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF @synthesize channel = _channel; @synthesize deltaFromSparkleExecutableSize = _deltaFromSparkleExecutableSize; @synthesize deltaFromSparkleLocales = _deltaFromSparkleLocales; +@synthesize signingValidationStatus = _signingValidationStatus; + (BOOL)supportsSecureCoding { @@ -105,6 +113,7 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF _displayVersionString = [(NSString *)[decoder decodeObjectOfClass:[NSString class] forKey:SUAppcastItemDisplayVersionStringKey] copy]; _signatures = (SUSignatures *)[decoder decodeObjectOfClass:[SUSignatures class] forKey:SUAppcastItemSignaturesKey]; + _releaseNotesSignatures = (SUSignatures *)[decoder decodeObjectOfClass:[SUSignatures class] forKey:SUAppcastItemReleaseNotesSignaturesKey]; _fileURL = [decoder decodeObjectOfClass:[NSURL class] forKey:SUAppcastItemFileURLKey]; _infoURL = [decoder decodeObjectOfClass:[NSURL class] forKey:SUAppcastItemInfoURLKey]; @@ -113,6 +122,7 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF } _contentLength = (uint64_t)[decoder decodeInt64ForKey:SUAppcastItemContentLengthKey]; + _releaseNotesContentLength = (uint64_t)[decoder decodeInt64ForKey:SUAppcastItemLinkLengthKey]; NSString *installationType = [decoder decodeObjectOfClass:[NSString class] forKey:SUAppcastItemInstallationTypeKey]; if (!SPUValidInstallationType(installationType)) { @@ -159,6 +169,19 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF _phasedRolloutInterval = [decoder decodeObjectOfClass:[NSNumber class] forKey:SUAppcastElementPhasedRolloutInterval]; _channel = [(NSString *)[decoder decodeObjectOfClass:[NSString class] forKey:SUAppcastElementChannel] copy]; + + NSInteger decodedSigningValidationStatus = [decoder decodeIntegerForKey:SUAppcastItemSigningValidationStatusKey]; + + switch (decodedSigningValidationStatus) { + case SPUAppcastSigningValidationStatusSkipped: + case SPUAppcastSigningValidationStatusSucceeded: + case SPUAppcastSigningValidationStatusFailed: + _signingValidationStatus = decodedSigningValidationStatus; + break; + default: + // This shouldn't be reached, skipped == 0 matches an old encoder that doesn't encode this enum. + return nil; + } } return self; @@ -186,6 +209,10 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF [encoder encodeObject:_signatures forKey:SUAppcastItemSignaturesKey]; } + if (_releaseNotesSignatures != nil) { + [encoder encodeObject:_releaseNotesSignatures forKey:SUAppcastItemReleaseNotesSignaturesKey]; + } + if (_fileURL != nil) { [encoder encodeObject:_fileURL forKey:SUAppcastItemFileURLKey]; } @@ -195,6 +222,7 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF } [encoder encodeInt64:(int64_t)_contentLength forKey:SUAppcastItemContentLengthKey]; + [encoder encodeInt64:(int64_t)_releaseNotesContentLength forKey:SUAppcastItemLinkLengthKey]; if (_itemDescription != nil) { [encoder encodeObject:_itemDescription forKey:SUAppcastItemDescriptionKey]; @@ -267,6 +295,8 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF if (_channel != nil) { [encoder encodeObject:_channel forKey:SUAppcastElementChannel]; } + + [encoder encodeInteger:_signingValidationStatus forKey:SUAppcastItemSigningValidationStatusKey]; } - (BOOL)isDeltaUpdate @@ -368,39 +398,65 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF } // Initializer used for making delta items -- (nullable instancetype)initWithDictionary:(NSDictionary *)dict relativeToURL:(NSURL * _Nullable)appcastURL state:(SPUAppcastItemState * _Nullable)state SPU_OBJC_DIRECT +- (nullable instancetype)initWithDictionary:(NSDictionary *)dict relativeToURL:(NSURL * _Nullable)appcastURL state:(SPUAppcastItemState * _Nullable)state signingValidationStatus:(SPUAppcastSigningValidationStatus)signingValidationStatus SPU_OBJC_DIRECT { - return [self initWithDictionary:dict relativeToURL:appcastURL stateResolver:nil resolvedState:state failureReason:nil]; + return [self initWithDictionary:dict relativeToURL:appcastURL stateResolver:nil resolvedState:state signingValidationStatus:signingValidationStatus failureReason:nil]; } // Exported public initializer -- (nullable instancetype)initWithDictionary:(NSDictionary *)dict relativeToURL:(NSURL * _Nullable)appcastURL stateResolver:(SPUAppcastItemStateResolver *)stateResolver failureReason:(NSString *__autoreleasing *)error +- (nullable instancetype)initWithDictionary:(NSDictionary *)dict relativeToURL:(NSURL * _Nullable)appcastURL stateResolver:(SPUAppcastItemStateResolver *)stateResolver signingValidationStatus:(SPUAppcastSigningValidationStatus)signingValidationStatus failureReason:(NSString *__autoreleasing *)error { - return [self initWithDictionary:dict relativeToURL:appcastURL stateResolver:stateResolver resolvedState:nil failureReason:error]; + return [self initWithDictionary:dict relativeToURL:appcastURL stateResolver:stateResolver resolvedState:nil signingValidationStatus:signingValidationStatus failureReason:error]; } // Deprecated - (nullable instancetype)initWithDictionary:(NSDictionary *)dict { - return [self initWithDictionary:dict relativeToURL:nil stateResolver:nil resolvedState:nil failureReason:nil]; + return [self initWithDictionary:dict relativeToURL:nil stateResolver:nil resolvedState:nil signingValidationStatus:SPUAppcastSigningValidationStatusSkipped failureReason:nil]; } // Deprecated - (nullable instancetype)initWithDictionary:(NSDictionary *)dict failureReason:(NSString *__autoreleasing *)error { - return [self initWithDictionary:dict relativeToURL:nil stateResolver:nil resolvedState:nil failureReason:error]; + return [self initWithDictionary:dict relativeToURL:nil stateResolver:nil resolvedState:nil signingValidationStatus:SPUAppcastSigningValidationStatusSkipped failureReason:error]; } // Deprecated - (nullable instancetype)initWithDictionary:(NSDictionary *)dict relativeToURL:(NSURL * _Nullable)appcastURL failureReason:(NSString *__autoreleasing *)error { - return [self initWithDictionary:dict relativeToURL:appcastURL stateResolver:nil resolvedState:nil failureReason:error]; + return [self initWithDictionary:dict relativeToURL:appcastURL stateResolver:nil resolvedState:nil signingValidationStatus:SPUAppcastSigningValidationStatusSkipped failureReason:error]; } -- (nullable instancetype)initWithDictionary:(NSDictionary *)dict relativeToURL:(NSURL * _Nullable)appcastURL stateResolver:(SPUAppcastItemStateResolver * _Nullable)stateResolver resolvedState:(SPUAppcastItemState * _Nullable)resolvedState failureReason:(NSString *__autoreleasing *)error +// When the feed fails signing validation as fallback, sanitize the version strings +// so they don't easily contain long believable messages telling the user to do something +#define MAX_NUMBER_OF_CHARACTERS_IN_UNTRUSTED_VERSION_STRING_AFTER_FIRST_LETTER 10 +static NSString *SPUSanitizeUntrustedVersionString(NSString *versionString, NSString *versionStringElement) +{ + NSCharacterSet *lettersCharacterSet = [NSCharacterSet letterCharacterSet]; + + NSRange firstLetterRange = [versionString rangeOfCharacterFromSet:lettersCharacterSet]; + if (firstLetterRange.location == NSNotFound) { + // No alphabetic characters + return versionString; + } + + NSUInteger maxVersionStringLength = MIN(firstLetterRange.location + MAX_NUMBER_OF_CHARACTERS_IN_UNTRUSTED_VERSION_STRING_AFTER_FIRST_LETTER, versionString.length); + + NSRange allowedRange = NSMakeRange(0, maxVersionStringLength); + NSString *allowedVersionString = [versionString substringWithRange:allowedRange]; + + if (![versionString isEqualToString:allowedVersionString]) { + SULog(SULogLevelError, @"Error: Sanitized appcast item %@ from '%@' to '%@' because appcast signing validation failed and version could be untrusted", versionStringElement, versionString, allowedVersionString); + } + + return allowedVersionString; +} + +- (nullable instancetype)initWithDictionary:(NSDictionary *)dict relativeToURL:(NSURL * _Nullable)appcastURL stateResolver:(SPUAppcastItemStateResolver * _Nullable)stateResolver resolvedState:(SPUAppcastItemState * _Nullable)resolvedState signingValidationStatus:(SPUAppcastSigningValidationStatus)signingValidationStatus failureReason:(NSString *__autoreleasing *)error { self = [super init]; if (self) { + _signingValidationStatus = signingValidationStatus; _title = [(NSString *)[dict objectForKey:SURSSElementTitle] copy]; NSDictionary *enclosure = [dict objectForKey:SURSSElementEnclosure]; @@ -424,26 +480,35 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF // No sparkle:version element/attribute anywhere? SULog(SULogLevelError, @"warning: Item '%@' is missing '<%@>' element. Version comparison may be unreliable. Please always specify %@", _title, SUAppcastElementVersion, SUAppcastElementVersion); - // Separate the url by underscores and take the last component, as that'll be closest to the end, - // then we remove the extension. Hopefully, this will be the version. - NSArray *fileComponents = [(NSString *)[enclosure objectForKey:SURSSAttributeURL] componentsSeparatedByString:@"_"]; - if ([fileComponents count] > 1) { - newVersion = [[fileComponents lastObject] stringByDeletingPathExtension]; + // Grabbing the version from the URL is not properly documented or encouraged. + // Not supporting it for appcast signing + if (signingValidationStatus == SPUAppcastSigningValidationStatusSkipped) { + // Separate the url by underscores and take the last component, as that'll be closest to the end, + // then we remove the extension. Hopefully, this will be the version. + NSArray *fileComponents = [(NSString *)[enclosure objectForKey:SURSSAttributeURL] componentsSeparatedByString:@"_"]; + if ([fileComponents count] > 1) { + newVersion = [[fileComponents lastObject] stringByDeletingPathExtension]; + } } } - if (!newVersion) { + if (newVersion == nil) { if (error) { - *error = [NSString stringWithFormat:@"Feed item lacks %@ element, and version couldn't be deduced from file name (would have used last component of a file name like AppName_1.3.4.zip)", SUAppcastElementVersion]; + *error = [NSString stringWithFormat:@"Feed item lacks %@ element, and version couldn't be deduced.", SUAppcastElementVersion]; } return nil; } + + if (signingValidationStatus == SPUAppcastSigningValidationStatusFailed) { + newVersion = SPUSanitizeUntrustedVersionString(newVersion, SUAppcastElementVersion); + } _propertiesDictionary = [[NSDictionary alloc] initWithDictionary:dict]; _dateString = [(NSString *)[dict objectForKey:SURSSElementPubDate] copy]; + // Description is not to be trusted if appcast wasn't signed correctly id itemDescription = [dict objectForKey:SURSSElementDescription]; - if (itemDescription != nil) { + if (signingValidationStatus != SPUAppcastSigningValidationStatusFailed && itemDescription != nil) { if ([(NSObject *)itemDescription isKindOfClass:[NSDictionary class]]) { NSString *descriptionContent = itemDescription[@"content"]; NSString *itemDescriptionString; @@ -489,20 +554,21 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF _itemDescriptionFormat = nil; } - NSString *theInfoURL = [dict objectForKey:SURSSElementLink]; - if (theInfoURL) { - if (![theInfoURL isKindOfClass:[NSString class]]) { + NSURL *infoURL = nil; + NSString *infoLinkURLString = [dict objectForKey:SURSSElementLink]; + if (infoLinkURLString != nil) { + if (![infoLinkURLString isKindOfClass:[NSString class]]) { SULog(SULogLevelError, @"%@ -%@ Info URL is not of valid type.", NSStringFromClass([self class]), NSStringFromSelector(_cmd)); } else { - NSURL *infoURL; + NSURL *processedInfoURL; if (appcastURL != nil) { - infoURL = [NSURL URLWithString:theInfoURL relativeToURL:appcastURL]; + processedInfoURL = [NSURL URLWithString:infoLinkURLString relativeToURL:appcastURL]; } else { - infoURL = [NSURL URLWithString:theInfoURL]; + processedInfoURL = [NSURL URLWithString:infoLinkURLString]; } - if ([infoURL.scheme caseInsensitiveCompare:@"http"] == NSOrderedSame || [infoURL.scheme caseInsensitiveCompare:@"https"] == NSOrderedSame) { - _infoURL = infoURL; + if ([processedInfoURL.scheme caseInsensitiveCompare:@"http"] == NSOrderedSame || [processedInfoURL.scheme caseInsensitiveCompare:@"https"] == NSOrderedSame) { + infoURL = processedInfoURL; } else { SULog(SULogLevelError, @"%@ -%@ Info URL must have a http or https URL scheme.", NSStringFromClass([self class]), NSStringFromSelector(_cmd)); } @@ -511,14 +577,15 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF // Need an info URL or an enclosure URL. Former to show "More Info" // page, latter to download & install: - if (!enclosure && !_infoURL) { + if (enclosure == nil && infoURL == nil) { if (error) { *error = @"No enclosure in feed item"; } return nil; } - if (_infoURL != nil) { + // Further below in this method validation is done for info-only updates if appcast signing validation failed + if (infoURL != nil) { // If enclosure doesn't exist, the update must be an informational update // Otherwise check presence of informational update element _informationalUpdateVersions = (enclosure != nil) ? [dict objectForKey:SUAppcastElementInformationalUpdate] : [NSSet set]; @@ -528,7 +595,7 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF } NSString *enclosureURLString = [enclosure objectForKey:SURSSAttributeURL]; - if (!enclosureURLString && !_infoURL) { + if (enclosureURLString == nil && infoURL == nil) { if (error) { *error = @"Feed item's enclosure lacks URL"; } @@ -622,18 +689,23 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF } // Grab critical update information - NSDictionary * _Nullable criticalUpdateDictionaryFromAppcast = (NSDictionary *)[dict objectForKey:SUAppcastElementCriticalUpdate]; - NSArray *tags = [dict objectForKey:SUAppcastElementTags]; - + // Critical update information is not to be trusted if appcast wasn't signed correctly NSDictionary * _Nullable criticalUpdateDictionary; - if (criticalUpdateDictionaryFromAppcast != nil) { - criticalUpdateDictionary = criticalUpdateDictionaryFromAppcast; - } else if ([tags isKindOfClass:[NSArray class]] && [tags containsObject:SUAppcastElementCriticalUpdate]) { - // Legacy path where critical update used to be a tag without a specified version - criticalUpdateDictionary = @{}; - } else { - // No critical info present + if (signingValidationStatus == SPUAppcastSigningValidationStatusFailed) { criticalUpdateDictionary = nil; + } else { + NSDictionary * _Nullable criticalUpdateDictionaryFromAppcast = (NSDictionary *)[dict objectForKey:SUAppcastElementCriticalUpdate]; + NSArray *tags = [dict objectForKey:SUAppcastElementTags]; + + if (criticalUpdateDictionaryFromAppcast != nil) { + criticalUpdateDictionary = criticalUpdateDictionaryFromAppcast; + } else if ([tags isKindOfClass:[NSArray class]] && [tags containsObject:SUAppcastElementCriticalUpdate]) { + // Legacy path where critical update used to be a tag without a specified version + criticalUpdateDictionary = @{}; + } else { + // No critical info present + criticalUpdateDictionary = nil; + } } _hasCriticalInformation = (criticalUpdateDictionary != nil); @@ -645,6 +717,18 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF _state = resolvedState; } + // Note this needs to be checked after creating _state and _informationalUpdateVersions + if (signingValidationStatus == SPUAppcastSigningValidationStatusFailed && [self isInformationOnlyUpdate]) { + if (error != nil) { + *error = @"Informational update is rejected because signing validation on feed failed"; + } + return nil; + } + + // Even when the update is not an informational only update, the link may be referenced elsewhere + // If signing validation on appcast failed, the link is not to be trusted anywhere + _infoURL = (signingValidationStatus != SPUAppcastSigningValidationStatusFailed) ? infoURL : nil; + NSString* rolloutIntervalString = [(NSString *)[dict objectForKey:SUAppcastElementPhasedRolloutInterval] copy]; if (rolloutIntervalString != nil) { _phasedRolloutInterval = @(rolloutIntervalString.integerValue); @@ -652,7 +736,11 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF NSString *shortVersionString = [enclosure objectForKey:SUAppcastAttributeShortVersionString]; if (nil == shortVersionString) { - shortVersionString = [dict objectForKey:SUAppcastAttributeShortVersionString]; // fall back on the + shortVersionString = [dict objectForKey:SUAppcastElementShortVersionString]; // fall back on the + } + + if (shortVersionString != nil && signingValidationStatus == SPUAppcastSigningValidationStatusFailed) { + shortVersionString = SPUSanitizeUntrustedVersionString(shortVersionString, SUAppcastElementShortVersionString); } if (shortVersionString) { @@ -719,29 +807,43 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF } // Find the appropriate release notes URL. - NSString *releaseNotesString = [dict objectForKey:SUAppcastElementReleaseNotesLink]; - if (releaseNotesString) { - NSURL *url; - if (appcastURL != nil) { - url = [NSURL URLWithString:releaseNotesString relativeToURL:appcastURL]; + // Release notes is not to be trusted if signing validation on appcast failed + NSDictionary *releaseNotesLinkDictionary = [dict objectForKey:SUAppcastElementReleaseNotesLink]; + if (signingValidationStatus != SPUAppcastSigningValidationStatusFailed && releaseNotesLinkDictionary != nil) { + NSString *releaseNotesString = [releaseNotesLinkDictionary objectForKey:@"content"]; + if (releaseNotesString != nil) { + NSURL *url; + if (appcastURL != nil) { + url = [NSURL URLWithString:releaseNotesString relativeToURL:appcastURL]; + } else { + url = [NSURL URLWithString:releaseNotesString]; + } + if ([url.scheme caseInsensitiveCompare:@"http"] == NSOrderedSame || [url.scheme caseInsensitiveCompare:@"https"] == NSOrderedSame) { + _releaseNotesURL = url; + } else { + SULog(SULogLevelError, @"Release notes must have a http or https URL scheme."); + _releaseNotesURL = nil; + } + } else if ([_itemDescription hasPrefix:@"http://"] || [_itemDescription hasPrefix:@"https://"]) { // if the description starts with http:// or https:// use that. + _releaseNotesURL = [NSURL URLWithString:(NSString * _Nonnull)_itemDescription]; } else { - url = [NSURL URLWithString:releaseNotesString]; - } - if ([url.scheme caseInsensitiveCompare:@"http"] == NSOrderedSame || [url.scheme caseInsensitiveCompare:@"https"] == NSOrderedSame) { - _releaseNotesURL = url; - } else { - SULog(SULogLevelError, @"Release notes must have a http or https URL scheme."); _releaseNotesURL = nil; } - } else if ([_itemDescription hasPrefix:@"http://"] || [_itemDescription hasPrefix:@"https://"]) { // if the description starts with http:// or https:// use that. - _releaseNotesURL = [NSURL URLWithString:(NSString * _Nonnull)_itemDescription]; - } else { - _releaseNotesURL = nil; + + _releaseNotesSignatures = [[SUSignatures alloc] initWithEd:[releaseNotesLinkDictionary objectForKey:SUAppcastAttributeEDSignature] + #if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + dsa:nil + #endif + ]; + + long long releaseNotesLength = [(NSString *)[releaseNotesLinkDictionary objectForKey:@"length"] longLongValue]; + _releaseNotesContentLength = (releaseNotesLength > 0) ? (uint64_t)releaseNotesLength : 0; } // Get full release notes URL if informed. + // Full release notes is not to be trusted if signing validation on appcast failed NSString *fullReleaseNotesString = [dict objectForKey:SUAppcastElementFullReleaseNotesLink]; - if (fullReleaseNotesString) { + if (signingValidationStatus != SPUAppcastSigningValidationStatusFailed && fullReleaseNotesString != nil) { NSURL *url; if (appcastURL != nil) { url = [NSURL URLWithString:fullReleaseNotesString relativeToURL:appcastURL]; @@ -768,7 +870,7 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF NSMutableDictionary *fakeAppCastDict = [dict mutableCopy]; [fakeAppCastDict removeObjectForKey:SUAppcastElementDeltas]; [fakeAppCastDict setObject:deltaDictionary forKey:SURSSElementEnclosure]; - SUAppcastItem *deltaItem = [[SUAppcastItem alloc] initWithDictionary:fakeAppCastDict relativeToURL:appcastURL state:_state]; + SUAppcastItem *deltaItem = [[SUAppcastItem alloc] initWithDictionary:fakeAppCastDict relativeToURL:appcastURL state:_state signingValidationStatus:_signingValidationStatus]; if (deltaItem != nil) { [deltas setObject:deltaItem forKey:deltaFrom]; diff --git a/Sparkle/SUConstants.h b/Sparkle/SUConstants.h index d0256b6f..2a38c2d8 100644 --- a/Sparkle/SUConstants.h +++ b/Sparkle/SUConstants.h @@ -42,9 +42,11 @@ extern NSString *const SUSkippedMajorSubreleaseVersionKey; extern NSString *const SUScheduledCheckIntervalKey; extern NSString *const SUScheduledImpatientCheckIntervalKey; extern NSString *const SULastCheckTimeKey; +extern NSString *const SUSignedFeedFailureExpirationIntervalKey; extern NSString *const SUPublicDSAKeyKey; extern NSString *const SUPublicDSAKeyFileKey; extern NSString *const SUPublicEDKeyKey; +extern NSString *const SURequireSignedFeedKey; extern NSString *const SUVerifyUpdateBeforeExtractionKey; extern NSString *const SUAutomaticallyUpdateKey; extern NSString *const SUAllowsAutomaticUpdatesKey; @@ -76,6 +78,7 @@ extern NSString *const SUAppcastAttributeVersion; extern NSString *const SUAppcastAttributeOsType; extern NSString *const SUAppcastAttributeInstallationType; extern NSString *const SUAppcastAttributeFormat; +extern NSString *const SUAppcastAttributeLength; extern NSString *const SUAppcastElementVersion; extern NSString *const SUAppcastElementShortVersionString; diff --git a/Sparkle/SUConstants.m b/Sparkle/SUConstants.m index f2ff38d5..22558be0 100644 --- a/Sparkle/SUConstants.m +++ b/Sparkle/SUConstants.m @@ -29,9 +29,11 @@ NSString *const SUSkippedMajorSubreleaseVersionKey = @"SUSkippedMajorSubreleaseV NSString *const SUScheduledCheckIntervalKey = @"SUScheduledCheckInterval"; NSString *const SUScheduledImpatientCheckIntervalKey = @"SUScheduledImpatientCheckInterval"; NSString *const SULastCheckTimeKey = @"SULastCheckTime"; +NSString *const SUSignedFeedFailureExpirationIntervalKey = @"SUSignedFeedFailureExpirationInterval"; NSString *const SUPublicDSAKeyKey = @"SUPublicDSAKey"; NSString *const SUPublicDSAKeyFileKey = @"SUPublicDSAKeyFile"; NSString *const SUPublicEDKeyKey = @"SUPublicEDKey"; +NSString *const SURequireSignedFeedKey = @"SURequireSignedFeed"; NSString *const SUVerifyUpdateBeforeExtractionKey = @"SUVerifyUpdateBeforeExtraction"; NSString *const SUAutomaticallyUpdateKey = @"SUAutomaticallyUpdate"; NSString *const SUAllowsAutomaticUpdatesKey = @"SUAllowsAutomaticUpdates"; @@ -65,6 +67,7 @@ NSString *const SUAppcastAttributeVersion = @"sparkle:version"; NSString *const SUAppcastAttributeOsType = @"sparkle:os"; NSString *const SUAppcastAttributeInstallationType = @"sparkle:installationType"; NSString *const SUAppcastAttributeFormat = @"sparkle:format"; +NSString *const SUAppcastAttributeLength = @"sparkle:length"; NSString *const SUAppcastElementVersion = SUAppcastAttributeVersion; NSString *const SUAppcastElementShortVersionString = SUAppcastAttributeShortVersionString; diff --git a/Sparkle/SUHost.h b/Sparkle/SUHost.h index b8e85925..ba90c3af 100644 --- a/Sparkle/SUHost.h +++ b/Sparkle/SUHost.h @@ -38,6 +38,7 @@ SUHostDefinitionAttribute @property (readonly, nonatomic, copy, nullable) NSString *publicDSAKeyFileKey; @property (nonatomic, readonly) BOOL hasUpdateSecurityPolicy; +@property (nonatomic, readonly) BOOL requiresSignedAppcast; - (nullable id)objectForInfoDictionaryKey:(NSString *)key ofClass:(Class)aClass; - (nullable NSNumber *)boolNumberForInfoDictionaryKey:(NSString *)key; diff --git a/Sparkle/SUHost.m b/Sparkle/SUHost.m index 048666bf..0ec8d73b 100644 --- a/Sparkle/SUHost.m +++ b/Sparkle/SUHost.m @@ -226,6 +226,11 @@ static void *SUHostObservableContext = &SUHostObservableContext; return (updateSecurityPolicy != nil); } +- (BOOL)requiresSignedAppcast +{ + return [self boolForInfoDictionaryKey:SURequireSignedFeedKey]; +} + - (SUPublicKeys *)publicKeys { return [[SUPublicKeys alloc] initWithEd:[self publicEDKey] diff --git a/Sparkle/SUPlainTextReleaseNotesView.m b/Sparkle/SUPlainTextReleaseNotesView.m index 7a29aef4..65017f43 100644 --- a/Sparkle/SUPlainTextReleaseNotesView.m +++ b/Sparkle/SUPlainTextReleaseNotesView.m @@ -324,6 +324,25 @@ static NSAttributedString *formatMarkdownAttributedString(NSAttributedString *or return outputAttributedString; } +// Foundation's markdown parser doesn't handle HTML comments, +// but the document may begin with a comment for describing a warning for signing +// Preprocess and skip the document beginning comment +static NSString *preprocessMarkdownContent(NSString *markdownContent) +{ + if (![markdownContent hasPrefix:@"\n" options:NSLiteralSearch]; + NSRange finalEndCommentRange = (endCommentRangeWithNewline.location != NSNotFound ? endCommentRangeWithNewline : [markdownContent rangeOfString:@"-->" options:NSLiteralSearch]); + if (finalEndCommentRange.location == NSNotFound) { + return markdownContent; + } + + return [markdownContent substringFromIndex:NSMaxRange(finalEndCommentRange)]; +} - (void)_loadAttributedString:(NSAttributedString * _Nullable)attributedString completionHandler:(void (^)(NSError * _Nullable))completionHandler SPU_OBJC_DIRECT { @@ -372,7 +391,10 @@ static NSAttributedString *formatMarkdownAttributedString(NSAttributedString *or [_scrollView setHasVerticalScroller:YES]; [_scrollView setHasHorizontalScroller:NO]; + NSString *preprocessedContents; if (_prefersMarkdown) { + preprocessedContents = preprocessMarkdownContent(contents); + if (@available(macOS 12, *)) { dispatch_queue_attr_t queuePriority = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, 0); @@ -380,12 +402,12 @@ static NSAttributedString *formatMarkdownAttributedString(NSAttributedString *or dispatch_async(markdownDispatchQueue, ^{ NSError *loadMarkdownError = nil; - NSAttributedString *originalMarkdownAttributedString = [[NSAttributedString alloc] initWithMarkdownString:contents options:nil baseURL:baseURL error:&loadMarkdownError]; + NSAttributedString *originalMarkdownAttributedString = [[NSAttributedString alloc] initWithMarkdownString:preprocessedContents options:nil baseURL:baseURL error:&loadMarkdownError]; if (originalMarkdownAttributedString == nil) { // Fallback to plain-text - NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:contents attributes:@{ NSFontAttributeName : [NSFont systemFontOfSize:(CGFloat)self->_fontPointSize] }]; + NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:preprocessedContents attributes:@{ NSFontAttributeName : [NSFont systemFontOfSize:(CGFloat)self->_fontPointSize] }]; dispatch_async(dispatch_get_main_queue(), ^{ [self _loadAttributedString:attributedString completionHandler:completionHandler]; @@ -403,9 +425,11 @@ static NSAttributedString *formatMarkdownAttributedString(NSAttributedString *or } else { SULog(SULogLevelDefault, @"Warning: falling back to plain text because markdown support requires macOS 12 or newer"); } + } else { + preprocessedContents = contents; } - NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:contents attributes:@{ NSFontAttributeName : [NSFont systemFontOfSize:(CGFloat)_fontPointSize] }]; + NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:preprocessedContents attributes:@{ NSFontAttributeName : [NSFont systemFontOfSize:(CGFloat)_fontPointSize] }]; [self _loadAttributedString:attributedString completionHandler:completionHandler]; } diff --git a/Sparkle/SUSignatures.h b/Sparkle/SUSignatures.h index e2b60302..87c22466 100644 --- a/Sparkle/SUSignatures.h +++ b/Sparkle/SUSignatures.h @@ -64,7 +64,9 @@ SUPublicKeysDefinitionAttribute @property (nonatomic, readonly) BOOL hasAnyKeys; - (instancetype)initWithEd:(NSString * _Nullable)ed +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT dsa:(NSString * _Nullable)dsa +#endif ; @end diff --git a/Sparkle/SUUpdateAlert.h b/Sparkle/SUUpdateAlert.h index 23a1db23..dccd7422 100644 --- a/Sparkle/SUUpdateAlert.h +++ b/Sparkle/SUUpdateAlert.h @@ -24,7 +24,7 @@ SPU_OBJC_DIRECT_MEMBERS @interface SUUpdateAlert : NSWindowController - (instancetype)initWithAppcastItem:(SUAppcastItem *)item state:(SPUUserUpdateState *)state host:(SUHost *)aHost versionDisplayer:(id)versionDisplayer updaterSettings:(SPUUpdaterSettings *)updaterSettings delegate:(id)delegate completionBlock:(void (^)(SPUUserUpdateChoice, NSRect, BOOL))completionBlock didBecomeKeyBlock:(void (^)(void))didBecomeKeyBlock; - (void)showUpdateReleaseNotesWithDownloadData:(SPUDownloadData *)downloadData; -- (void)showReleaseNotesFailedToDownload; +- (void)showReleaseNotesFailedToDownloadWithError:(NSError *)error; - (void)setInstallButtonFocus:(BOOL)focus; diff --git a/Sparkle/SUUpdateAlert.m b/Sparkle/SUUpdateAlert.m index 37d49366..aa8099af 100644 --- a/Sparkle/SUUpdateAlert.m +++ b/Sparkle/SUUpdateAlert.m @@ -160,7 +160,7 @@ typedef NS_ENUM(NSInteger, SUReleaseNotesFormat) - (void)displayReleaseNotesSpinner SPU_OBJC_DIRECT { - // Stick a nice big spinner in the middle of the web view until the page is loaded. + // Stick a nice big spinner in the middle of the release notes view until the page is loaded. _releaseNotesSpinner = [[NSProgressIndicator alloc] init]; _releaseNotesSpinner.controlSize = NSControlSizeRegular; [_releaseNotesSpinner setStyle:NSProgressIndicatorStyleSpinning]; @@ -176,7 +176,7 @@ typedef NS_ENUM(NSInteger, SUReleaseNotesFormat) _releaseNotesSpinner.displayedWhenStopped = NO; [_releaseNotesSpinner startAnimation:self]; - // If there's no release notes URL, just stick the contents of the description into the web view + // If there's no release notes URL, just stick the contents of the description into the release notes view // Otherwise we'll wait until the client wants us to show release notes if (_updateItem.releaseNotesURL == nil) { NSString *itemDescription = _updateItem.itemDescription; @@ -197,7 +197,7 @@ typedef NS_ENUM(NSInteger, SUReleaseNotesFormat) __weak __typeof__(self) weakSelf = self; [_releaseNotesView loadString:itemDescription baseURL:nil completionHandler:^(NSError * _Nullable error) { if (error != nil) { - SULog(SULogLevelError, @"Failed to load HTML string from web view: %@", error); + SULog(SULogLevelError, @"Failed to load HTML string from release notes view: %@", error); } [weakSelf stopReleaseNotesSpinner]; }]; @@ -247,15 +247,24 @@ typedef NS_ENUM(NSInteger, SUReleaseNotesFormat) __weak __typeof__(self) weakSelf = self; [_releaseNotesView loadData:downloadData.data MIMEType:chosenMIMEType textEncodingName:chosenTextEncodingName baseURL:baseURL completionHandler:^(NSError * _Nullable error) { if (error != nil) { - SULog(SULogLevelError, @"Failed to load data from web view: %@", error); + SULog(SULogLevelError, @"Failed to load data from release notes view: %@", error); } [weakSelf stopReleaseNotesSpinner]; }]; } -- (void)showReleaseNotesFailedToDownload +- (void)showReleaseNotesFailedToDownloadWithError:(NSError *)error { - [self stopReleaseNotesSpinner]; + [self _createReleaseNotesViewPreferringFormat:SUReleaseNotesFormatPlainText]; + + __weak __typeof__(self) weakSelf = self; + [_releaseNotesView loadString:error.localizedDescription baseURL:nil completionHandler:^(NSError * _Nullable loadCompletionError) { + if (loadCompletionError != nil) { + SULog(SULogLevelError, @"Failed to load HTML error string from release notes view: %@", loadCompletionError); + } + + [weakSelf stopReleaseNotesSpinner]; + }]; } - (void)stopReleaseNotesSpinner SPU_OBJC_DIRECT @@ -343,14 +352,19 @@ typedef NS_ENUM(NSInteger, SUReleaseNotesFormat) // FB6993802: https://twitter.com/sindresorhus/status/1160577243929878528 | https://github.com/feedback-assistant/reports/issues/1 // If the developer is using the downloader XPC service, they are very most likely are a) sandboxed b) do not use outgoing network entitlement. // In this case, fall back to legacy WebKit view. - // (In theory it is possible for a non-sandboxed app or sandboxed app with outgoing network entitlement to use the XPC service, it's just pretty unlikely. And falling back to a legacy web view would not be too harmful in those cases). + // (In theory it is possible for a non-sandboxed app or sandboxed app with outgoing network entitlement to use the XPC service, it's just unlikely and unsupported). + // Note: because legacy web view is only supported with using downloader XPC Service, and the app + // should not have an outgoing network client, there's no need to be concerned about the + // appcast signing validation status for loading external resources, which shouldn't be possible. BOOL useWKWebView = !SPUXPCServiceIsEnabled(SUEnableDownloaderServiceKey); if (!useWKWebView) { _releaseNotesView = [[SULegacyWebView alloc] initWithColorStyleSheetLocation:colorStyleURL fontFamily:defaultFontFamily fontPointSize:defaultFontSize javaScriptEnabled:javaScriptEnabled customAllowedURLSchemes:customAllowedURLSchemes]; } else #endif { - _releaseNotesView = [[SUWKWebView alloc] initWithColorStyleSheetLocation:colorStyleURL fontFamily:defaultFontFamily fontPointSize:defaultFontSize javaScriptEnabled:javaScriptEnabled customAllowedURLSchemes:customAllowedURLSchemes installedVersion: _host.version]; + BOOL allowsLoadingExternalReferences = (_updateItem.signingValidationStatus == SPUAppcastSigningValidationStatusSkipped); + + _releaseNotesView = [[SUWKWebView alloc] initWithColorStyleSheetLocation:colorStyleURL fontFamily:defaultFontFamily fontPointSize:defaultFontSize javaScriptEnabled:javaScriptEnabled customAllowedURLSchemes:customAllowedURLSchemes allowsLoadingExternalReferences:allowsLoadingExternalReferences installedVersion:_host.version]; } break; diff --git a/Sparkle/SUWKWebView.h b/Sparkle/SUWKWebView.h index 1d28b6a7..cf19c202 100644 --- a/Sparkle/SUWKWebView.h +++ b/Sparkle/SUWKWebView.h @@ -15,7 +15,7 @@ NS_ASSUME_NONNULL_BEGIN SPU_OBJC_DIRECT_MEMBERS @interface SUWKWebView : NSObject -- (instancetype)initWithColorStyleSheetLocation:(NSURL *)colorStyleSheetLocation fontFamily:(NSString *)fontFamily fontPointSize:(int)fontPointSize javaScriptEnabled:(BOOL)javaScriptEnabled customAllowedURLSchemes:(NSArray *)customAllowedURLSchemes installedVersion:(NSString *)installedVersion; +- (instancetype)initWithColorStyleSheetLocation:(NSURL *)colorStyleSheetLocation fontFamily:(NSString *)fontFamily fontPointSize:(int)fontPointSize javaScriptEnabled:(BOOL)javaScriptEnabled customAllowedURLSchemes:(NSArray *)customAllowedURLSchemes allowsLoadingExternalReferences:(BOOL)allowsLoadingExternalReferences installedVersion:(NSString *)installedVersion; @end diff --git a/Sparkle/SUWKWebView.m b/Sparkle/SUWKWebView.m index 10dacd53..81899bd3 100644 --- a/Sparkle/SUWKWebView.m +++ b/Sparkle/SUWKWebView.m @@ -33,6 +33,7 @@ void (^_completionHandler)(NSError * _Nullable); BOOL _drawsWebViewBackground; + BOOL _allowsLoadingExternalReferences; } static WKUserScript *makeUserScriptWithInjectedStyleSource(NSString *styleSource) @@ -73,13 +74,15 @@ static WKUserScript *makeUserScriptForExposingCurrentRelease(NSString *releaseSt return [[WKUserScript alloc] initWithSource:scriptSource injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES]; } -- (instancetype)initWithColorStyleSheetLocation:(NSURL *)colorStyleSheetLocation fontFamily:(NSString *)fontFamily fontPointSize:(int)fontPointSize javaScriptEnabled:(BOOL)javaScriptEnabled customAllowedURLSchemes:(NSArray *)customAllowedURLSchemes installedVersion:(NSString *)installedVersion +- (instancetype)initWithColorStyleSheetLocation:(NSURL *)colorStyleSheetLocation fontFamily:(NSString *)fontFamily fontPointSize:(int)fontPointSize javaScriptEnabled:(BOOL)javaScriptEnabled customAllowedURLSchemes:(NSArray *)customAllowedURLSchemes allowsLoadingExternalReferences:(BOOL)allowsLoadingExternalReferences installedVersion:(NSString *)installedVersion { self = [super init]; if (self != nil) { // Synchronize with web view defaulting to drawing background to avoid unnecessary invocations in -setDrawsBackground: _drawsWebViewBackground = YES; + _allowsLoadingExternalReferences = allowsLoadingExternalReferences; + WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; // Note: this javaScriptEnabled property is deprecated in favor of another webpage preference property, @@ -141,18 +144,46 @@ static WKUserScript *makeUserScriptForExposingCurrentRelease(NSString *releaseSt return _webView; } +static void SPULoadWebContent(BOOL allowsExternalReferences, WKUserContentController *userContentController, void (^loadHTMLContent)(void)) +{ + if (allowsExternalReferences) { + loadHTMLContent(); + return; + } + + // Block loading all external resources for signed appcasts & signed release notes + NSString *encodedContentRuleList = + @"[{\"trigger\": { \"url-filter\": \".*\" }, \"action\": { \"type\": \"block\" } }]"; + + [WKContentRuleListStore.defaultStore compileContentRuleListForIdentifier:@"sparkle-updater" encodedContentRuleList:encodedContentRuleList completionHandler:^(WKContentRuleList *contentRuleList, NSError *contentRuleListError) { + dispatch_async(dispatch_get_main_queue(), ^{ + if (contentRuleList == nil) { + SULog(SULogLevelError, @"Error: failed to load content rule list for WKWebView with error: %@", contentRuleListError); + } else { + [userContentController addContentRuleList:contentRuleList]; + } + + loadHTMLContent(); + }); + }]; +} + - (void)loadString:(NSString *)htmlString baseURL:(NSURL * _Nullable)baseURL completionHandler:(void (^)(NSError * _Nullable))completionHandler { _completionHandler = [completionHandler copy]; - _currentNavigation = [_webView loadHTMLString:htmlString baseURL:baseURL]; + SPULoadWebContent(_allowsLoadingExternalReferences, _webView.configuration.userContentController, ^{ + self->_currentNavigation = [self->_webView loadHTMLString:htmlString baseURL:baseURL]; + }); } - (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL completionHandler:(void (^)(NSError * _Nullable))completionHandler { _completionHandler = [completionHandler copy]; - _currentNavigation = [_webView loadData:data MIMEType:MIMEType characterEncodingName:textEncodingName baseURL:baseURL]; + SPULoadWebContent(_allowsLoadingExternalReferences, _webView.configuration.userContentController, ^{ + self->_currentNavigation = [self->_webView loadData:data MIMEType:MIMEType characterEncodingName:textEncodingName baseURL:baseURL]; + }); } - (void)setDrawsBackground:(BOOL)drawsBackground diff --git a/TestApplication/SUTestApplicationDelegate.m b/TestApplication/SUTestApplicationDelegate.m index 852782a3..17c87f96 100644 --- a/TestApplication/SUTestApplicationDelegate.m +++ b/TestApplication/SUTestApplicationDelegate.m @@ -216,6 +216,19 @@ NSUInteger numberOfFromVersionReplacements = [appcastContents replaceOccurrencesOfString:@"$INSERT_DELTA_FROM_VERSION" withString:mainBundleVersion options:NSLiteralSearch range:NSMakeRange(0, appcastContents.length)]; assert(numberOfFromVersionReplacements == 1); + NSRange feedSignaturesPrefixRange = [appcastContents rangeOfString:@" Sparkle Test App Changelog @@ -144,3 +147,7 @@ Note though, Sparkle's markdown support does not support tables or images. It ne + diff --git a/Tests/Resources/test-dangerous-link.xml b/Tests/Resources/test-dangerous-link.xml index 02d0d96f..a4800824 100644 --- a/Tests/Resources/test-dangerous-link.xml +++ b/Tests/Resources/test-dangerous-link.xml @@ -2,13 +2,23 @@ For unit test only + + Version 4.0 + Sat, 26 Jul 2014 15:20:12 +0000 + https://sparkle-project.org/notes/relnote-4.0.txt + https://sparkle-project.org/fullnotes.txt + + https://sparkle-project.org + + Version 3.0 Sat, 26 Jul 2014 15:20:12 +0000 https://sparkle-project.org/notes/relnote-3.0.txt https://sparkle-project.org/fullnotes.txt + https://sparkle-project.org - + Version 2.0 @@ -16,7 +26,9 @@ http://sparkle-project.org/notes/relnote-2.0.txt http://sparkle-project.org/fullnotes.txt http://sparkle-project.org - + 2.0 + 2.0 (Visit abc.com for updates) + Version 1.0 diff --git a/Tests/Resources/testreleasenotes.html b/Tests/Resources/testreleasenotes.html new file mode 100644 index 00000000..79db18fd --- /dev/null +++ b/Tests/Resources/testreleasenotes.html @@ -0,0 +1,23 @@ + + + + + + + + + + + +

1.8 Changes

+
    +
  • Add some stuff
  • +
  • Fix some stuff
  • +
  • Update some stuff
  • +
+ + diff --git a/Tests/SUAppcastTest.swift b/Tests/SUAppcastTest.swift index 7298ca81..6b5d5a83 100644 --- a/Tests/SUAppcastTest.swift +++ b/Tests/SUAppcastTest.swift @@ -20,7 +20,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "1.0" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) let items = appcast.items XCTAssertEqual(4, items.count) @@ -91,7 +91,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "1.0" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) XCTAssertEqual(6, appcast.items.count) do { @@ -149,7 +149,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "1.0" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) XCTAssertEqual(4, appcast.items.count) do { @@ -179,7 +179,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "1.0" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) XCTAssertTrue(appcast.items[0].isCriticalUpdate) } @@ -188,7 +188,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "1.5" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) XCTAssertFalse(appcast.items[0].isCriticalUpdate) } @@ -197,7 +197,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "1.6" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) XCTAssertFalse(appcast.items[0].isCriticalUpdate) } } catch let err as NSError { @@ -219,7 +219,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "1.0" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) XCTAssertFalse(appcast.items[0].isInformationOnlyUpdate) XCTAssertFalse(appcast.items[1].isInformationOnlyUpdate) @@ -238,7 +238,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "2.3" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) XCTAssertFalse(appcast.items[1].isInformationOnlyUpdate) } @@ -248,7 +248,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "2.4" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) XCTAssertTrue(appcast.items[1].isInformationOnlyUpdate) } @@ -258,7 +258,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "2.5" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) XCTAssertTrue(appcast.items[1].isInformationOnlyUpdate) } @@ -268,7 +268,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "2.6" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) XCTAssertFalse(appcast.items[1].isInformationOnlyUpdate) } @@ -278,7 +278,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "0.5" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) XCTAssertFalse(appcast.items[1].isInformationOnlyUpdate) } @@ -288,7 +288,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "0.4" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) XCTAssertTrue(appcast.items[1].isInformationOnlyUpdate) } @@ -298,7 +298,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "0.0" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) XCTAssertTrue(appcast.items[1].isInformationOnlyUpdate) } @@ -323,7 +323,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "1.0" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) XCTAssertEqual(2, appcast.items.count) } @@ -334,7 +334,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "1.0" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testMinimumSystemRequirements: true, testMinimumAutoupdateVersion: true) @@ -350,7 +350,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "2.0" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testMinimumSystemRequirements: true, testMinimumAutoupdateVersion: true) @@ -366,7 +366,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "2.5" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testMinimumSystemRequirements: true, testMinimumAutoupdateVersion: true) @@ -382,7 +382,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "1.0" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) // There should be no items if 2.0 is skipped from 1.0 and 3.0 fails minimum autoupdate version do { @@ -514,7 +514,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "1.0" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) XCTAssertEqual(5, appcast.items.count) } @@ -525,7 +525,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "1.0" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testMinimumSystemRequirements: true, testMinimumAutoupdateVersion: true) @@ -542,7 +542,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "1.0" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) let skippedUpdate = SPUSkippedUpdate(minorVersion: nil, majorVersion: "3.0", majorSubreleaseVersion: nil) @@ -561,7 +561,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "1.0" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) let skippedUpdate = SPUSkippedUpdate(minorVersion: nil, majorVersion: "3.0", majorSubreleaseVersion: nil) @@ -580,7 +580,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "1.0" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) let skippedUpdate = SPUSkippedUpdate(minorVersion: nil, majorVersion: "4.0", majorSubreleaseVersion: nil) @@ -612,7 +612,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "1.0" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) // Allow minimum autoupdate version to fail and only skip major version "3.0" with no subrelease version // This should skip all 3.x versions except for 3.9 which ignores skipped upgrades below 3.5, but not 4.x versions nor 2.x versions @@ -734,7 +734,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "1.0" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) XCTAssertEqual(6, appcast.items.count) } @@ -744,7 +744,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "1.0" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) let supportedAppcast = SUAppcastDriver.filterSupportedAppcast(appcast, phasedUpdateGroup: nil, skippedUpdate: nil, currentDate: currentDate, hostVersion: hostVersion, versionComparator: versionComparator, testMinimumSystemRequirements: true, testMinimumAutoupdateVersion: false) @@ -788,7 +788,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "1.0" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) do { // Test no group @@ -896,7 +896,7 @@ class SUAppcastTest: XCTestCase { let hostVersion = "2.0" let stateResolver = SPUAppcastItemStateResolver(hostVersion: hostVersion, applicationVersionComparator: versionComparator, standardVersionComparator: versionComparator) - let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) do { // Test no group @@ -960,7 +960,7 @@ class SUAppcastTest: XCTestCase { let stateResolver = SPUAppcastItemStateResolver(hostVersion: "1.0", applicationVersionComparator: SUStandardVersionComparator.default, standardVersionComparator: SUStandardVersionComparator.default) - let fullAppcast = try SUAppcast(xmlData: testFileData, relativeTo: testFileUrl, stateResolver: stateResolver) + let fullAppcast = try SUAppcast(xmlData: testFileData, relativeTo: testFileUrl, stateResolver: stateResolver, signingValidationStatus: .skipped) do { let appcast = SUAppcastDriver.filterAppcast(fullAppcast, forMacOSAndAllowedChannels: ["english-later"]) @@ -1006,7 +1006,7 @@ class SUAppcastTest: XCTestCase { do { let stateResolver = SPUAppcastItemStateResolver(hostVersion: "1.0", applicationVersionComparator: SUStandardVersionComparator.default, standardVersionComparator: SUStandardVersionComparator.default) - let appcast = try SUAppcast(xmlData: testData as Data, relativeTo: nil, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData as Data, relativeTo: nil, stateResolver: stateResolver, signingValidationStatus: .skipped) let items = appcast.items XCTAssertEqual(2, items.count) @@ -1030,7 +1030,7 @@ class SUAppcastTest: XCTestCase { let stateResolver = SPUAppcastItemStateResolver(hostVersion: "1.0", applicationVersionComparator: SUStandardVersionComparator.default, standardVersionComparator: SUStandardVersionComparator.default) - let appcast = try SUAppcast(xmlData: testData as Data, relativeTo: baseURL, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData as Data, relativeTo: baseURL, stateResolver: stateResolver, signingValidationStatus: .skipped) let items = appcast.items XCTAssertEqual(3, items.count) @@ -1068,7 +1068,7 @@ class SUAppcastTest: XCTestCase { let stateResolver = SPUAppcastItemStateResolver(hostVersion: "1.0", applicationVersionComparator: SUStandardVersionComparator.default, standardVersionComparator: SUStandardVersionComparator.default) - let appcast = try SUAppcast(xmlData: testData as Data, relativeTo: baseURL, stateResolver: stateResolver) + let appcast = try SUAppcast(xmlData: testData as Data, relativeTo: baseURL, stateResolver: stateResolver, signingValidationStatus: .skipped) let items = appcast.items XCTAssertEqual(4, items.count) @@ -1103,7 +1103,7 @@ class SUAppcastTest: XCTestCase { let stateResolver = SPUAppcastItemStateResolver(hostVersion: "1.0", applicationVersionComparator: SUStandardVersionComparator.default, standardVersionComparator: SUStandardVersionComparator.default) - let _ = try SUAppcast(xmlData: testData as Data, relativeTo: baseURL, stateResolver: stateResolver) + let _ = try SUAppcast(xmlData: testData as Data, relativeTo: baseURL, stateResolver: stateResolver, signingValidationStatus: .skipped) XCTFail("Appcast creation should fail when encountering dangerous link") } catch let err as NSError { @@ -1111,4 +1111,56 @@ class SUAppcastTest: XCTestCase { XCTAssertNotNil(err) } } + + func testDangerousLinkWithSucceededSigningValidation() { + let testFile = Bundle(for: SUAppcastTest.self).path(forResource: "test-dangerous-link", ofType: "xml")! + let testData = NSData(contentsOfFile: testFile)! + + do { + let baseURL: URL? = nil + + let stateResolver = SPUAppcastItemStateResolver(hostVersion: "1.0", applicationVersionComparator: SUStandardVersionComparator.default, standardVersionComparator: SUStandardVersionComparator.default) + + let _ = try SUAppcast(xmlData: testData as Data, relativeTo: baseURL, stateResolver: stateResolver, signingValidationStatus: .skipped) + + XCTFail("Appcast creation should fail when encountering dangerous link") + } catch let err as NSError { + NSLog("Expected error: %@", err) + XCTAssertNotNil(err) + } + } + + func testDangerousLinkWithFailedSigningValidation() { + let testFile = Bundle(for: SUAppcastTest.self).path(forResource: "test-dangerous-link", ofType: "xml")! + let testData = NSData(contentsOfFile: testFile)! + + do { + let baseURL: URL? = nil + + let stateResolver = SPUAppcastItemStateResolver(hostVersion: "1.0", applicationVersionComparator: SUStandardVersionComparator.default, standardVersionComparator: SUStandardVersionComparator.default) + + let appcast = try SUAppcast(xmlData: testData as Data, relativeTo: baseURL, stateResolver: stateResolver, signingValidationStatus: .failed) + + // Links and info only and critical updates should be stripped/removed appropriately + + XCTAssertEqual(appcast.items.count, 2) + XCTAssertEqual(appcast.signingValidationStatus, .failed) + + for (appcastItemIndex, appcastItem) in appcast.items.enumerated() { + XCTAssertNil(appcastItem.infoURL) + XCTAssertNil(appcastItem.releaseNotesURL) + XCTAssertNil(appcastItem.fullReleaseNotesURL) + XCTAssertFalse(appcastItem.isCriticalUpdate) + + if appcastItemIndex == 0 { + XCTAssertEqual(appcastItem.versionString, "3.0 (Visit abc.") + } else if appcastItemIndex == 1 { + XCTAssertEqual(appcastItem.displayVersionString, "2.0 (Visit abc.") + } + } + } catch let err as NSError { + NSLog("Expected error: %@", err) + XCTFail("Appcast creation should have passed when encountering dangerous link of one item") + } + } } diff --git a/Tests/SUFeedSignatureVerifierTest.swift b/Tests/SUFeedSignatureVerifierTest.swift new file mode 100644 index 00000000..dd0a5fe2 --- /dev/null +++ b/Tests/SUFeedSignatureVerifierTest.swift @@ -0,0 +1,146 @@ +// +// SUFeedSignatureVerifierTest.swift +// Sparkle Unit Tests +// +// Created on 12/30/25. +// Copyright © 2025 Sparkle Project. All rights reserved. +// + +import Foundation +import XCTest + +class SUFeedSignatureVerifierTest: XCTestCase { + var privateEdKey: Data! + var publicEdKey: Data! + + override func setUp() { + super.setUp() + + // These are the same private and public keys the Sparkle Test App uses + + let privateKeyBytes: [UInt8] = [ + 200, 238, 135, 84, 10, 189, 3, 193, + 61, 208, 203, 30, 133, 47, 12, 22, + 19, 52, 252, 99, 110, 205, 209, 94, + 215, 144, 201, 70, 27, 162, 163, 108, + 0, 164, 68, 184, 226, 93, 121, 199, + 172, 17, 26, 64, 89, 68, 232, 41, + 2, 26, 245, 175, 158, 165, 42, 55, + 5, 97, 8, 243, 251, 164, 93, 9 + ] + + privateEdKey = Data(privateKeyBytes) + + let publicKeyBytes: [UInt8] = [ + 121, 17, 79, 45, 155, 141, 51, 169, + 188, 110, 91, 102, 182, 147, 215, 225, + 252, 202, 110, 231, 200, 215, 62, 171, + 40, 145, 237, 128, 130, 44, 150, 89 + ] + + publicEdKey = Data(publicKeyBytes) + } + + func testSigningAndValidatingAppcast() { + let appcastURL = Bundle(for: SUFeedSignatureVerifierTest.self).url(forResource: "testappcast", withExtension: "xml")! + + let initialAppcastData = try! Data(contentsOf: appcastURL) + + let publicKeys = SUPublicKeys(ed: publicEdKey.base64EncodedString(), dsa: nil) + let signatureVerifier = SUSignatureVerifier(publicKeys: publicKeys) + + // The content should be the same as the initial appcast data which isn't signed yet + do { + var outEdSignatureBase64: NSString? + var outContentLength: UInt64 = 0 + let appcastContentData = SPUExtractAppcastContent(initialAppcastData, &outEdSignatureBase64, &outContentLength) + + XCTAssertNil(outEdSignatureBase64) + XCTAssertEqual(outContentLength, 0) + XCTAssertEqual(initialAppcastData, appcastContentData) + + // Trying to verify this file should fail when no signature is present + let signatures = SUSignatures(ed: outEdSignatureBase64 as? String, dsa: nil) + + let verifierInformation = SPUVerifierInformation(expectedVersion: nil, expectedContentLength: outContentLength) + verifierInformation.actualContentLength = UInt64(appcastContentData.count) + + do { + try signatureVerifier.verifyData(appcastContentData, signatures: signatures, fileKind: "appcast", verifierInformation: verifierInformation) + XCTFail("Verification should have failed on unsigned file") + } catch { + XCTAssertNotNil(error) + } + } + + // Add sign warning to appcast + let appcastDataWithSigningWarning = addSignWarningToAppcast(data: initialAppcastData) + XCTAssertGreaterThan(appcastDataWithSigningWarning.count, initialAppcastData.count) + + // Adding a signing warning to appcast shouldn't change anything + do { + let appcastDataWithSigningWarningAgain = addSignWarningToAppcast(data: appcastDataWithSigningWarning) + XCTAssertEqual(appcastDataWithSigningWarningAgain, appcastDataWithSigningWarning) + } + + let signedAppcastData = try! signAppcast(data: appcastDataWithSigningWarning, publicEdKey: publicEdKey, privateEdKey: privateEdKey) + + // XML data should be valid after signing + _ = try! XMLDocument(data: signedAppcastData, options: XMLNode.Options()) + + do { + // Content of signed data should be same as content before it + + var outEdSignatureBase64: NSString? + var outContentLength: UInt64 = 0 + let contentSignedAppcastData = SPUExtractAppcastContent(signedAppcastData, &outEdSignatureBase64, &outContentLength) + + XCTAssertNotNil(outEdSignatureBase64) + XCTAssertEqual(outContentLength, UInt64(appcastDataWithSigningWarning.count)) + XCTAssertEqual(contentSignedAppcastData, appcastDataWithSigningWarning) + + // Verify the signature is correct + + let signatures = SUSignatures(ed: outEdSignatureBase64! as String, dsa: nil) + let verifierInformation = SPUVerifierInformation(expectedVersion: nil, expectedContentLength: UInt64(appcastDataWithSigningWarning.count)) + verifierInformation.actualContentLength = UInt64(contentSignedAppcastData.count) + + try! signatureVerifier.verifyData(contentSignedAppcastData, signatures: signatures, fileKind: "appcast", verifierInformation: verifierInformation) + + // Insert a byte somewhere in the middle and ensure signing validation fails + var modifiedInvalidSignedAppcastData = signedAppcastData + modifiedInvalidSignedAppcastData.insert(62, at: signedAppcastData.count / 2) + + do { + try signatureVerifier.verifyData(modifiedInvalidSignedAppcastData, signatures: signatures, fileKind: "appcast", verifierInformation: nil) + XCTFail("Signature verification of modified appcast should have failed") + } catch { + XCTAssertNotNil(error) + } + + // Re-signing should fix the signature however + let modifiedSignedAppcastData = try! signAppcast(data: modifiedInvalidSignedAppcastData, publicEdKey: publicEdKey, privateEdKey: privateEdKey) + + let modifiedSignedAppcastDataContent = SPUExtractAppcastContent(modifiedSignedAppcastData, &outEdSignatureBase64, &outContentLength) + + let signaturesAfterModification = SUSignatures(ed: outEdSignatureBase64! as String, dsa: nil) + try! signatureVerifier.verifyData(modifiedSignedAppcastDataContent, signatures: signaturesAfterModification, fileKind: "appcast", verifierInformation: nil) + } + } + + func testAddingSignWarningToHTMLReleaseNotes() { + let releaseNotesURL = Bundle(for: SUFeedSignatureVerifierTest.self).url(forResource: "testreleasenotes", withExtension: "html")! + + let releaseNotesData = try! Data(contentsOf: releaseNotesURL) + + // Add sign warning to release notes + let releaseNotesDataWithSigningWarning = updateHTMLCommentSigningWarningInReleaseNotes(data: releaseNotesData)! + XCTAssertGreaterThan(releaseNotesDataWithSigningWarning.count, releaseNotesData.count) + + // Test that the content is the same minus the beginning signing warning + do { + let byteDifference = releaseNotesDataWithSigningWarning.count - releaseNotesData.count + XCTAssertEqual(releaseNotesDataWithSigningWarning.subdata(in: releaseNotesDataWithSigningWarning.startIndex.advanced(by: byteDifference) ..< releaseNotesDataWithSigningWarning.endIndex), releaseNotesData) + } + } +} diff --git a/Tests/Sparkle Unit Tests-Bridging-Header.h b/Tests/Sparkle Unit Tests-Bridging-Header.h index 82a83790..54e3d433 100644 --- a/Tests/Sparkle Unit Tests-Bridging-Header.h +++ b/Tests/Sparkle Unit Tests-Bridging-Header.h @@ -22,6 +22,9 @@ #import "SUSignatures.h" #import "SPUInstallationType.h" #import "SPUAppcastItemStateResolver.h" +#import "SPUExtractAppcast.h" +#import "SUSignatureVerifier.h" +#import "ed25519.h" NS_ASSUME_NONNULL_BEGIN diff --git a/common_cli/secret.swift b/common_cli/Secret.swift similarity index 100% rename from common_cli/secret.swift rename to common_cli/Secret.swift diff --git a/common_cli/Signing.swift b/common_cli/Signing.swift new file mode 100644 index 00000000..530ba12f --- /dev/null +++ b/common_cli/Signing.swift @@ -0,0 +1,218 @@ +// +// signing.swift +// Sparkle +// +// Created on 12/26/25. +// Copyright © 2025 Sparkle Project. All rights reserved. +// + +import Foundation + +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 + } +} + +enum SigningError: Error { + case failedToDecodeSigningBlockAsUTF8 +} + +// All of these are for legacy DSA related errors +enum DSAError: Error { + case invalidOpenSSLFormat + case invalidSecTransformData + case secKeychainOpenFailure + case secItemImportFailure + case secItemCopyFailure +} + +// Adds a XML comment at the begining warning the developer about making future modifications to this signed appcast. +func addSignWarningToAppcast(data inputData: Data) -> Data { + let xmlData: Data + do { + let signWarningPrefix = " sparkle-sign-warning:" + let signWarningMessage = "\nIMPORTANT: This file was signed by Sparkle. Any modifications to this file requires re-signing this file with generate_appcast or sign_update! The signed signature will be embedded at the end of this file.\n" + + let readOptions: XMLNode.Options = [ + XMLNode.Options.nodeLoadExternalEntitiesNever, + XMLNode.Options.nodePreserveCDATA, + XMLNode.Options.nodePreserveWhitespace, + ] + + do { + let document = try XMLDocument(data: inputData, options: readOptions) + + var foundSignWarningComment: Bool = false + if let documentChildren = document.children { + for child in documentChildren { + if child.kind == .comment, let commentValue = child.stringValue, commentValue.hasPrefix(signWarningPrefix) { + foundSignWarningComment = true + break + } + } + } + + if !foundSignWarningComment { + let newSigningWarningMessage = "\(signWarningPrefix)\(signWarningMessage)" + + let newCommentNode = XMLNode(kind: .comment) + newCommentNode.stringValue = newSigningWarningMessage + document.insertChild(newCommentNode, at: 0) + + let writeOptions: XMLNode.Options = [.nodeCompactEmptyElement, .nodePrettyPrint] + xmlData = document.xmlData(options: writeOptions) + } else { + xmlData = inputData + } + } catch { + print("Error: failed to parse XML data: \(error)") + xmlData = inputData + } + } + + return xmlData +} + +// Sign the contents of the XML data, and append the signing block (containing the signature / other info) +// to the end of the appcast data. +// The input data should have the signing block already stripped (use SPUExtractAppcastContent() +func signAppcast(data contentData: Data, publicEdKey: Data, privateEdKey: Data) throws -> Data { + let base64Signature = edSignature(data: contentData, publicEdKey: publicEdKey, privateEdKey: privateEdKey) + + let signingBlock = "\n" + + guard let signingBlockData = signingBlock.data(using: .utf8) else { + // Extremely unlikely to occur + throw SigningError.failedToDecodeSigningBlockAsUTF8 + } + + var signedData = contentData + signedData.append(signingBlockData) + + return signedData +} + +// This inserts a HTML comment in the beginning of the data warning the developer +// that future modifications to this file will require it to be re-signed +func updateHTMLCommentSigningWarningInReleaseNotes(data: Data) -> Data? { + let modificationWarningPrefix = "\n" + + let modificationWarningMessage = "\(modificationWarningPrefix)\nIMPORTANT: This file was signed by Sparkle. Any modifications to this file requires updating signatures in appcasts that reference this file! This will involve re-running generate_appcast or sign_update.\n\(modificationWarningSuffix)" + + var dataToSign = data + dataToSign.insert(contentsOf: Data(modificationWarningMessage.utf8), at: dataToSign.startIndex) + + return dataToSign +} + +#if GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT +func loadPrivateDSAKey(at privateKeyURL: URL) throws -> SecKey { + let data = try Data(contentsOf: privateKeyURL) + + var cfitems: CFArray? + var format = SecExternalFormat.formatOpenSSL + var type = SecExternalItemType.itemTypePrivateKey + + let status = SecItemImport(data as CFData, nil, &format, &type, SecItemImportExportFlags(rawValue: UInt32(0)), nil, nil, &cfitems) + if status != errSecSuccess || cfitems == nil { + print("Private DSA key file", privateKeyURL.path, "exists, but it could not be read. SecItemImport error", status) + throw DSAError.secItemImportFailure + } + + if format != SecExternalFormat.formatOpenSSL || type != SecExternalItemType.itemTypePrivateKey { + print("Not an OpensSSL private key \(format) \(type)") + throw DSAError.invalidOpenSSLFormat + } + + return (cfitems! as NSArray)[0] as! SecKey +} + +func loadPrivateDSAKey(named keyName: String, fromKeychainAt keychainURL: URL) throws -> SecKey { + var keychain: SecKeychain? + + guard SecKeychainOpen(keychainURL.path, &keychain) == errSecSuccess, keychain != nil else { + throw DSAError.secKeychainOpenFailure + } + + let query: [CFString: CFTypeRef] = [ + kSecClass: kSecClassKey, + kSecAttrKeyClass: kSecAttrKeyClassPrivate, + kSecAttrLabel: keyName as CFString, + kSecMatchLimit: kSecMatchLimitOne, + kSecUseKeychain: keychain!, + kSecReturnRef: kCFBooleanTrue, + ] + + var item: CFTypeRef? + guard SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess, item != nil else { + throw DSAError.secItemCopyFailure + } + + return item! as! SecKey +} + +func dsaSignature(path: URL, privateDSAKey: SecKey) throws -> String { + + var error: Unmanaged? + + let stream = InputStream(fileAtPath: path.path)! + let dataReadTransform = SecTransformCreateReadTransformWithReadStream(stream) + + let dataDigestTransform = SecDigestTransformCreate(kSecDigestSHA1, 20, nil) + guard let dataSignTransform = SecSignTransformCreate(privateDSAKey, &error) else { + print("can't use the key") + throw error!.takeRetainedValue() + } + + let group = SecTransformCreateGroupTransform() + SecTransformConnectTransforms(dataReadTransform, kSecTransformOutputAttributeName, dataDigestTransform, kSecTransformInputAttributeName, group, &error) + if error != nil { + throw error!.takeRetainedValue() + } + + SecTransformConnectTransforms(dataDigestTransform, kSecTransformOutputAttributeName, dataSignTransform, kSecTransformInputAttributeName, group, &error) + if error != nil { + throw error!.takeRetainedValue() + } + + let result = SecTransformExecute(group, &error) + if error != nil { + throw error!.takeRetainedValue() + } + guard let resultData = result as? Data else { + throw DSAError.invalidSecTransformData + } + return resultData.base64EncodedString() +} +#endif + +func edSignature(data: Data, publicEdKey: Data, privateEdKey: Data) -> String { + assert(publicEdKey.count == 32) + assert(privateEdKey.count == 64) + let data = Array(data) + var output = Array(repeating: 0, count: 64) + let pubkey = Array(publicEdKey), privkey = Array(privateEdKey) + + ed25519_sign(&output, data, data.count, pubkey, privkey) + return Data(output).base64EncodedString() +} + +func edSignature(path: URL, publicEdKey: Data, privateEdKey: Data) throws -> String { + let data = try Data(contentsOf: path, options: .mappedIfSafe) + return edSignature(data: data, publicEdKey: publicEdKey, privateEdKey: privateEdKey) +} diff --git a/generate_appcast/ArchiveItem.swift b/generate_appcast/ArchiveItem.swift index 234fe82d..e424623e 100644 --- a/generate_appcast/ArchiveItem.swift +++ b/generate_appcast/ArchiveItem.swift @@ -77,6 +77,7 @@ class ArchiveItem: CustomStringConvertible { let feedURL: URL? let publicEdKey: Data? let supportsDSA: Bool + let requiresSignedAppcast: Bool let archiveFileAttributes: [FileAttributeKey: Any] var deltas: [DeltaUpdate] @@ -174,10 +175,11 @@ class ArchiveItem: CustomStringConvertible { } } - init(version: String, shortVersion: String?, feedURL: URL?, minimumSystemVersion: String?, hardwareRequirements: String?, frameworkVersion: String?, sparkleExecutableFileSize: Int?, sparkleLocales: String?, publicEdKey: String?, supportsDSA: Bool, appPath: URL, archivePath: URL) throws { + init(version: String, shortVersion: String?, feedURL: URL?, requiresSignedAppcast: Bool, minimumSystemVersion: String?, hardwareRequirements: String?, frameworkVersion: String?, sparkleExecutableFileSize: Int?, sparkleLocales: String?, publicEdKey: String?, supportsDSA: Bool, appPath: URL, archivePath: URL) throws { self.version = version self._shortVersion = shortVersion self.feedURL = feedURL + self.requiresSignedAppcast = requiresSignedAppcast self.minimumSystemVersion = minimumSystemVersion ?? "10.13" self.hardwareRequirements = hardwareRequirements self.frameworkVersion = frameworkVersion @@ -251,6 +253,13 @@ class ArchiveItem: CustomStringConvertible { } } + let requiresSignedAppcast: Bool + if let requiresSignedAppcastValue = infoPlist[SURequireSignedFeedKey] as? Bool { + requiresSignedAppcast = requiresSignedAppcastValue + } else { + requiresSignedAppcast = false + } + // Intel Macs shouldn't be supported on macOS 27+ and // we don't have any other hardware requirements except for arm64 right now var mayNeedHardwareRequirement = true @@ -358,6 +367,7 @@ class ArchiveItem: CustomStringConvertible { try self.init(version: version, shortVersion: shortVersion, feedURL: feedURL, + requiresSignedAppcast: requiresSignedAppcast, minimumSystemVersion: minimumSystemVersion, hardwareRequirements: hardwareRequirements, frameworkVersion: frameworkVersion, @@ -405,7 +415,7 @@ class ArchiveItem: CustomStringConvertible { return (self.archiveFileAttributes[.size] as! NSNumber).int64Value } - private var releaseNotesPath: URL? { + var releaseNotesPath: URL? { var basename = self.archivePath.deletingPathExtension() if basename.pathExtension == "tar" { // tar.gz basename = basename.deletingPathExtension() @@ -467,15 +477,12 @@ class ArchiveItem: CustomStringConvertible { return nil } - func releaseNotesURL(embedReleaseNotesAlways: Bool) -> URL? { - guard let path = self.releaseNotesPath else { - return nil - } + func releaseNotesURL(releaseNotesPath: URL, embedReleaseNotesAlways: Bool) -> URL? { // The file is already used as inline description - if self.getReleaseNotesAsFragment(path, embedReleaseNotesAlways) != nil { + if self.getReleaseNotesAsFragment(releaseNotesPath, embedReleaseNotesAlways) != nil { return nil } - return self.releaseNoteURL(for: path.lastPathComponent) + return self.releaseNoteURL(for: releaseNotesPath.lastPathComponent) } func releaseNoteURL(for unescapedFilename: String) -> URL? { @@ -492,12 +499,12 @@ class ArchiveItem: CustomStringConvertible { } } - func localizedReleaseNotes() -> [(String, URL)] { + func localizedReleaseNotes() -> [(String, URL, URL)] { var basename = archivePath.deletingPathExtension() if basename.pathExtension == "tar" { basename = basename.deletingPathExtension() } - var localizedReleaseNotes = [(String, URL)]() + var localizedReleaseNotes = [(String, URL, URL)]() for languageCode in Locale.isoLanguageCodes { let baseLocalizedReleaseNoteURL = basename .appendingPathExtension(languageCode) @@ -524,7 +531,7 @@ class ArchiveItem: CustomStringConvertible { if let localizedReleaseNoteURL = localizedReleaseNoteURL, let localizedReleaseNoteRemoteURL = self.releaseNoteURL(for: localizedReleaseNoteURL.lastPathComponent) { - localizedReleaseNotes.append((languageCode, localizedReleaseNoteRemoteURL)) + localizedReleaseNotes.append((languageCode, localizedReleaseNoteRemoteURL, localizedReleaseNoteURL)) } } return localizedReleaseNotes diff --git a/generate_appcast/Bridging-Header.h b/generate_appcast/Bridging-Header.h index ab24116b..64e905de 100644 --- a/generate_appcast/Bridging-Header.h +++ b/generate_appcast/Bridging-Header.h @@ -1,5 +1,6 @@ #import +#import "SPUExtractAppcast.h" #import "SUStandardVersionComparator.h" #import "SUConstants.h" #import "SUErrors.h" diff --git a/generate_appcast/FeedXML.swift b/generate_appcast/FeedXML.swift index 03acd26a..91e53991 100644 --- a/generate_appcast/FeedXML.swift +++ b/generate_appcast/FeedXML.swift @@ -150,11 +150,72 @@ func readAppcast(archives: [String: ArchiveItem], appcastURL: URL) throws -> [St return updateBranches } -func writeAppcast(appcastDestPath: URL, appcast: Appcast, fullReleaseNotesLink: String?, preferToEmbedReleaseNotes: Bool, link: String?, newChannel: String?, newMinimumUpdateVersion: String?, majorVersion: String?, ignoreSkippedUpgradesBelowVersion: String?, phasedRolloutInterval: Int?, criticalUpdateVersion: String?, informationalUpdateVersions: [String]?) throws -> (numNewUpdates: Int, numExistingUpdates: Int, numUpdatesRemoved: Int) { +private func signReleaseNotesIfNeeded(element releaseNotesElement: XMLElement, filePath unresolvedReleaseNotesPath: URL, signedReleaseNoteFiles: inout [String: (String, UInt)], requiresSignedAppcast: Bool, disableEmbeddedSignWarning: Bool, keys: PrivateKeys) throws { + guard let publicEdKey = keys.publicEdKey, let privateEdKey = keys.privateEdKey else { + return + } + + let existingEdSignatureAttribute = releaseNotesElement.attribute(forName: SUAppcastAttributeEDSignature) + guard requiresSignedAppcast || existingEdSignatureAttribute != nil else { + return + } + + let resolvedReleaseNotesPath = unresolvedReleaseNotesPath.resolvingSymlinksInPath() + + let releaseNotesBase64Signature: String + let releaseNotesLength: UInt + if let (existingReleaseNotesBase64Signature, existingReleaseNotesLength) = signedReleaseNoteFiles[resolvedReleaseNotesPath.path] { + releaseNotesBase64Signature = existingReleaseNotesBase64Signature + releaseNotesLength = existingReleaseNotesLength + } else { + var releaseNotesData = try Data(contentsOf: resolvedReleaseNotesPath) + + if !disableEmbeddedSignWarning { + // Update release notes file (except for plain-text ones) to include warning about making + // future modifications in the file + let pathExtension = resolvedReleaseNotesPath.pathExtension + if pathExtension == "html" || pathExtension == "md" || pathExtension == "markdown" { + do { + if let updatedReleaseNotesData = updateHTMLCommentSigningWarningInReleaseNotes(data: releaseNotesData) { + try updatedReleaseNotesData.write(to: resolvedReleaseNotesPath, options: .atomic) + print("Updated \(resolvedReleaseNotesPath.lastPathComponent) to include signing warning for making further modifications.") + + releaseNotesData = updatedReleaseNotesData + } + } catch { + // Fallback to using original release notes + print("Warning: failed to update release notes to include signing warning for making further modifications. Skipping updating \(resolvedReleaseNotesPath.path)") + } + } + } + + releaseNotesBase64Signature = try edSignature(path: resolvedReleaseNotesPath, publicEdKey: publicEdKey, privateEdKey: privateEdKey) + releaseNotesLength = UInt(releaseNotesData.count) + + signedReleaseNoteFiles[resolvedReleaseNotesPath.path] = (releaseNotesBase64Signature, releaseNotesLength) + } + + if let existingEdSignatureAttribute { + existingEdSignatureAttribute.stringValue = releaseNotesBase64Signature + } else { + let signatureAttribute = XMLNode.attribute(withName: SUAppcastAttributeEDSignature, stringValue: releaseNotesBase64Signature) as! XMLNode + releaseNotesElement.addAttribute(signatureAttribute) + } + + if let existingLengthAttribute = releaseNotesElement.attribute(forName: SUAppcastAttributeLength) { + existingLengthAttribute.stringValue = "\(releaseNotesLength)" + } else { + let lengthAttribute = XMLNode.attribute(withName: SUAppcastAttributeLength, stringValue: "\(releaseNotesLength)") as! XMLNode + releaseNotesElement.addAttribute(lengthAttribute) + } +} + +func writeAppcast(appcastDestPath: URL, keys: PrivateKeys, disableEmbeddedSignWarning: Bool, appcast: Appcast, fullReleaseNotesLink: String?, preferToEmbedReleaseNotes: Bool, link: String?, newChannel: String?, newMinimumUpdateVersion: String?, majorVersion: String?, ignoreSkippedUpgradesBelowVersion: String?, phasedRolloutInterval: Int?, criticalUpdateVersion: String?, informationalUpdateVersions: [String]?) throws -> (numNewUpdates: Int, numExistingUpdates: Int, numUpdatesRemoved: Int) { let appBaseName = appcast.inferredAppName let sparkleNS = "http://www.andymatuschak.org/xml-namespaces/sparkle" + let appcastWasPreviouslySigned: Bool var doc: XMLDocument do { let options: XMLNode.Options = [ @@ -162,13 +223,20 @@ func writeAppcast(appcastDestPath: URL, appcast: Appcast, fullReleaseNotesLink: XMLNode.Options.nodePreserveCDATA, XMLNode.Options.nodePreserveWhitespace, ] - doc = try XMLDocument(contentsOf: appcastDestPath, options: options) + + let xmlData = try Data(contentsOf: appcastDestPath) + doc = try XMLDocument(data: xmlData, options: options) + + let contentData = SPUExtractAppcastContent(xmlData, nil, nil) + appcastWasPreviouslySigned = contentData.count != xmlData.count } catch { let root = XMLElement(name: "rss") root.addAttribute(XMLNode.attribute(withName: "xmlns:sparkle", stringValue: sparkleNS) as! XMLNode) root.addAttribute(XMLNode.attribute(withName: "version", stringValue: "2.0") as! XMLNode) doc = XMLDocument(rootElement: root) doc.isStandalone = true + + appcastWasPreviouslySigned = false } var channel: XMLElement @@ -224,11 +292,36 @@ func writeAppcast(appcastDestPath: URL, appcast: Appcast, fullReleaseNotesLink: root.addChild(channel) } + // If appcast has not already been signed, see if any of its update archives require signing + let requiresSignedAppcast: Bool + if appcastWasPreviouslySigned { + requiresSignedAppcast = true + } else { + var requiresSignedAppcastFromArchives = false + for version in appcast.versionsInFeed { + guard let update = appcast.archives[version] else { + continue + } + + if update.requiresSignedAppcast { + requiresSignedAppcastFromArchives = true + break + } + } + + requiresSignedAppcast = requiresSignedAppcastFromArchives + } + + // Keep track of already signed release note files so we avoid + // re-signing the same file in case the developer is using symlinks + // Path -> [(EdSignature, Length)] + var signedReleaseNoteFiles: [String: (String, UInt)] = [:] + var numNewUpdates = 0 var numExistingUpdates = 0 let versionComparator = SUStandardVersionComparator() - + var numItems = 0 for version in appcast.versionsInFeed { guard let update = appcast.archives[version] else { @@ -432,35 +525,57 @@ func writeAppcast(appcastDestPath: URL, appcast: Appcast, fullReleaseNotesLink: item.removeChild(at: existingDescriptionElement.index) } - if let url = update.releaseNotesURL(embedReleaseNotesAlways: embedReleaseNotesAlways) { + if let releaseNotesFilePath = update.releaseNotesPath, + let url = update.releaseNotesURL(releaseNotesPath: releaseNotesFilePath, embedReleaseNotesAlways: embedReleaseNotesAlways) { // The update includes a valid release notes URL + let releaseNotesElement: XMLElement if let existingReleaseNotesElement = relElement { - // The existing item includes a release notes element. Update it. - existingReleaseNotesElement.stringValue = url.absoluteString + releaseNotesElement = existingReleaseNotesElement } else { - // The existing item doesn't have a release notes element. Add one. - item.addChild(XMLElement.element(withName: SUAppcastElementReleaseNotesLink, stringValue: url.absoluteString) as! XMLElement) + releaseNotesElement = XMLElement.element(withName: SUAppcastElementReleaseNotesLink) as! XMLElement + item.addChild(releaseNotesElement) } + + // Update release notes + releaseNotesElement.stringValue = url.absoluteString + + // Sign the release notes + try signReleaseNotesIfNeeded(element: releaseNotesElement, filePath: releaseNotesFilePath, signedReleaseNoteFiles: &signedReleaseNoteFiles, requiresSignedAppcast: requiresSignedAppcast, disableEmbeddedSignWarning: disableEmbeddedSignWarning, keys: keys) } else if let childIndex = relElement?.index { // The update doesn't include a release notes URL. Remove it. item.removeChild(at: childIndex) } + // Retrieve all existing language nodes for release notes let languageNotesNodes = ((try? item.nodes(forXPath: releaseNotesXpath)) as? [XMLElement])? .map { ($0, $0.attribute(forName: SUXMLLanguage)?.stringValue )} .filter { $0.1 != nil } ?? [] + + // Remove all language nodes that don't have corresponding release notes file + let localizedReleaseNotes = update.localizedReleaseNotes() for (node, language) in languageNotesNodes.reversed() - where !update.localizedReleaseNotes().contains(where: { $0.0 == language }) { + where !localizedReleaseNotes.contains(where: { $0.0 == language }) { item.removeChild(at: node.index) } - for (language, url) in update.localizedReleaseNotes() { - if !languageNotesNodes.contains(where: { $0.1 == language }) { + // Update all existing and insert missing localized release notes nodes + for (language, url, releaseNotesFilePath) in localizedReleaseNotes { + let localizedReleaseNotesElement: XMLElement + if let foundNodeIndex = languageNotesNodes.firstIndex(where: { $0.1 == language }) { + localizedReleaseNotesElement = languageNotesNodes[foundNodeIndex].0 + localizedReleaseNotesElement.stringValue = url.absoluteString + } else { let localizedNode = XMLNode.element( withName: SUAppcastElementReleaseNotesLink, children: [XMLNode.text(withStringValue: url.absoluteString) as! XMLNode], - attributes: [XMLNode.attribute(withName: SUXMLLanguage, stringValue: language) as! XMLNode]) - item.addChild(localizedNode as! XMLNode) + attributes: [XMLNode.attribute(withName: SUXMLLanguage, stringValue: language) as! XMLNode]) as! XMLElement + + item.addChild(localizedNode) + + localizedReleaseNotesElement = localizedNode } + + // Sign the localized release notes + try signReleaseNotesIfNeeded(element: localizedReleaseNotesElement, filePath: releaseNotesFilePath, signedReleaseNoteFiles: &signedReleaseNoteFiles, requiresSignedAppcast: requiresSignedAppcast, disableEmbeddedSignWarning: disableEmbeddedSignWarning, keys: keys) } var enclosure = findElement(name: "enclosure", parent: item) @@ -525,9 +640,20 @@ func writeAppcast(appcastDestPath: URL, appcast: Appcast, fullReleaseNotesLink: } let options: XMLNode.Options = [.nodeCompactEmptyElement, .nodePrettyPrint] - let docData = doc.xmlData(options: options) - _ = try XMLDocument(data: docData, options: XMLNode.Options()); // Verify that it was generated correctly, which does not always happen! - try docData.write(to: appcastDestPath) + let unsignedDocData = doc.xmlData(options: options) + + // Sign the appcast if needed + let finalDocData: Data + if requiresSignedAppcast, let publicKey = keys.publicEdKey, let privateKey = keys.privateEdKey { + let contentData = SPUExtractAppcastContent(unsignedDocData, nil, nil) + let dataToSign = disableEmbeddedSignWarning ? contentData : addSignWarningToAppcast(data: contentData) + finalDocData = try signAppcast(data: dataToSign, publicEdKey: publicKey, privateEdKey: privateKey) + } else { + finalDocData = unsignedDocData + } + + _ = try XMLDocument(data: finalDocData, options: XMLNode.Options()); // Verify that it was generated correctly, which does not always happen! + try finalDocData.write(to: appcastDestPath) return (numNewUpdates, numExistingUpdates, numUpdatesRemoved) } diff --git a/generate_appcast/Signatures.swift b/generate_appcast/Signatures.swift deleted file mode 100644 index 8bd3041f..00000000 --- a/generate_appcast/Signatures.swift +++ /dev/null @@ -1,109 +0,0 @@ -// -// Created by Kornel on 23/12/2016. -// Copyright © 2016 Sparkle Project. All rights reserved. -// - -import Foundation - -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 - } -} - -#if GENERATE_APPCAST_BUILD_LEGACY_DSA_SUPPORT -func loadPrivateDSAKey(at privateKeyURL: URL) throws -> SecKey { - let data = try Data(contentsOf: privateKeyURL) - - var cfitems: CFArray? - var format = SecExternalFormat.formatOpenSSL - var type = SecExternalItemType.itemTypePrivateKey - - let status = SecItemImport(data as CFData, nil, &format, &type, SecItemImportExportFlags(rawValue: UInt32(0)), nil, nil, &cfitems) - if status != errSecSuccess || cfitems == nil { - print("Private DSA key file", privateKeyURL.path, "exists, but it could not be read. SecItemImport error", status) - throw NSError(domain: SUSparkleErrorDomain, code: Int(OSStatus(SUError.signatureError.rawValue)), userInfo: nil) - } - - if format != SecExternalFormat.formatOpenSSL || type != SecExternalItemType.itemTypePrivateKey { - throw makeError(code: .signatureError, "Not an OpensSSL private key \(format) \(type)") - } - - return (cfitems! as NSArray)[0] as! SecKey -} - -func loadPrivateDSAKey(named keyName: String, fromKeychainAt keychainURL: URL) throws -> SecKey { - var keychain: SecKeychain? - - 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, - kSecAttrLabel: keyName as CFString, - kSecMatchLimit: kSecMatchLimitOne, - kSecUseKeychain: keychain!, - kSecReturnRef: kCFBooleanTrue, - ] - - var item: CFTypeRef? - 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, privateDSAKey: SecKey) throws -> String { - - var error: Unmanaged? - - let stream = InputStream(fileAtPath: path.path)! - let dataReadTransform = SecTransformCreateReadTransformWithReadStream(stream) - - let dataDigestTransform = SecDigestTransformCreate(kSecDigestSHA1, 20, nil) - guard let dataSignTransform = SecSignTransformCreate(privateDSAKey, &error) else { - print("can't use the key") - throw error!.takeRetainedValue() - } - - let group = SecTransformCreateGroupTransform() - SecTransformConnectTransforms(dataReadTransform, kSecTransformOutputAttributeName, dataDigestTransform, kSecTransformInputAttributeName, group, &error) - if error != nil { - throw error!.takeRetainedValue() - } - - SecTransformConnectTransforms(dataDigestTransform, kSecTransformOutputAttributeName, dataSignTransform, kSecTransformInputAttributeName, group, &error) - if error != nil { - throw error!.takeRetainedValue() - } - - let result = SecTransformExecute(group, &error) - if error != nil { - throw error!.takeRetainedValue() - } - guard let resultData = result as? Data else { - throw makeError(code: .signatureError, "SecTransformExecute returned non-data") - } - return resultData.base64EncodedString() -} -#endif - -func edSignature(path: URL, publicEdKey: Data, privateEdKey: Data) throws -> String { - assert(publicEdKey.count == 32) - assert(privateEdKey.count == 64) - let data = Array(try Data.init(contentsOf: path, options: .mappedIfSafe)) - var output = Array(repeating: 0, count: 64) - let pubkey = Array(publicEdKey), privkey = Array(privateEdKey) - - ed25519_sign(&output, data, data.count, pubkey, privkey) - return Data(output).base64EncodedString() -} diff --git a/generate_appcast/main.swift b/generate_appcast/main.swift index 5772bf9d..958410e3 100644 --- a/generate_appcast/main.swift +++ b/generate_appcast/main.swift @@ -165,6 +165,10 @@ struct GenerateAppcast: ParsableCommand { @Argument(help: "The path to the directory containing the update archives and delta files.", transform: { URL(fileURLWithPath: $0, isDirectory: true) }) var archivesSourceDir: URL + // Disables embedding sign warning when signing appcast XML feeds or HTML/markdown release note files + @Flag(name: .long, help: .hidden) + var disableEmbeddedSignWarning: Bool = false + @Flag(help: .hidden) var verbose: Bool = false @@ -190,20 +194,22 @@ struct GenerateAppcast: ParsableCommand { For HTML release notes, if the contents of these files do not include a DOCTYPE or body tags, they will be treated as embedded CDATA release notes. Release notes for new items can be forced to be embedded by passing --embed-release-notes - For new update entries, Sparkle infers the minimum system OS and hardware requirements based on your update's bundle. + If appcast signing is required by any of the updates, the appcast and release note files may be updated for signing. If you make any manual modifications to the appcast or release note files, please re-run \(programName) to ensure all signatures are updated. + + For new update entries, Sparkle infers the minimum system OS and hardware requirements based on your update's bundle (e.g. via inspecting LSMinimumSystemVersion or detecting which architecture slices are available). An example of an archives directory may look like: ./my-app-release-zipfiles/ MyApp 1.0.zip MyApp 1.0.html - MyApp 1.1.zip - MyApp 1.1.html + MyApp 1.1.dmg + MyApp 1.1.md appcast.xml \(oldFilesDirectoryName)/ EXAMPLES: - \(programNamePath) ./my-app-release-zipfiles/ - \(programNamePath) -o appcast-name.xml ./my-app-release-zipfiles/ + \(programNamePath) ./my-app-release-dmg-files/ + \(programNamePath) -o appcast-name.xml ./my-app-release-dmg-files/ For more advanced options that can be used for publishing updates, see https://sparkle-project.org/documentation/publishing/ for further documentation. @@ -331,7 +337,7 @@ struct GenerateAppcast: ParsableCommand { relativeTo: archivesSourceDir) // Write the appcast - let (numNewUpdates, numExistingUpdates, numUpdatesRemoved) = try writeAppcast(appcastDestPath: appcastDestPath, appcast: appcast, fullReleaseNotesLink: fullReleaseNotesURL, preferToEmbedReleaseNotes: embedReleaseNotes, link: link, newChannel: channel, newMinimumUpdateVersion: minimumUpdateVersion, majorVersion: majorVersion, ignoreSkippedUpgradesBelowVersion: ignoreSkippedUpgradesBelowVersion, phasedRolloutInterval: phasedRolloutInterval, criticalUpdateVersion: criticalUpdateVersion, informationalUpdateVersions: informationalUpdateVersions) + let (numNewUpdates, numExistingUpdates, numUpdatesRemoved) = try writeAppcast(appcastDestPath: appcastDestPath, keys: keys, disableEmbeddedSignWarning: disableEmbeddedSignWarning, appcast: appcast, fullReleaseNotesLink: fullReleaseNotesURL, preferToEmbedReleaseNotes: embedReleaseNotes, link: link, newChannel: channel, newMinimumUpdateVersion: minimumUpdateVersion, majorVersion: majorVersion, ignoreSkippedUpgradesBelowVersion: ignoreSkippedUpgradesBelowVersion, phasedRolloutInterval: phasedRolloutInterval, criticalUpdateVersion: criticalUpdateVersion, informationalUpdateVersions: informationalUpdateVersions) // Inform the user, pluralizing "update" if necessary let pluralizeUpdates = { pluralizeWord($0, "update") } diff --git a/sign_update/Bridging-Header.h b/sign_update/Bridging-Header.h index abaa54ee..7240b65b 100644 --- a/sign_update/Bridging-Header.h +++ b/sign_update/Bridging-Header.h @@ -1,5 +1,6 @@ #import +#import "SPUExtractAppcast.h" #import "SUConstants.h" #import "SUErrors.h" #import "SUSignatures.h" diff --git a/sign_update/main.swift b/sign_update/main.swift index 68b3d0c4..546407a6 100644 --- a/sign_update/main.swift +++ b/sign_update/main.swift @@ -85,52 +85,82 @@ func findKeys(inString secretBase64String: String, allowNewFormat: Bool) throws return (privateKey, publicKey) } -func edSignature(data: Data, publicEdKey: Data, privateEdKey: Data) -> String { - assert(publicEdKey.count == 32) - assert(privateEdKey.count == 64) - let data = Array(data) - var output = Array(repeating: 0, count: 64) - let pubkey = Array(publicEdKey), privkey = Array(privateEdKey) - - ed25519_sign(&output, data, data.count, pubkey, privkey) - return Data(output).base64EncodedString() -} - struct SignUpdate: ParsableCommand { static let programName = "sign_update" - @Option(help: ArgumentHelp("The account name in your keychain associated with your private EdDSA (ed25519) key to use for signing the update.")) + @Option(help: ArgumentHelp("The account name in your keychain associated with your private keys to use for signing.")) var account: String = "ed25519" - @Flag(help: ArgumentHelp("Verify that the update is signed correctly. If this is set, a second argument denoting the signature must be passed after the .", valueName: "verify")) + @Flag(help: ArgumentHelp("Verify that the file is signed correctly. If this is set, a second argument denoting the signature must be passed after the .", valueName: "verify")) var verify: Bool = false @Option(name: [.customShort("f"), .customLong("ed-key-file")], help: ArgumentHelp("Path to the file containing the private EdDSA (ed25519) key. '-' can be used to echo the EdDSA key from a 'secret' environment variable to the standard input stream. For example: echo \"$PRIVATE_KEY_SECRET\" | ./\(programName) --ed-key-file -", valueName: "private-key-file")) var privateKeyFile: String? - @Flag(name: .customShort("p"), help: ArgumentHelp("Only prints the signature when signing an update.")) + @Flag(name: .customShort("p"), help: ArgumentHelp("Only prints the signature when signing a file without extra metadata. For signing XML files, nothing will be printed because the signature is embedded inside the file.")) var printOnlySignature: Bool = false - @Argument(help: "The update archive, delta update, or package (pkg) to sign or verify.") - var updatePath: String + @Argument(help: "The update archive, delta update, package (pkg), release notes file, or update feed (xml) to sign or verify. If the file is a update feed (xml), the file will be modified to include the generated signature. If the file is a release notes file, the file may also be updated to include a warning that it is signed.") + var filePath: String - @Argument(help: "The signature to verify when --verify is passed.") + @Argument(help: "The signature to verify when --verify is passed. Don't pass this option for verifying appcast XML feeds, which already have a signature embedded.") var verifySignature: String? @Option(name: .customShort("s"), help: ArgumentHelp("(DEPRECATED): The private EdDSA (ed25519) key. Please use the Keychain, or pass the key as standard input when using --ed-key-file - instead. This option is no longer supported for newly generated keys. ", valueName: "private-key")) var privateKey: String? + // Disables embedding sign warning when signing appcast XML feeds or HTML/markdown release note files + @Flag(name: .long, help: .hidden) + var disableEmbeddedSignWarning: Bool = false + static var configuration: CommandConfiguration = CommandConfiguration( - abstract: "Sign or verify an update using your EdDSA (ed25519) keys.", - discussion: "The EdDSA keys are automatically read from the Keychain if no is specified.\n\nWhen signing, this tool will output an EdDSA signature and length attributes to use for your update's appcast item enclosure. You can use -p to only print the EdDSA signature for automation.") + abstract: "Sign or verify an update file using your signing keys.", + discussion: + """ + sign_update can be used to sign or verify update archives, delta updates, pkg updates, appcast feeds, and release note files. + + The signing keys are automatically read from the Keychain if no is specified. + + For signing update archives, sign_update will output an EdDSA signature and length attributes to use for your update's appcast item enclosure. + + For signing release note files, sign_update will output an EdDSA signature and length attributes to use for your update's appcast releaseNotesLink. Additionally, the release notes file may be modified to include a warning about making future modifications to the file. + + For signing appcast feeds, sign_update will embed the signature inside the XML file and include a warning about making future modifications to the file. + + For signing files, you can use -p to only print the EdDSA signature for automation. + """) + + private var filePathIsFeed: Bool { + return filePath.hasSuffix(".xml") || filePath.hasSuffix(".XML") + } + + private var filePathIsHTMLReleaseNotes: Bool { + return filePath.hasSuffix(".html") || + filePath.hasSuffix(".htm") + } + + private var filePathIsMarkdownReleaseNotes: Bool { + return filePath.hasSuffix(".md") || + filePath.hasSuffix(".markdown") + } + + private var filePathIsReleaseNotes: Bool { + return filePath.hasSuffix(".txt") || + self.filePathIsMarkdownReleaseNotes || + self.filePathIsHTMLReleaseNotes + } func validate() throws { guard privateKey == nil || privateKeyFile == nil else { throw ValidationError("Both --ed-key-file and -s options cannot be provided.") } - guard !verify || verifySignature != nil else { - throw ValidationError(" must be passed as a second argument after if --verify is passed.") + guard !verify || verifySignature != nil || self.filePathIsFeed else { + throw ValidationError(" must be passed as a second argument after if --verify is passed.") + } + + guard !self.filePathIsFeed || verifySignature == nil else { + throw ValidationError(" must not be passed for signing appcast feeds, which already have the signature embedded.") } guard !verify || !printOnlySignature else { @@ -150,17 +180,39 @@ struct SignUpdate: ParsableCommand { } else { (priv, pub) = try findKeysInKeychain(account: account) } + + let fileURL = URL(fileURLWithPath: filePath, isDirectory: false).resolvingSymlinksInPath() - let data = try Data.init(contentsOf: URL.init(fileURLWithPath: updatePath), options: .mappedIfSafe) + let data = try Data.init(contentsOf: fileURL, options: .mappedIfSafe) if verify { // Verify the signature - guard let verifySignature = verifySignature else { - print("Error: failed to unwrap verifySignature, which is unexpected") - throw ExitCode.failure + + let dataToVerify: Data + let base64Signature: String + let expectedContentLength: UInt64 + if let verifySignature { + base64Signature = verifySignature + dataToVerify = data + expectedContentLength = UInt64(data.count) + } else { + assert(self.filePathIsFeed) + + var processedBase64Signature: NSString? = nil + var processedExpectedContentLength: UInt64 = 0 + dataToVerify = SPUExtractAppcastContent(data, &processedBase64Signature, &processedExpectedContentLength) + + expectedContentLength = processedExpectedContentLength + + guard let processedBase64Signature else { + print("Error: failed to extract signature from appcast. Is the appcast signed?") + throw ExitCode.failure + } + + base64Signature = processedBase64Signature as String } - guard let signatureData = Data(base64Encoded: verifySignature, options: .ignoreUnknownCharacters) else { - print("Error: failed to decode base64 signature: \(verifySignature)") + guard let signatureData = Data(base64Encoded: base64Signature, options: .ignoreUnknownCharacters) else { + print("Error: failed to decode base64 signature: \(base64Signature)") throw ExitCode.failure } @@ -170,21 +222,72 @@ struct SignUpdate: ParsableCommand { throw ExitCode.failure } - let dataBytes = Array(data) + let dataBytesToVerify = Array(dataToVerify) let publicKeyBytes = Array(pub) - if ed25519_verify(signatureBytes, dataBytes, data.count, publicKeyBytes) == 0 { + if ed25519_verify(signatureBytes, dataBytesToVerify, dataBytesToVerify.count, publicKeyBytes) == 0 { print("Error: failed to pass signing verification.") + let dataBytesCount = UInt64(dataBytesToVerify.count) + if expectedContentLength != dataBytesCount { + print("\(expectedContentLength) bytes were expected to be signed, but actually read \(dataBytesCount) bytes.") + } throw ExitCode.failure } } else { // Sign the update - let sig = edSignature(data: data, publicEdKey: pub, privateEdKey: priv) - - if printOnlySignature { - print(sig) + if self.filePathIsFeed { + let contentData = SPUExtractAppcastContent(data, nil, nil) + + let dataToSign: Data = disableEmbeddedSignWarning ? contentData : addSignWarningToAppcast(data: contentData) + let addedSignWarningToAppcast = (contentData.count != dataToSign.count) + let signedData = try signAppcast(data: dataToSign, publicEdKey: pub, privateEdKey: priv) + try signedData.write(to: fileURL, options: .atomic) + + if !printOnlySignature { + if !addedSignWarningToAppcast { + print("") + } else { + print("") + } + } } else { - print("sparkle:edSignature=\"\(sig)\" length=\"\(data.count)\"") + let signedData: Data + let updatedSigningWarningInReleaseNotes: Bool + + if disableEmbeddedSignWarning || (!self.filePathIsHTMLReleaseNotes && !self.filePathIsMarkdownReleaseNotes) { + signedData = data + updatedSigningWarningInReleaseNotes = false + } else { + if let updatedDataForSigning = updateHTMLCommentSigningWarningInReleaseNotes(data: data) { + do { + try updatedDataForSigning.write(to: fileURL, options: .atomic) + signedData = updatedDataForSigning + updatedSigningWarningInReleaseNotes = true + } catch { + // Fallback to original data if the release notes is not updatable + signedData = data + updatedSigningWarningInReleaseNotes = false + } + } else { + signedData = data + updatedSigningWarningInReleaseNotes = false + } + } + + let sig = edSignature(data: signedData, publicEdKey: pub, privateEdKey: priv) + + if printOnlySignature { + print(sig) + } else { + if self.filePathIsReleaseNotes { + if updatedSigningWarningInReleaseNotes { + print("") + } + print("sparkle:edSignature=\"\(sig)\" sparkle:length=\"\(signedData.count)\"") + } else { + print("sparkle:edSignature=\"\(sig)\" length=\"\(signedData.count)\"") + } + } } } }