From 1526a024b841952eed1b39e45f4f3904ae718503 Mon Sep 17 00:00:00 2001 From: Zorg Date: Sun, 28 Feb 2021 21:05:13 -0800 Subject: [PATCH] Propagate installer errors to Sparkle --- Autoupdate/AppInstaller.h | 6 +- Autoupdate/AppInstaller.m | 106 ++++++++++++++++++----------------- Autoupdate/SPUMessageTypes.h | 3 +- Autoupdate/SPUMessageTypes.m | 3 +- Autoupdate/main.m | 2 +- Sparkle/SPUInstallerDriver.m | 36 ++++++++---- Sparkle/SUErrors.h | 2 +- Sparkle/SUUpdateValidator.h | 4 +- Sparkle/SUUpdateValidator.m | 69 ++++++++++++++++------- 9 files changed, 141 insertions(+), 90 deletions(-) diff --git a/Autoupdate/AppInstaller.h b/Autoupdate/AppInstaller.h index dde6c42a..3dc2f62e 100644 --- a/Autoupdate/AppInstaller.h +++ b/Autoupdate/AppInstaller.h @@ -9,12 +9,16 @@ #import #import "SUUnarchiverProtocol.h" +NS_ASSUME_NONNULL_BEGIN + @interface AppInstaller : NSObject - (instancetype)initWithHostBundleIdentifier:(NSString *)hostBundleIdentifier; - (void)start; -- (void)cleanupAndExitWithStatus:(int)status __attribute__((noreturn)); +- (void)cleanupAndExitWithStatus:(int)status error:(NSError * _Nullable)error; @end + +NS_ASSUME_NONNULL_END diff --git a/Autoupdate/AppInstaller.m b/Autoupdate/AppInstaller.m index 2b4f105d..f2f6ecef 100644 --- a/Autoupdate/AppInstaller.m +++ b/Autoupdate/AppInstaller.m @@ -147,8 +147,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; AppInstaller *strongSelf = weakSelf; if (strongSelf != nil) { if (strongSelf.activeConnection != nil && !strongSelf.willCompleteInstallation) { - SULog(SULogLevelError, @"Invalidation on remote port being called, and installation is not close enough to completion!"); - [strongSelf cleanupAndExitWithStatus:EXIT_FAILURE]; + [strongSelf cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Invalidation on remote port being called, and installation is not close enough to completion!" }]]; } strongSelf.communicator = nil; strongSelf.activeConnection = nil; @@ -170,13 +169,11 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(FIRST_UPDATER_MESSAGE_TIMEOUT * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ if (!self.receivedInstallationData) { - SULog(SULogLevelError, @"Timeout: installation data was never received"); - [self cleanupAndExitWithStatus:EXIT_FAILURE]; + [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Timeout: installation data was never received" }]]; } if (!self.agentConnection.connected) { - SULog(SULogLevelError, @"Timeout: agent connection was never initiated"); - [self cleanupAndExitWithStatus:EXIT_FAILURE]; + [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Timeout: agent connection was never initiated" }]]; } }); } @@ -188,9 +185,10 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; NSString *archivePath = [self.updateDirectoryPath stringByAppendingPathComponent:self.downloadName]; id unarchiver = [SUUnarchiver unarchiverForPath:archivePath updatingHostBundlePath:self.host.bundlePath decryptionPassword:self.decryptionPassword expectingInstallationType:self.installationType]; + NSError *unarchiverError = nil; BOOL success = NO; if (!unarchiver) { - SULog(SULogLevelError, @"Error: No valid unarchiver for %@", archivePath); + unarchiverError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"No valid unarchiver was found for %@", archivePath] }]; success = NO; } else { @@ -201,28 +199,27 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; BOOL needsPrevalidation = [[unarchiver class] mustValidateBeforeExtraction] || ![self.installationType isEqualToString:SPUInstallationTypeApplication]; if (needsPrevalidation) { - success = [self.updateValidator validateDownloadPath]; + success = [self.updateValidator validateDownloadPathWithError:&unarchiverError]; } else { success = YES; } } if (!success) { - [self unarchiverDidFail]; + [self unarchiverDidFailWithError:unarchiverError]; } else { [unarchiver unarchiveWithCompletionBlock:^(NSError * _Nullable error) { if (error != nil) { - SULog(SULogLevelError, @"Failed to unarchive %@ with error: %@", archivePath, error); - [self unarchiverDidFail]; + [self unarchiverDidFailWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to unarchive %@", archivePath], NSUnderlyingErrorKey: (NSError * _Nonnull)error }]]; } else { [self.communicator handleMessageWithIdentifier:SPUValidationStarted data:[NSData data]]; - BOOL validationSuccess = [self.updateValidator validateWithUpdateDirectory:self.updateDirectoryPath]; + NSError *validationError = nil; + BOOL validationSuccess = [self.updateValidator validateWithUpdateDirectory:self.updateDirectoryPath error:&validationError]; if (!validationSuccess) { - SULog(SULogLevelError, @"Error: update validation was a failure"); - [self cleanupAndExitWithStatus:EXIT_FAILURE]; + [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Update validation was a failure", NSUnderlyingErrorKey: validationError }]]; } else { [self.communicator handleMessageWithIdentifier:SPUInstallationStartedStage1 data:[NSData data]]; @@ -244,8 +241,15 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; } } -- (void)unarchiverDidFail +- (void)unarchiverDidFailWithError:(NSError *)error { + SULog(SULogLevelError, @"Failed to unarchive file: %@", error); + + NSError *underlyingError = error.userInfo[NSUnderlyingErrorKey]; + if (underlyingError != nil) { + SULog(SULogLevelError, @"Error: %@", underlyingError); + } + // No longer need update validator until next possible extraction (eg: if initial delta update fails) self.updateValidator = nil; @@ -260,7 +264,8 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; self.relaunchPath = nil; self.host = nil; - [self.communicator handleMessageWithIdentifier:SPUArchiveExtractionFailed data:[NSData data]]; + NSData *archivedError = SPUArchiveRootObjectSecurely(error); + [self.communicator handleMessageWithIdentifier:SPUArchiveExtractionFailed data:archivedError != nil ? archivedError : [NSData data]]; } - (void)agentConnectionDidInitiate @@ -274,8 +279,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; - (void)agentConnectionDidInvalidate { if (!self.finishedValidation || !self.agentInitiatedConnection) { - SULog(SULogLevelError, @"Error: Agent connection invalidated before installation began"); - [self cleanupAndExitWithStatus:EXIT_FAILURE]; + [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Error: Agent connection invalidated before installation began" }]]; } } @@ -294,8 +298,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(RETRIEVE_PROCESS_IDENTIFIER_TIMEOUT * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ if (self.terminationListener == nil) { - SULog(SULogLevelError, @"Timeout error: failed to retreive process identifier from agent"); - [self cleanupAndExitWithStatus:EXIT_FAILURE]; + [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Timeout error: failed to retreive process identifier from agent" }]]; } }); } @@ -310,15 +313,13 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; SPUInstallationInputData *installationData = (SPUInstallationInputData *)SPUUnarchiveRootObjectSecurely(data, [SPUInstallationInputData class]); if (installationData == nil) { - SULog(SULogLevelError, @"Error: Failed to unarchive input installation data"); - [self cleanupAndExitWithStatus:EXIT_FAILURE]; + [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Error: Failed to unarchive input installation data" }]]; return; } NSString *installationType = installationData.installationType; if (!SPUValidInstallationType(installationType)) { - SULog(SULogLevelError, @"Error: Received invalid installation type: %@", installationType); - [self cleanupAndExitWithStatus:EXIT_FAILURE]; + [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Error: Received invalid installation type: %@", installationType] }]]; return; } @@ -326,15 +327,13 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; NSString *bundleIdentifier = hostBundle.bundleIdentifier; if (bundleIdentifier == nil || ![bundleIdentifier isEqualToString:self.hostBundleIdentifier]) { - SULog(SULogLevelError, @"Error: Failed to match host bundle identifiers %@ and %@", self.hostBundleIdentifier, bundleIdentifier); - [self cleanupAndExitWithStatus:EXIT_FAILURE]; + [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Error: Failed to match host bundle identifiers %@ and %@", self.hostBundleIdentifier, bundleIdentifier] }]]; return; } // This will be important later if (installationData.relaunchPath == nil) { - SULog(SULogLevelError, @"Error: Failed to obtain relaunch path from installation data"); - [self cleanupAndExitWithStatus:EXIT_FAILURE]; + [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Error: Failed to obtain relaunch path from installation data" }]]; return; } @@ -345,8 +344,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; NSString *cacheInstallationPath = [SPULocalCacheDirectory createUniqueDirectoryInDirectory:rootCacheInstallationPath]; if (cacheInstallationPath == nil) { - SULog(SULogLevelError, @"Error: Failed to create installation cache directory in %@", rootCacheInstallationPath); - [self cleanupAndExitWithStatus:EXIT_FAILURE]; + [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Error: Failed to create installation cache directory in %@", rootCacheInstallationPath] }]]; return; } @@ -359,8 +357,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; NSError *moveError = nil; if (![[[SUFileManager alloc] init] moveItemAtURL:downloadURL toURL:downloadDestinationURL error:&moveError]) { - SULog(SULogLevelError, @"Error: Failed to move download archive to new location: %@", moveError); - [self cleanupAndExitWithStatus:EXIT_FAILURE]; + [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Error: Failed to move download archive to new location", NSUnderlyingErrorKey: moveError }]]; return; } @@ -368,22 +365,21 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; NSError *attributesError = nil; NSString *downloadDestinationPath = downloadDestinationURL.path; if (downloadDestinationPath == nil) { - SULog(SULogLevelError, @"Error: Failed to retrieve download archive path from %@", downloadDestinationURL); - [self cleanupAndExitWithStatus:EXIT_FAILURE]; + [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Error: Failed to retrieve download archive path from %@", downloadDestinationURL] }]]; + return; } NSDictionary *archiveAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:downloadDestinationPath error:&attributesError]; if (archiveAttributes == nil) { - SULog(SULogLevelError, @"Error: Failed to retrieve download archive attributes from %@", downloadDestinationPath); - [self cleanupAndExitWithStatus:EXIT_FAILURE]; + [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Error: Failed to retrieve download archive attributes from %@", downloadDestinationPath] }]]; + return; } if (![(NSString *)archiveAttributes[NSFileType] isEqualToString:NSFileTypeRegular]) { - SULog(SULogLevelError, @"Error: Received bad archive file type: %@", archiveAttributes[NSFileType]); - [self cleanupAndExitWithStatus:EXIT_FAILURE]; + [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Error: Received bad archive file type: %@", archiveAttributes[NSFileType]] }]]; return; } @@ -442,20 +438,18 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; id installer = [SUInstaller installerForHost:self.host expectedInstallationType:self.installationType updateDirectory:self.updateDirectoryPath error:&installerError]; if (installer == nil) { - SULog(SULogLevelError, @"Error: Failed to create installer instance with error: %@", installerError); dispatch_async(dispatch_get_main_queue(), ^{ - [self cleanupAndExitWithStatus:EXIT_FAILURE]; + [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Error: Failed to create installer instance", NSUnderlyingErrorKey: installerError }]]; }); return; } NSError *firstStageError = nil; if (![installer performInitialInstallation:&firstStageError]) { - SULog(SULogLevelError, @"Error: Failed to start installer with error: %@", firstStageError); self.installer = nil; dispatch_async(dispatch_get_main_queue(), ^{ - [self cleanupAndExitWithStatus:EXIT_FAILURE]; + [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Error: Failed to start installer", NSUnderlyingErrorKey: firstStageError }]]; }); return; } @@ -503,11 +497,10 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; [self.agentConnection.agent sendTerminationSignal]; }); } else { - SULog(SULogLevelError, @"Error: Failed to resume installer on stage 2 because installation cannot be installed silently"); self.installer = nil; dispatch_async(dispatch_get_main_queue(), ^{ - [self cleanupAndExitWithStatus:EXIT_FAILURE]; + [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Error: Failed to resume installer on stage 2 because installation cannot be installed silently" }]]; }); } } @@ -516,8 +509,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; { [self.terminationListener startListeningWithCompletion:^(BOOL success) { if (!success) { - SULog(SULogLevelError, @"Failed to listen for application termination"); - [self cleanupAndExitWithStatus:EXIT_FAILURE]; + [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to listen for application termination" }]]; return; } @@ -556,12 +548,10 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; NSError *thirdStageError = nil; if (![self.installer performFinalInstallationProgressBlock:nil error:&thirdStageError]) { - SULog(SULogLevelError, @"Failed to finalize installation with error: %@", thirdStageError); - self.installer = nil; dispatch_async(dispatch_get_main_queue(), ^{ - [self cleanupAndExitWithStatus:EXIT_FAILURE]; + [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to finalize installation", NSUnderlyingErrorKey: thirdStageError }]]; }); return; } @@ -591,14 +581,28 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; [self.agentConnection.agent relaunchPath:pathToRelaunch]; } - [self cleanupAndExitWithStatus:EXIT_SUCCESS]; + [self cleanupAndExitWithStatus:EXIT_SUCCESS error:nil]; }); }); }]; } -- (void)cleanupAndExitWithStatus:(int)status __attribute__((noreturn)) +- (void)cleanupAndExitWithStatus:(int)status error:(NSError * _Nullable)error __attribute__((noreturn)) { + if (error != nil) { + SULog(SULogLevelError, @"Error: %@", error); + + NSError *underlyingError = error.userInfo[NSUnderlyingErrorKey]; + if (underlyingError != nil) { + SULog(SULogLevelError, @"Error: %@", underlyingError); + } + + NSData *errorData = SPUArchiveRootObjectSecurely((NSError * _Nonnull)error); + if (errorData != nil) { + [self.communicator handleMessageWithIdentifier:SPUInstallerError data:errorData]; + } + } + // It's nice to tell the other end we're invalidating [self.activeConnection invalidate]; diff --git a/Autoupdate/SPUMessageTypes.h b/Autoupdate/SPUMessageTypes.h index 05f264c6..8b69a006 100644 --- a/Autoupdate/SPUMessageTypes.h +++ b/Autoupdate/SPUMessageTypes.h @@ -26,7 +26,8 @@ typedef NS_ENUM(int32_t, SPUInstallerMessageType) SPUInstallationFinishedStage1 = 6, SPUInstallationFinishedStage2 = 7, SPUInstallationFinishedStage3 = 8, - SPUUpdaterAlivePing = 9 + SPUUpdaterAlivePing = 9, + SPUInstallerError = 10 }; typedef NS_ENUM(int32_t, SPUUpdaterMessageType) diff --git a/Autoupdate/SPUMessageTypes.m b/Autoupdate/SPUMessageTypes.m index 7df9db0c..4ea84ac3 100644 --- a/Autoupdate/SPUMessageTypes.m +++ b/Autoupdate/SPUMessageTypes.m @@ -55,9 +55,10 @@ BOOL SPUInstallerMessageTypeIsLegal(SPUInstallerMessageType oldMessageType, SPUI case SPUInstallationFinishedStage3: legal = (oldMessageType == SPUInstallationFinishedStage2); break; + case SPUInstallerError: case SPUUpdaterAlivePing: // Having this state being dependent on other installation states would make the complicate our logic - // So just always allow this type of message + // So just always allow these type of messages legal = YES; break; } diff --git a/Autoupdate/main.m b/Autoupdate/main.m index 6bed9fe5..1e4f3d06 100644 --- a/Autoupdate/main.m +++ b/Autoupdate/main.m @@ -23,7 +23,7 @@ int main(int __unused argc, const char __unused *argv[]) dispatch_source_t sigtermSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGTERM, 0, dispatch_get_main_queue()); dispatch_source_set_event_handler(sigtermSource, ^{ - [appInstaller cleanupAndExitWithStatus:SIGTERM]; + [appInstaller cleanupAndExitWithStatus:SIGTERM error:nil]; }); dispatch_resume(sigtermSource); diff --git a/Sparkle/SPUInstallerDriver.m b/Sparkle/SPUInstallerDriver.m index b0cef277..60dd99e7 100644 --- a/Sparkle/SPUInstallerDriver.m +++ b/Sparkle/SPUInstallerDriver.m @@ -59,6 +59,7 @@ @property (nonatomic, copy) NSString *temporaryDirectory; @property (nonatomic) BOOL aborted; +@property (nonatomic, nullable) NSError *installerError; @end @@ -80,6 +81,7 @@ @synthesize downloadName = _downloadName; @synthesize temporaryDirectory = _temporaryDirectory; @synthesize aborted = _aborted; +@synthesize installerError = _installerError; - (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle sparkleBundle:(NSBundle *)sparkleBundle updater:(id)updater updaterDelegate:(id)updaterDelegate delegate:(nullable id)delegate { @@ -115,16 +117,18 @@ dispatch_async(dispatch_get_main_queue(), ^{ SPUInstallerDriver *strongSelf = weakSelf; if (strongSelf.installerConnection != nil && !strongSelf.aborted) { - NSError *remoteError = - [NSError - errorWithDomain:SUSparkleErrorDomain - code:SUInstallationError - userInfo:@{ - NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while running the updater. Please try again later.", nil), - NSLocalizedFailureReasonErrorKey:@"The remote port connection was invalidated from the updater. Please check Console logs for "@SPARKLE_RELAUNCH_TOOL_NAME - } - ]; - [strongSelf.delegate installerIsRequestingAbortInstallWithError:remoteError]; + + NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ + NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while running the updater. Please try again later.", nil), + NSLocalizedFailureReasonErrorKey:@"The remote port connection was invalidated from the updater. For additional details, please check Console logs for "@SPARKLE_RELAUNCH_TOOL_NAME + }]; + + NSError *installerError = strongSelf.installerError; + if (installerError != nil) { + userInfo[NSUnderlyingErrorKey] = installerError; + } + + [strongSelf.delegate installerIsRequestingAbortInstallWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:userInfo]]; } }); }]; @@ -234,7 +238,14 @@ [self.delegate installerDidFailToApplyDeltaUpdate]; } else { // Don't have to store current stage because we're going to abort - [self.delegate installerIsRequestingAbortInstallWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil) }]]; + NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ NSLocalizedDescriptionKey:SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil) }]; + + NSError *unarchivedError = (NSError *)SPUUnarchiveRootObjectSecurely(data, [NSError class]); + if (unarchivedError != nil) { + userInfo[NSUnderlyingErrorKey] = unarchivedError; + } + + [self.delegate installerIsRequestingAbortInstallWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:userInfo]]; } } else if (identifier == SPUValidationStarted) { self.currentStage = identifier; @@ -300,6 +311,9 @@ } else if (identifier == SPUUpdaterAlivePing) { // Don't update the current stage; a ping request has no effect on that. [self.installerConnection handleMessageWithIdentifier:SPUUpdaterAlivePong data:[NSData data]]; + } else if (identifier == SPUInstallerError) { + // Don't update the current stage; an installation error has no effect on that. + self.installerError = (NSError *)SPUUnarchiveRootObjectSecurely(data, [NSError class]); } } diff --git a/Sparkle/SUErrors.h b/Sparkle/SUErrors.h index 5f0bc8b1..da9580e7 100644 --- a/Sparkle/SUErrors.h +++ b/Sparkle/SUErrors.h @@ -49,7 +49,7 @@ typedef NS_ENUM(OSStatus, SUError) { // Extraction phase errors. SUUnarchivingError = 3000, - SUSignatureError = 3001, + SUValidationError = 3001, // Installation phase errors. SUFileCopyFailure = 4000, diff --git a/Sparkle/SUUpdateValidator.h b/Sparkle/SUUpdateValidator.h index 2281aa52..c1b93951 100644 --- a/Sparkle/SUUpdateValidator.h +++ b/Sparkle/SUUpdateValidator.h @@ -18,10 +18,10 @@ NS_ASSUME_NONNULL_BEGIN - (instancetype)initWithDownloadPath:(NSString *)downloadPath signatures:(SUSignatures *)signatures host:(SUHost *)host; // This is "pre" validation, before the archive has been extracted - - (BOOL)validateDownloadPath; +- (BOOL)validateDownloadPathWithError:(NSError **)error; // This is "post" validation, after an archive has been extracted -- (BOOL)validateWithUpdateDirectory:(NSString *)updateDirectory; +- (BOOL)validateWithUpdateDirectory:(NSString *)updateDirectory error:(NSError **)error; @end diff --git a/Sparkle/SUUpdateValidator.m b/Sparkle/SUUpdateValidator.m index 5b0d1ead..b8aab518 100644 --- a/Sparkle/SUUpdateValidator.m +++ b/Sparkle/SUUpdateValidator.m @@ -13,6 +13,8 @@ #import "SUHost.h" #import "SULog.h" #import "SUSignatures.h" +#import "SUErrors.h" + #include "AppKitPrevention.h" @@ -43,23 +45,28 @@ return self; } -- (BOOL)validateDownloadPath { +- (BOOL)validateDownloadPathWithError:(NSError * __autoreleasing *)error +{ SUPublicKeys *publicKeys = self.host.publicKeys; SUSignatures *signatures = self.signatures; if (!publicKeys.hasAnyKeys) { - SULog(SULogLevelError, @"Failed to validate update before unarchiving because no (Ed)DSA public key was found in the old app"); + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to validate update before unarchiving because no (Ed)DSA public key was found in the old app" }]; + } } else { if ([SUSignatureVerifier validatePath:self.downloadPath withSignatures:signatures withPublicKeys:publicKeys]) { self.prevalidatedSignature = YES; return YES; } - SULog(SULogLevelError, @"(Ed)DSA signature validation before unarchiving failed for update %@", self.downloadPath); + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"(Ed)DSA signature validation before unarchiving failed for update %@", self.downloadPath] }]; + } } return NO; } -- (BOOL)validateWithUpdateDirectory:(NSString *)updateDirectory +- (BOOL)validateWithUpdateDirectory:(NSString *)updateDirectory error:(NSError * __autoreleasing *)error { SUSignatures *signatures = self.signatures; SUPublicKeys *publicKeys = self.host.publicKeys; @@ -71,7 +78,9 @@ // install source could point to a new bundle or a package NSString *installSource = [SUInstaller installSourcePathInUpdateFolder:updateDirectory forHost:host isPackage:&isPackage isGuided:NULL]; if (installSource == nil) { - SULog(SULogLevelError, @"No suitable install is found in the update. The update will be rejected."); + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"No suitable install is found in the update. The update will be rejected." }]; + } return NO; } @@ -84,12 +93,14 @@ // For package type updates, all we do is check if the DSA signature is valid BOOL validationCheckSuccess = [SUSignatureVerifier validatePath:downloadPath withSignatures:signatures withPublicKeys:publicKeys]; if (!validationCheckSuccess) { - SULog(SULogLevelError, @"DSA signature validation of the package failed. The update contains an installer package, and valid DSA signatures are mandatory for all installer packages. The update will be rejected. Sign the installer with a valid DSA key or use an .app bundle update instead."); + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"DSA signature validation of the package failed. The update contains an installer package, and valid DSA signatures are mandatory for all installer packages. The update will be rejected. Sign the installer with a valid DSA key or use an .app bundle update instead." }]; + } } return validationCheckSuccess; } else { // For application bundle updates, we check both the DSA and Apple code signing signatures - return [self validateUpdateForHost:host downloadedToPath:downloadPath newBundleURL:installSourceURL signatures:signatures]; + return [self validateUpdateForHost:host downloadedToPath:downloadPath newBundleURL:installSourceURL signatures:signatures error:error]; } } else if (isPackage) { // We already prevalidated the package and nothing else needs to be done @@ -98,9 +109,12 @@ // Because we already validated the DSA signature, this is just a consistency check to see // if the developer signed their application properly with their Apple ID // Currently, this case only gets hit for binary delta updates - NSError *error = nil; - if ([SUCodeSigningVerifier bundleAtURLIsCodeSigned:installSourceURL] && ![SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:installSourceURL error:&error]) { - SULog(SULogLevelError, @"Failed to validate apple code sign signature on bundle after archive validation with error: %@", error); + NSError *innerError = nil; + if ([SUCodeSigningVerifier bundleAtURLIsCodeSigned:installSourceURL] && ![SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:installSourceURL error:&innerError]) { + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to validate apple code sign signature on bundle after archive validation", NSUnderlyingErrorKey: innerError }]; + } + return NO; } else { return YES; @@ -116,11 +130,13 @@ * * old and new Code Signing identity are the same and valid * */ -- (BOOL)validateUpdateForHost:(SUHost *)host downloadedToPath:(NSString *)downloadedPath newBundleURL:(NSURL *)newBundleURL signatures:(SUSignatures *)signatures +- (BOOL)validateUpdateForHost:(SUHost *)host downloadedToPath:(NSString *)downloadedPath newBundleURL:(NSURL *)newBundleURL signatures:(SUSignatures *)signatures error:(NSError * __autoreleasing *)error { NSBundle *newBundle = [NSBundle bundleWithURL:newBundleURL]; if (newBundle == nil) { - SULog(SULogLevelError, @"No suitable bundle is found in the update. The update will be rejected."); + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"No suitable bundle is found in the update. The update will be rejected." }]; + } return NO; } @@ -140,7 +156,9 @@ // This is not essential for security, only a policy if (oldHasAnyDSAKey && !newHasAnyDSAKey) { - SULog(SULogLevelError, @"A public (Ed)DSA key was found in the old bundle but no public (Ed)DSA key was found in the new update. Sparkle only supports rotation, but not removal of (Ed)DSA keys. Please add an EdDSA key to the new app."); + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"A public (Ed)DSA key was found in the old bundle but no public (Ed)DSA key was found in the new update. Sparkle only supports rotation, but not removal of (Ed)DSA keys. Please add an EdDSA key to the new app." }]; + } return NO; } @@ -154,8 +172,8 @@ } if (hostIsCodeSigned) { - NSError *error = nil; - passedCodeSigning = [SUCodeSigningVerifier codeSignatureAtBundleURL:host.bundle.bundleURL matchesSignatureAtBundleURL:newHost.bundle.bundleURL error:&error]; + NSError *innerError = nil; + passedCodeSigning = [SUCodeSigningVerifier codeSignatureAtBundleURL:host.bundle.bundleURL matchesSignatureAtBundleURL:newHost.bundle.bundleURL error:&innerError]; } // End of security-critical part @@ -163,14 +181,18 @@ // In that case, the check ensures that the app author has correctly used DSA keys, so that the app will be updateable in the next version. if (!passedDSACheck && newHasAnyDSAKey) { if (![SUSignatureVerifier validatePath:downloadedPath withSignatures:signatures withPublicKeys:newPublicKeys]) { - SULog(SULogLevelError, @"The update has a public (Ed)DSA key, but the public key shipped with the update doesn't match the signature. To prevent future problems, the update will be rejected."); + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"The update has a public (Ed)DSA key, but the public key shipped with the update doesn't match the signature. To prevent future problems, the update will be rejected." }]; + } return NO; } } - NSError *error = nil; - if (passedDSACheck && updateIsCodeSigned && ![SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:newHost.bundle.bundleURL error:&error]) { - SULog(SULogLevelError, @"The update archive has a valid (Ed)DSA signature, but the app is also signed with Code Signing, which is corrupted: %@. The update will be rejected.", error); + NSError *innerError = nil; + if (passedDSACheck && updateIsCodeSigned && ![SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:newHost.bundle.bundleURL error:&innerError]) { + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"The update archive has a valid (Ed)DSA signature, but the app is also signed with Code Signing, which is corrupted. The update will be rejected.", NSUnderlyingErrorKey: innerError }]; + } return NO; } @@ -195,9 +217,14 @@ if (!hostIsCodeSigned || !updateIsCodeSigned) { NSString *acsStatus = !hostIsCodeSigned ? @"old app hasn't been signed with app Code Signing" : @"new app isn't signed with app Code Signing"; - SULog(SULogLevelError, @"The update archive %@, and the %@. At least one method of signature verification must be valid. The update will be rejected.", dsaStatus, acsStatus); + + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"The update archive %@, and the %@. At least one method of signature verification must be valid. The update will be rejected.", dsaStatus, acsStatus] }]; + } } else { - SULog(SULogLevelError, @"The update archive %@, and the app is signed with a new Code Signing identity that doesn't match code signing of the original app: %@. At least one method of signature verification must be valid. The update will be rejected.", dsaStatus, error); + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"The update archive %@, and the app is signed with a new Code Signing identity that doesn't match code signing of the original app. At least one method of signature verification must be valid. The update will be rejected.", dsaStatus], NSUnderlyingErrorKey: innerError }]; + } } return NO;