diff --git a/Autoupdate/AgentConnection.m b/Autoupdate/AgentConnection.m index 92a56251..5561101f 100644 --- a/Autoupdate/AgentConnection.m +++ b/Autoupdate/AgentConnection.m @@ -10,6 +10,8 @@ #import "SPUMessageTypes.h" #import "SPUInstallerAgentProtocol.h" #import "SUInstallerAgentInitiationProtocol.h" +#import "SUCodeSigningVerifier.h" +#import "SULog.h" #include "AppKitPrevention.h" @@ -52,7 +54,7 @@ _delegate = nil; [_activeConnection invalidate]; - _activeConnection = nil; + // Don't need to set _activeConnection to nil, we don't expect new connections [_xpcListener invalidate]; _xpcListener = nil; @@ -61,10 +63,29 @@ - (BOOL)listener:(NSXPCListener *)__unused listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection { if (_activeConnection != nil) { + SULog(SULogLevelError, @"Error: Rejecting new connection for agent due already having an active connection"); + [newConnection invalidate]; return NO; } + // Hardening but not critical for security + NSError *validationError = nil; + SUValidateConnectionStatus validationStatus = [SUCodeSigningVerifier validateConnection:newConnection options:SUValidateConnectionOptionDefault error:&validationError]; + switch (validationStatus) { + case SUValidateConnectionStatusSetCodeSigningRequirementSuccess: + break; + case SUValidateConnectionStatusSetNoRequirementSuccess: + break; + case SUValidateConnectionStatusAPIFailure: + case SUValidateConnectionStatusCodeSigningRequirementFailure: + case SUValidateConectionNoSupportedValidationMethodFailure: + SULog(SULogLevelError, @"Error: Rejecting new connection for agent due to failing validation of XPC connection with status %lu and error: %@", validationStatus, validationError.localizedDescription); + + [newConnection invalidate]; + return NO; + } + newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerAgentInitiationProtocol)]; newConnection.exportedObject = self; @@ -91,9 +112,8 @@ }); }; - [newConnection resume]; - _agent = newConnection.remoteObjectProxy; + [newConnection resume]; return YES; } @@ -106,7 +126,9 @@ [self->_delegate agentConnectionDidInitiate]; }); - acknowledgement(); + if (acknowledgement != NULL) { + acknowledgement(); + } } - (void)connectionWillInvalidateWithError:(NSError *)error diff --git a/Autoupdate/AppInstaller.m b/Autoupdate/AppInstaller.m index 95a2296d..72467696 100644 --- a/Autoupdate/AppInstaller.m +++ b/Autoupdate/AppInstaller.m @@ -29,6 +29,8 @@ #import "SPULocalCacheDirectory.h" #import "SPUVerifierInformation.h" #import "SUConstants.h" +#import "SUCodeSigningVerifier.h" +#import #include "AppKitPrevention.h" @@ -49,7 +51,10 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; @implementation AppInstaller { NSXPCListener* _xpcListener; + // Must be synchronized with _newConnectionLock + // Set from new connection handler, and also set/read from main thread NSXPCConnection *_activeConnection; + id _communicator; AgentConnection *_agentConnection; @@ -72,6 +77,14 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; dispatch_queue_t _installerQueue; + os_unfair_lock _newConnectionLock; + +#if SPARKLE_BUILD_PACKAGE_SUPPORT + // Must be synchronized with _newConnectionLock + // Set from new connection handler, read from main thread + BOOL _connectionCodeSigningValidationSkipped; +#endif + BOOL _shouldRelaunch; BOOL _shouldShowUI; @@ -82,7 +95,9 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; BOOL _finishedValidation; BOOL _agentInitiatedConnection; + // Setting _performedStage1Installation on main thread must be synchronzied with reading it from new connection handler BOOL _performedStage1Installation; + BOOL _performedStage2Installation; BOOL _performedStage3Installation; @@ -95,6 +110,8 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; return nil; } + _newConnectionLock = OS_UNFAIR_LOCK_INIT; + _hostBundleIdentifier = [hostBundleIdentifier copy]; _homeDirectory = [homeDirectory copy]; @@ -110,13 +127,59 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; - (BOOL)listener:(NSXPCListener *)__unused listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection { - if (_activeConnection != nil) { - SULog(SULogLevelDefault, @"Rejecting multiple connections..."); - [newConnection invalidate]; - return NO; + os_unfair_lock_lock(&_newConnectionLock); + { + if (_activeConnection != nil) { + os_unfair_lock_unlock(&_newConnectionLock); + + SULog(SULogLevelError, @"Error: Rejecting multiple XPC connections for installer..."); + + [newConnection invalidate]; + return NO; + } + + #if SPARKLE_BUILD_PACKAGE_SUPPORT + BOOL connectionCodeSigningValidationSkipped = NO; + #endif + + // It's safe to allow any connections once stage 1 installation is complete + // This is to allow general updaters to resume the installation. + if (!_performedStage1Installation) { + BOOL passesValidation; + NSError *validationError = nil; + SUValidateConnectionStatus status = [SUCodeSigningVerifier validateConnection:newConnection options:SUValidateConnectionOptionDefault error:&validationError]; + switch (status) { + case SUValidateConnectionStatusSetCodeSigningRequirementSuccess: + passesValidation = YES; + break; + case SUValidateConnectionStatusSetNoRequirementSuccess: + passesValidation = YES; +#if SPARKLE_BUILD_PACKAGE_SUPPORT + connectionCodeSigningValidationSkipped = YES; +#endif + break; + case SUValidateConnectionStatusAPIFailure: + case SUValidateConnectionStatusCodeSigningRequirementFailure: + case SUValidateConectionNoSupportedValidationMethodFailure: + passesValidation = NO; + break; + } + + if (!passesValidation) { + os_unfair_lock_unlock(&_newConnectionLock); + + SULog(SULogLevelError, @"Error: Rejecting new connection for installer due to failing validation of XPC connection with status %lu and error: %@", status, validationError.localizedDescription); + [newConnection invalidate]; + return NO; + } + } + +#if SPARKLE_BUILD_PACKAGE_SUPPORT + _connectionCodeSigningValidationSkipped = connectionCodeSigningValidationSkipped; +#endif + _activeConnection = newConnection; } - - _activeConnection = newConnection; + os_unfair_lock_unlock(&_newConnectionLock); newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerCommunicationProtocol)]; newConnection.exportedObject = self; @@ -128,7 +191,11 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; dispatch_async(dispatch_get_main_queue(), ^{ __typeof__(self) strongSelf = weakSelf; if (strongSelf != nil) { - [strongSelf->_activeConnection invalidate]; + os_unfair_lock_lock(&strongSelf->_newConnectionLock); + NSXPCConnection *activeConnection = strongSelf->_activeConnection; + os_unfair_lock_unlock(&strongSelf->_newConnectionLock); + + [activeConnection invalidate]; } }); }; @@ -141,14 +208,19 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; [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; + + os_unfair_lock_lock(&strongSelf->_newConnectionLock); strongSelf->_activeConnection = nil; + os_unfair_lock_unlock(&strongSelf->_newConnectionLock); } }); }; - [newConnection resume]; - - _communicator = newConnection.remoteObjectProxy; + // _communicator is used only on main thread + dispatch_async(dispatch_get_main_queue(), ^{ + self->_communicator = newConnection.remoteObjectProxy; + [newConnection resume]; + }); return YES; } @@ -360,7 +432,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; // Do not rely on eg: self->_updateDirectoryPath != nil because we may set it to nil again if an early stage fails (i.e, archive extraction) self->_receivedInstallationData = YES; - SPUInstallationInputData *installationData = (SPUInstallationInputData *)SPUUnarchiveRootObjectSecurely(data, [SPUInstallationInputData class]); + SPUInstallationInputData *installationData = (data != nil) ? (SPUInstallationInputData *)SPUUnarchiveRootObjectSecurely(data, [SPUInstallationInputData class]) : nil; if (installationData == nil) { [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Error: Failed to unarchive input installation data" }]]; return; @@ -525,7 +597,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; [self extractAndInstallUpdate]; }); } else if (identifier == SPUSentUpdateAppcastItemData) { - SUAppcastItem *updateItem = (SUAppcastItem *)SPUUnarchiveRootObjectSecurely(data, [SUAppcastItem class]); + SUAppcastItem *updateItem = (data != nil) ? (SUAppcastItem *)SPUUnarchiveRootObjectSecurely(data, [SUAppcastItem class]) : nil; if (updateItem != nil) { SPUInstallationInfo *installationInfo = [[SPUInstallationInfo alloc] initWithAppcastItem:updateItem canSilentlyInstall:[_installer canInstallSilently]]; @@ -578,9 +650,17 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; _installerQueue = dispatch_queue_create("org.sparkle-project.sparkle.installer", queuePriority); +#if SPARKLE_BUILD_PACKAGE_SUPPORT + os_unfair_lock_lock(&_newConnectionLock); + BOOL connectionCodeSigningValidationSkipped = self->_connectionCodeSigningValidationSkipped; + os_unfair_lock_unlock(&_newConnectionLock); +#else + BOOL connectionCodeSigningValidationSkipped = NO; +#endif + dispatch_async(_installerQueue, ^{ NSError *installerError = nil; - id installer = [SUInstaller installerForHost:self->_host expectedInstallationType:self->_installationType updateDirectory:self->_extractionDirectory homeDirectory:self->_homeDirectory userName:self->_userName error:&installerError]; + id installer = [SUInstaller installerForHost:self->_host expectedInstallationType:self->_installationType updateDirectory:self->_extractionDirectory connectionCodeSigningValidationSkipped:connectionCodeSigningValidationSkipped homeDirectory:self->_homeDirectory userName:self->_userName error:&installerError]; if (installer == nil) { dispatch_async(dispatch_get_main_queue(), ^{ @@ -604,14 +684,16 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; dispatch_async(dispatch_get_main_queue(), ^{ self->_installer = installer; + os_unfair_lock_lock(&self->_newConnectionLock); + self->_performedStage1Installation = YES; + os_unfair_lock_unlock(&self->_newConnectionLock); + uint8_t sendInformation[] = {canPerformSilentInstall, (uint8_t)self->_targetTerminated}; NSData *sendData = [NSData dataWithBytes:sendInformation length:sizeof(sendInformation)]; [self->_communicator handleMessageWithIdentifier:SPUInstallationFinishedStage1 data:sendData]; - self->_performedStage1Installation = YES; - if (self->_targetTerminated) { // Stage 2 can still be run before we finish installation // if the updater requests for it before the app is terminated @@ -728,9 +810,15 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; // It's nice to tell the other end we're invalidating - [_activeConnection invalidate]; + os_unfair_lock_lock(&_newConnectionLock); + + NSXPCConnection *activeConnection = _activeConnection; _activeConnection = nil; + os_unfair_lock_unlock(&_newConnectionLock); + + [activeConnection invalidate]; + [_xpcListener invalidate]; _xpcListener = nil; diff --git a/Autoupdate/SUCodeSigningVerifier.h b/Autoupdate/SUCodeSigningVerifier.h index 7605c202..26b9805e 100644 --- a/Autoupdate/SUCodeSigningVerifier.h +++ b/Autoupdate/SUCodeSigningVerifier.h @@ -19,6 +19,22 @@ NS_ASSUME_NONNULL_BEGIN #define SUCodeSigningVerifierDefinitionAttribute __attribute__((objc_runtime_name("SUTestCodeSigningVerifier"))) #endif +typedef NS_ENUM(NSUInteger, SUValidateConnectionStatus) { + SUValidateConnectionStatusSetCodeSigningRequirementSuccess = 0, + SUValidateConnectionStatusSetNoRequirementSuccess, + SUValidateConnectionStatusAPIFailure, + SUValidateConnectionStatusCodeSigningRequirementFailure, + SUValidateConectionNoSupportedValidationMethodFailure, +}; + +typedef NS_OPTIONS(NSUInteger, SUValidateConnectionOptions) { + // Default validation behavior (matches against Team ID from main executable if available) + SUValidateConnectionOptionDefault = 0, + + // Require that the connecting client has the app sandbox entitlement + SUValidateConnectionOptionRequireSandboxEntitlement = 1 << 0, +}; + SUCodeSigningVerifierDefinitionAttribute @interface SUCodeSigningVerifier : NSObject @@ -34,6 +50,9 @@ SUCodeSigningVerifierDefinitionAttribute + (BOOL)bundleAtURLIsCodeSigned:(NSURL *)bundleURL; + (NSString * _Nullable)teamIdentifierAtURL:(NSURL *)url; ++ (NSString * _Nullable)teamIdentifierFromMainExecutable; + ++ (SUValidateConnectionStatus)validateConnection:(NSXPCConnection *)connection options:(SUValidateConnectionOptions)options error:(NSError * __autoreleasing *)error; @end diff --git a/Autoupdate/SUCodeSigningVerifier.m b/Autoupdate/SUCodeSigningVerifier.m index b88c8e2f..ffe6c2b3 100644 --- a/Autoupdate/SUCodeSigningVerifier.m +++ b/Autoupdate/SUCodeSigningVerifier.m @@ -15,6 +15,12 @@ #include "AppKitPrevention.h" +@interface NSXPCConnection (Private) + +@property (nonatomic, readonly) audit_token_t auditToken; + +@end + @implementation SUCodeSigningVerifier + (BOOL)codeSignatureIsValidAtBundleURL:(NSURL *)newBundleURL andMatchesSignatureAtBundleURL:(NSURL *)oldBundleURL error:(NSError * __autoreleasing *)error @@ -263,7 +269,7 @@ static id valueOrNSNull(id value) { return (result == 0); } -static NSString * _Nullable SUTeamIdentifierFromStaticCode(SecStaticCodeRef staticCode) +static NSString * _Nullable SUTeamIdentifierFromCode(SecStaticCodeRef staticCode) { CFDictionaryRef cfSigningInformation = NULL; OSStatus copySigningInfoCode = SecCodeCopySigningInformation(staticCode, kSecCSSigningInformation, @@ -284,12 +290,12 @@ static NSString * _Nullable SUTeamIdentifierFromStaticCode(SecStaticCodeRef stat { SecStaticCodeRef staticCode = NULL; OSStatus staticCodeResult = SecStaticCodeCreateWithPath((__bridge CFURLRef)url, kSecCSDefaultFlags, &staticCode); - if (staticCodeResult != noErr) { + if (staticCodeResult != errSecSuccess) { SULog(SULogLevelError, @"Failed to get static code for retrieving team identifier: %d", staticCodeResult); return nil; } - NSString *teamIdentifier = SUTeamIdentifierFromStaticCode(staticCode); + NSString *teamIdentifier = SUTeamIdentifierFromCode(staticCode); if (staticCode != NULL) { CFRelease(staticCode); @@ -298,6 +304,22 @@ static NSString * _Nullable SUTeamIdentifierFromStaticCode(SecStaticCodeRef stat return teamIdentifier; } ++ (NSString * _Nullable)teamIdentifierFromMainExecutable +{ + SecCodeRef code = NULL; + OSStatus result = SecCodeCopySelf(kSecCSDefaultFlags, &code); + if (result != errSecSuccess) { + SULog(SULogLevelError, @"Failed to get code for retrieving team identifier of main executable: %d", result); + return nil; + } + + NSString *teamIdentifier = SUTeamIdentifierFromCode(code); + + CFRelease(code); + + return teamIdentifier; +} + + (BOOL)codeSignatureIsValidAtDownloadURL:(NSURL *)downloadURL andMatchesDeveloperIDTeamFromOldBundleURL:(NSURL *)oldBundleURL error:(NSError * __autoreleasing *)error { NSString *teamIdentifier = nil; @@ -323,7 +345,7 @@ static NSString * _Nullable SUTeamIdentifierFromStaticCode(SecStaticCodeRef stat goto finally; } - teamIdentifier = SUTeamIdentifierFromStaticCode(oldStaticCode); + teamIdentifier = SUTeamIdentifierFromCode(oldStaticCode); if (teamIdentifier == nil) { resultError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"%@. The team identifier could not be retrieved from the original app: %@", commonErrorMessage, oldBundleURL.path] }]; @@ -421,4 +443,100 @@ finally: return (resultError == nil); } ++ (SUValidateConnectionStatus)validateConnection:(NSXPCConnection *)connection options:(SUValidateConnectionOptions)options error:(NSError * __autoreleasing *)error +{ + NSMutableArray *codeSigningRequirementComponents = [NSMutableArray array]; + + // Build the default team ID signing requirement + NSString *hostTeamIdentifier = [self teamIdentifierFromMainExecutable]; + if (hostTeamIdentifier != nil) { + NSString *teamIdentifierRequirement = [NSString stringWithFormat:@"(anchor apple generic and certificate leaf[subject.OU] = %@)", hostTeamIdentifier]; + [codeSigningRequirementComponents addObject:teamIdentifierRequirement]; + } + + // Build the sandboxing requirement + if ((options & SUValidateConnectionOptionRequireSandboxEntitlement) != 0) { + // This ensures the entitlement is set to true too + NSString *sandboxingRequirement = @"(entitlement [\"com.apple.security.app-sandbox\"] exists)"; + [codeSigningRequirementComponents addObject:sandboxingRequirement]; + } + + // Check if no requirement is required + if (codeSigningRequirementComponents.count == 0) { + return SUValidateConnectionStatusSetNoRequirementSuccess; + } + + NSString *codeSigningRequirement = [codeSigningRequirementComponents componentsJoinedByString:@" and "]; + + if (@available(macOS 13.0, *)) { + [connection setCodeSigningRequirement:codeSigningRequirement]; + + return SUValidateConnectionStatusSetCodeSigningRequirementSuccess; + } + + // Fall back to audit token on older OS's + if ([connection respondsToSelector:@selector(auditToken)]) { + audit_token_t auditToken = [connection auditToken]; + NSData *auditTokenData = [NSData dataWithBytes:&auditToken length:sizeof(auditToken)]; + + NSDictionary *attributes = @{ + (NSString *)kSecGuestAttributeAudit: auditTokenData + }; + + SecCodeRef code = NULL; + OSStatus result = SecCodeCopyGuestWithAttributes(NULL, (__bridge CFDictionaryRef _Nullable)(attributes), kSecCSDefaultFlags, &code); + if (result != errSecSuccess) { + CFRelease(code); + + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"The client connection could not be validated because SecCodeCopyGuestWithAttributes() failed with error %d", result] }]; + } + + return SUValidateConnectionStatusAPIFailure; + } + + // Check if the client is code signed with our signing requirement + + SecRequirementRef requirement = NULL; + result = SecRequirementCreateWithString((__bridge CFStringRef)codeSigningRequirement, kSecCSDefaultFlags, &requirement); + + if (result != errSecSuccess) { + CFRelease(code); + + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"The client connection could not be validated because SecRequirementCreateWithString() failed with error %d", result] }]; + } + + return SUValidateConnectionStatusAPIFailure; + } + + CFErrorRef cfError = NULL; + // This is not a static code, so we don't pass kSecCSCheckAllArchitectures + result = SecCodeCheckValidityWithErrors(code, kSecCSDefaultFlags, requirement, &cfError); + + CFRelease(requirement); + requirement = NULL; + + if (result != errSecSuccess) { + NSError *cfBridgedError = (NSError *)CFBridgingRelease(cfError); + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInsufficientSigningError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"The client connection could not be validated because validating the code signature failed with error %d (%@). Does the app meet the designated requirement: %@", result, cfBridgedError.localizedDescription, codeSigningRequirement] }]; + } + + [self logSigningInfoForCode:code label:@"Client"]; + + CFRelease(code); + + return SUValidateConnectionStatusCodeSigningRequirementFailure; + } + + CFRelease(code); + + return SUValidateConnectionStatusSetCodeSigningRequirementSuccess; + } + + // Not much we can do if auditToken is not supported. This code should not be reached though. + return SUValidateConectionNoSupportedValidationMethodFailure; +} + @end diff --git a/Autoupdate/SUInstaller.h b/Autoupdate/SUInstaller.h index 76481fd7..689481a8 100644 --- a/Autoupdate/SUInstaller.h +++ b/Autoupdate/SUInstaller.h @@ -15,7 +15,7 @@ NS_ASSUME_NONNULL_BEGIN SPU_OBJC_DIRECT_MEMBERS @interface SUInstaller : NSObject -+ (nullable id)installerForHost:(SUHost *)host expectedInstallationType:(NSString *)expectedInstallationType updateDirectory:(NSString *)updateDirectory homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName error:(NSError **)error; ++ (nullable id)installerForHost:(SUHost *)host expectedInstallationType:(NSString *)expectedInstallationType updateDirectory:(NSString *)updateDirectory connectionCodeSigningValidationSkipped:(BOOL)connectionCodeSigningValidationSkipped homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName error:(NSError **)error; + (nullable NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host #if SPARKLE_BUILD_PACKAGE_SUPPORT diff --git a/Autoupdate/SUInstaller.m b/Autoupdate/SUInstaller.m index 1e48fead..cb9d5680 100644 --- a/Autoupdate/SUInstaller.m +++ b/Autoupdate/SUInstaller.m @@ -150,7 +150,7 @@ return newAppDownloadPath; } -+ (nullable id)installerForHost:(SUHost *)host expectedInstallationType:(NSString *)expectedInstallationType updateDirectory:(NSString *)updateDirectory homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName error:(NSError * __autoreleasing *)error ++ (nullable id)installerForHost:(SUHost *)host expectedInstallationType:(NSString *)expectedInstallationType updateDirectory:(NSString *)updateDirectory connectionCodeSigningValidationSkipped:(BOOL)connectionCodeSigningValidationSkipped homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName error:(NSError * __autoreleasing *)error { #if SPARKLE_BUILD_PACKAGE_SUPPORT BOOL isPackage = NO; @@ -170,6 +170,83 @@ return nil; } +#if SPARKLE_BUILD_PACKAGE_SUPPORT + if (isPackage && connectionCodeSigningValidationSkipped) { + // Package updates cannot update arbitrary bundles if code signing validation on the connection was skipped + // (This means our helper is not code signed with an Apple issued certificate). + // In this case, the main executable must be owned by root and the host must contain our installer tool + + NSString *installerExecutablePath = NSBundle.mainBundle.executableURL.URLByResolvingSymlinksInPath.path; + if (installerExecutablePath == nil) { + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"The "@SPARKLE_RELAUNCH_TOOL_NAME" executable path failed to be retrieved, which is an internal error that shouldn't happen. Please try to update using a production build of your app." }]; + } + + return nil; + } + + NSString *hostBundlePath = host.bundle.bundleURL.URLByResolvingSymlinksInPath.path; + if (hostBundlePath == nil) { + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"The host bundle path to update to be retrieved, which is an internal error that shouldn't happen. Please try to update using a production build of your app." }]; + } + + return nil; + } + + NSError *attributesError = nil; + NSDictionary *fileAttributes = [NSFileManager.defaultManager attributesOfItemAtPath:installerExecutablePath error:&attributesError]; + + if (fileAttributes == nil) { + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"File attributes failed to be retrieved from the "@SPARKLE_RELAUNCH_TOOL_NAME" executable, which is an internal error that shouldn't happen. Please try to update using a production build of your app." }]; + } + + return nil; + } + + NSNumber *installerOwnerID = fileAttributes[NSFileOwnerAccountID]; + if (installerOwnerID == nil) { + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"File owner ID failed to be retrieved from the "@SPARKLE_RELAUNCH_TOOL_NAME" executable, which is an internal error that shouldn't happen. Please try to update using a production build of your app." }]; + } + + return nil; + } + + // Check our helper is owned by root + if (![installerOwnerID isEqual:@(0)]) { + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Due to security, updating apps with package installers is disabled when '%@' is not signed with the same Team ID as your app, and "@SPARKLE_RELAUNCH_TOOL_NAME" is not owned by root (this specific case) or not residing in '%@'. Please either test an exported & production build of your app, or for development, code sign your app and Sparkle's embedded helpers with the same team: https://sparkle-project.org/documentation/sandboxing#code-signing", installerExecutablePath, hostBundlePath] }]; + } + + return nil; + } + + NSArray *installerExecutablePathComponents = installerExecutablePath.pathComponents; + NSArray *hostBundlePathComponents = hostBundlePath.pathComponents; + + if (installerExecutablePathComponents.count <= hostBundlePathComponents.count) { + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Due to security, updating apps with package installers is disabled when '%@' is not signed with the same Team ID as your app, and "@SPARKLE_RELAUNCH_TOOL_NAME" is not owned by root or not residing in '%@' (this specific case). Please either test an exported & production build of your app, or for development, code sign your app and Sparkle's embedded helpers with the same team: https://sparkle-project.org/documentation/sandboxing#code-signing", installerExecutablePath, hostBundlePath] }]; + } + + return nil; + } + + // Check out helper resides inside the host app to be updated + if (![[installerExecutablePathComponents subarrayWithRange:NSMakeRange(0, hostBundlePathComponents.count)] isEqualToArray:hostBundlePathComponents]) { + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Due to security, updating apps with package installers is disabled when '%@' is not signed with the same Team ID as your app, and "@SPARKLE_RELAUNCH_TOOL_NAME" is not owned by root or not residing in '%@' (this specific case). Please either test an exported & production build of your app, or for development, code sign your app and Sparkle's embedded helpers with the same team: https://sparkle-project.org/documentation/sandboxing#code-signing", installerExecutablePath, hostBundlePath] }]; + } + + return nil; + } + } +#else + (void)connectionCodeSigningValidationSkipped; +#endif + // Make sure we find the type of installer that we were expecting to find // We shouldn't implicitly trust the installation type fed into here from the appcast because the installation type helps us determine // ahead of time whether or not this installer tool should be ran as root or not diff --git a/Autoupdate/SUPlainInstaller.m b/Autoupdate/SUPlainInstaller.m index 26303ed3..b6e2284b 100644 --- a/Autoupdate/SUPlainInstaller.m +++ b/Autoupdate/SUPlainInstaller.m @@ -353,22 +353,16 @@ // If the update has a custom update security policy, the same team ID policy may not apply, // so in that case we will also skip performing an atomic swap - NSURL *mainExecutableURL = NSBundle.mainBundle.executableURL; - if (mainExecutableURL == nil) { - // This shouldn't happen + updateHasCustomUpdateSecurityPolicy = updateHost.hasUpdateSecurityPolicy; + if (updateHasCustomUpdateSecurityPolicy) { + // We don't handle working around a custom update security policy _canPerformSafeAtomicSwap = NO; } else { - updateHasCustomUpdateSecurityPolicy = updateHost.hasUpdateSecurityPolicy; - if (updateHasCustomUpdateSecurityPolicy) { - // We don't handle working around a custom update security policy - _canPerformSafeAtomicSwap = NO; - } else { - NSString *installerTeamIdentifier = [SUCodeSigningVerifier teamIdentifierAtURL:mainExecutableURL]; - NSString *bundleTeamIdentifier = [SUCodeSigningVerifier teamIdentifierAtURL:bundle.bundleURL]; - - // If bundleTeamIdentifier is nil, then the update isn't code signed so atomic swap is okay - _canPerformSafeAtomicSwap = (bundleTeamIdentifier == nil || (installerTeamIdentifier != nil && [installerTeamIdentifier isEqualToString:bundleTeamIdentifier])); - } + NSString *installerTeamIdentifier = [SUCodeSigningVerifier teamIdentifierFromMainExecutable]; + NSString *bundleTeamIdentifier = [SUCodeSigningVerifier teamIdentifierAtURL:bundle.bundleURL]; + + // If bundleTeamIdentifier is nil, then the update isn't code signed so atomic swap is okay + _canPerformSafeAtomicSwap = (bundleTeamIdentifier == nil || (installerTeamIdentifier != nil && [installerTeamIdentifier isEqualToString:bundleTeamIdentifier])); } } else { _canPerformSafeAtomicSwap = YES; diff --git a/Downloader/SPUDownloader.m b/Downloader/SPUDownloader.m index 6f6d3b78..32322751 100644 --- a/Downloader/SPUDownloader.m +++ b/Downloader/SPUDownloader.m @@ -55,6 +55,32 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; - (void)startDownloadWithRequest:(NSURLRequest *)request SPU_OBJC_DIRECT { + if (request == nil) { + NSString *message = @"The download request must not be nil"; + NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:@{ NSLocalizedDescriptionKey: message }]; + [_delegate downloaderDidFailWithError:error]; + + return; + } + + // Prevent any unwanted URL schemes (e.g. file://) + NSString *scheme = request.URL.scheme; + if (scheme == nil) { + NSString *message = @"The download request scheme must not be nil"; + NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:@{ NSLocalizedDescriptionKey: message }]; + [_delegate downloaderDidFailWithError:error]; + + return; + } + + if ([scheme caseInsensitiveCompare:@"http"] != NSOrderedSame && [scheme caseInsensitiveCompare:@"https"] != NSOrderedSame) { + NSString *message = [NSString stringWithFormat:@"The download request URL must use http or https (%@)", request.URL]; + NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:@{ NSLocalizedDescriptionKey: message }]; + [_delegate downloaderDidFailWithError:error]; + + return; + } + _downloadSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self @@ -117,12 +143,14 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; // The downloader instance that creates this temp directory isn't necessarily the same as the one // that clears it (eg upon skipping an already downloaded update), so we can't just preserve it here too dispatch_async(dispatch_get_main_queue(), ^{ - NSString *rootPersistentDownloadCachePath = [self rootPersistentDownloadCachePathForBundleIdentifier:bundleIdentifier]; - if (rootPersistentDownloadCachePath != nil) { - NSString *sanitizedDownloadToken = downloadToken.lastPathComponent; - NSString *tempDir = [rootPersistentDownloadCachePath stringByAppendingPathComponent:sanitizedDownloadToken]; - - [[NSFileManager defaultManager] removeItemAtPath:tempDir error:NULL]; + if (bundleIdentifier != nil && downloadToken != nil) { + NSString *rootPersistentDownloadCachePath = [self rootPersistentDownloadCachePathForBundleIdentifier:bundleIdentifier]; + if (rootPersistentDownloadCachePath != nil) { + NSString *sanitizedDownloadToken = downloadToken.lastPathComponent; + NSString *tempDir = [rootPersistentDownloadCachePath stringByAppendingPathComponent:sanitizedDownloadToken]; + + [[NSFileManager defaultManager] removeItemAtPath:tempDir error:NULL]; + } } }); } @@ -148,7 +176,9 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; dispatch_async(dispatch_get_main_queue(), ^{ [self _cleanup]; - completionHandler(); + if (completionHandler != NULL) { + completionHandler(); + } }); } diff --git a/Downloader/main.m b/Downloader/main.m index 8b960dda..319ce796 100644 --- a/Downloader/main.m +++ b/Downloader/main.m @@ -9,6 +9,8 @@ #import #import "SPUDownloader.h" #import "SPUDownloaderDelegate.h" +#import "SULog.h" +#import "SUCodeSigningVerifier.h" @interface ServiceDelegate : NSObject @end @@ -18,6 +20,29 @@ - (BOOL)listener:(NSXPCListener *)__unused listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection { // This method is where the NSXPCListener configures, accepts, and resumes a new incoming NSXPCConnection. + // Validate connection of clients to avoid any client from using the service. + // Ideally we would also prevent clients connecting that have an outgoing network connection enabled, + // but this is not easy to enforce. + // This is a policy, not a security critical enforcement. + { + NSError *validationError = nil; + SUValidateConnectionStatus validationStatus = [SUCodeSigningVerifier validateConnection:newConnection options:SUValidateConnectionOptionDefault error:&validationError]; + switch (validationStatus) { + case SUValidateConnectionStatusSetCodeSigningRequirementSuccess: + break; + case SUValidateConnectionStatusSetNoRequirementSuccess: + break; + case SUValidateConnectionStatusAPIFailure: + case SUValidateConnectionStatusCodeSigningRequirementFailure: + case SUValidateConectionNoSupportedValidationMethodFailure: + SULog(SULogLevelError, @"Error: Downloader XPC Service is rejecting new connection due to failing validation of XPC connection with status %lu and error: %@", validationStatus, validationError.localizedDescription); + + [newConnection invalidate]; + + return NO; + } + } + // Configure the connection. // First, set the interface that the exported object implements. newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SPUDownloaderProtocol)]; diff --git a/InstallerLauncher/SUInstallerLauncher.m b/InstallerLauncher/SUInstallerLauncher.m index d9a5e184..0019e75b 100644 --- a/InstallerLauncher/SUInstallerLauncher.m +++ b/InstallerLauncher/SUInstallerLauncher.m @@ -106,7 +106,7 @@ return (submittedJob == true); } -- (SUInstallerLauncherStatus)submitInstallerAtPath:(NSString *)installerPath withHostBundle:(NSBundle *)hostBundle updaterIdentifier:(NSString *)updaterIdentifier userName:(NSString *)userName homeDirectory:(NSString *)homeDirectory authorizationPrompt:(NSString *)authorizationPrompt inSystemDomain:(BOOL)systemDomain rootUser:(BOOL)rootUser SPU_OBJC_DIRECT +- (SUInstallerLauncherStatus)submitInstallerAtPath:(NSString *)installerPath withHostBundle:(NSBundle *)hostBundle updaterIdentifier:(NSString *)updaterIdentifier userName:(NSString *)userName homeDirectory:(NSString *)homeDirectory mainBundleName:(NSString *)mainBundleName inSystemDomain:(BOOL)systemDomain rootUser:(BOOL)rootUser SPU_OBJC_DIRECT { SUFileManager *fileManager = [[SUFileManager alloc] init]; @@ -140,14 +140,25 @@ // Using this right rather than using something like kSMRightModifySystemDaemons allows us to present a better worded prompt // Note the right name is cached, so if we want to change the authorization // prompt, we may need to change the right name. I have found no good way around this :| + + SUHost *host = [[SUHost alloc] initWithBundle:hostBundle]; + NSString *hostName = host.name; + + // Figure out the authorization prompt and right name + // We create the authorization prompt here so that a bad client cannot pass in a completely arbitrary prompt message + // We also forgo localization for this prompt at the moment because with the right name being cached, updating localizations will be undesirable. + // Furthermore, we can avoid adding localization files to the Installer XPC Service (if that one is being used). NSString *sparkleAuthTag = @"sparkle2-auth"; // this needs to change if auth wording changes NSString *rightNameString; + NSString *authorizationPrompt; if ([hostBundleIdentifier isEqualToString:updaterIdentifier]) { // Application bundle is likely updating itself rightNameString = [NSString stringWithFormat:@"%@.%@", hostBundleIdentifier, sparkleAuthTag]; + authorizationPrompt = [NSString stringWithFormat:@"%1$@ wants permission to update.", hostName]; } else { // Updater is likely updating a bundle that is not itself rightNameString = [NSString stringWithFormat:@"%@.%@.%@", updaterIdentifier, hostBundleIdentifier, sparkleAuthTag]; + authorizationPrompt = [NSString stringWithFormat:@"%1$@ wants permission to update %2$@.", mainBundleName, hostName]; } const char *rightName = rightNameString.UTF8String; @@ -403,9 +414,38 @@ static BOOL SPUUsesSystemDomainForBundlePath(NSString *path, BOOL rootUser } // Note: do not pass untrusted information such as paths to the installer and progress agent tools, when we can find them ourselves here -- (void)launchInstallerWithHostBundlePath:(NSString *)hostBundlePath updaterIdentifier:(NSString *)updaterIdentifier authorizationPrompt:(NSString *)authorizationPrompt installationType:(NSString *)installationType allowingDriverInteraction:(BOOL)allowingDriverInteraction completion:(void (^)(SUInstallerLauncherStatus, BOOL))completionHandler +- (void)launchInstallerWithHostBundlePath:(NSString *)hostBundlePath updaterIdentifier:(NSString *)updaterIdentifier mainBundleName:(NSString *)mainBundleName installationType:(NSString *)installationType allowingDriverInteraction:(BOOL)allowingDriverInteraction completion:(void (^)(SUInstallerLauncherStatus, BOOL))completionHandler { dispatch_async(dispatch_get_main_queue(), ^{ + if (completionHandler == NULL) { + SULog(SULogLevelError, @"Error: Failed to retrieve completionHandler (nil)"); + return; + } + + if (hostBundlePath == nil) { + SULog(SULogLevelError, @"Error: Failed to retrieve hostBundlePath (nil)"); + completionHandler(SUInstallerLauncherFailure, NO); + return; + } + + if (updaterIdentifier == nil) { + SULog(SULogLevelError, @"Error: Failed to retrieve updaterIdentifier (nil)"); + completionHandler(SUInstallerLauncherFailure, NO); + return; + } + + if (mainBundleName == nil) { + SULog(SULogLevelError, @"Error: Failed to retrieve mainBundleName (nil)"); + completionHandler(SUInstallerLauncherFailure, NO); + return; + } + + if (installationType == nil) { + SULog(SULogLevelError, @"Error: Failed to retrieve installationType (nil)"); + completionHandler(SUInstallerLauncherFailure, NO); + return; + } + // We could do a sort of preflight Authorization test instead of testing if we are running as root, // but I think this is not necessarily a better approach. We have to chown() the launcher cache directory later on, // and that is not necessarily related to a preflight test. It's more related to being ran under a root / different user from the active GUI session @@ -535,7 +575,7 @@ static BOOL SPUUsesSystemDomainForBundlePath(NSString *path, BOOL rootUser return; } - SUInstallerLauncherStatus installerStatus = [self submitInstallerAtPath:installerPath withHostBundle:hostBundle updaterIdentifier:updaterIdentifier userName:userName homeDirectory:homeDirectory authorizationPrompt:authorizationPrompt inSystemDomain:inSystemDomain rootUser:rootUser]; + SUInstallerLauncherStatus installerStatus = [self submitInstallerAtPath:installerPath withHostBundle:hostBundle updaterIdentifier:updaterIdentifier userName:userName homeDirectory:homeDirectory mainBundleName:mainBundleName inSystemDomain:inSystemDomain rootUser:rootUser]; BOOL submittedProgressTool = NO; if (installerStatus == SUInstallerLauncherSuccess) { diff --git a/InstallerLauncher/SUInstallerLauncherProtocol.h b/InstallerLauncher/SUInstallerLauncherProtocol.h index b43bbe75..f098fadd 100644 --- a/InstallerLauncher/SUInstallerLauncherProtocol.h +++ b/InstallerLauncher/SUInstallerLauncherProtocol.h @@ -11,6 +11,6 @@ @protocol SUInstallerLauncherProtocol -- (void)launchInstallerWithHostBundlePath:(NSString *)hostBundlePath updaterIdentifier:(NSString *)updaterBundleIdentifier authorizationPrompt:(NSString *)authorizationPrompt installationType:(NSString *)installationType allowingDriverInteraction:(BOOL)allowingDriverInteraction completion:(void (^)(SUInstallerLauncherStatus, BOOL))completionHandler; +- (void)launchInstallerWithHostBundlePath:(NSString *)hostBundlePath updaterIdentifier:(NSString *)updaterBundleIdentifier mainBundleName:(NSString *)mainBundleName installationType:(NSString *)installationType allowingDriverInteraction:(BOOL)allowingDriverInteraction completion:(void (^)(SUInstallerLauncherStatus, BOOL))completionHandler; @end diff --git a/InstallerLauncher/main.m b/InstallerLauncher/main.m index 6f1ac846..b9b472c5 100644 --- a/InstallerLauncher/main.m +++ b/InstallerLauncher/main.m @@ -8,6 +8,8 @@ #import #import "SUInstallerLauncher.h" +#import "SULog.h" +#import "SUCodeSigningVerifier.h" @interface ServiceDelegate : NSObject @end @@ -17,6 +19,27 @@ - (BOOL)listener:(NSXPCListener *)__unused listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection { // This method is where the NSXPCListener configures, accepts, and resumes a new incoming NSXPCConnection. + // Validate connection of clients to avoid any client from using the service. + // This is a policy, not a security critical enforcement. + { + NSError *validationError = nil; + SUValidateConnectionStatus validationStatus = [SUCodeSigningVerifier validateConnection:newConnection options: SUValidateConnectionOptionDefault error:&validationError]; + switch (validationStatus) { + case SUValidateConnectionStatusSetCodeSigningRequirementSuccess: + break; + case SUValidateConnectionStatusSetNoRequirementSuccess: + break; + case SUValidateConnectionStatusAPIFailure: + case SUValidateConnectionStatusCodeSigningRequirementFailure: + case SUValidateConectionNoSupportedValidationMethodFailure: + SULog(SULogLevelError, @"Error: Installer XPC Service is rejecting new connection due to failing validation of XPC connection with status %lu and error: %@", validationStatus, validationError.localizedDescription); + + [newConnection invalidate]; + + return NO; + } + } + // Configure the connection. // First, set the interface that the exported object implements. newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerLauncherProtocol)]; diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index 87d7e335..f381450f 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -354,6 +354,9 @@ 728ED34C277DA23400D9238F /* SPUSparkleDeltaArchive.m in Sources */ = {isa = PBXBuildFile; fileRef = 728ED349277DA23400D9238F /* SPUSparkleDeltaArchive.m */; }; 728ED34D277DA23400D9238F /* SPUSparkleDeltaArchive.m in Sources */ = {isa = PBXBuildFile; fileRef = 728ED349277DA23400D9238F /* SPUSparkleDeltaArchive.m */; }; 729051E41DC82AC0003DEA7F /* SUOperatingSystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 726F2CE41BC9C33D001971A4 /* SUOperatingSystem.m */; }; + 7290BF2F2E5A5AFA00D75022 /* SUCodeSigningVerifier.m in Sources */ = {isa = PBXBuildFile; fileRef = 7267E5991D3D8A5A00D1BF90 /* SUCodeSigningVerifier.m */; }; + 7290BF302E5A5B0F00D75022 /* SUCodeSigningVerifier.m in Sources */ = {isa = PBXBuildFile; fileRef = 7267E5991D3D8A5A00D1BF90 /* SUCodeSigningVerifier.m */; }; + 7290BF312E5A5B2F00D75022 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 61B5F8F609C4CEB300B25A18 /* Security.framework */; }; 729743AB279D1BD2009910B2 /* SUCodeSigningVerifier.m in Sources */ = {isa = PBXBuildFile; fileRef = 7267E5991D3D8A5A00D1BF90 /* SUCodeSigningVerifier.m */; }; 729924941DF4A45000DBCDF5 /* SUUpdateValidator.m in Sources */ = {isa = PBXBuildFile; fileRef = 729924931DF4A45000DBCDF5 /* SUUpdateValidator.m */; }; 729F7EAC27366353004592DC /* test-links.xml in Resources */ = {isa = PBXBuildFile; fileRef = 729F7EAB27366353004592DC /* test-links.xml */; }; @@ -1622,6 +1625,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 7290BF312E5A5B2F00D75022 /* Security.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -3541,6 +3545,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 7290BF302E5A5B0F00D75022 /* SUCodeSigningVerifier.m in Sources */, 72464F7E1E21ED8C00FB341C /* SUHost.m in Sources */, 726E07B41CAF08D6001A286B /* main.m in Sources */, 721D8A7B1D4963190032E472 /* SPULocalCacheDirectory.m in Sources */, @@ -3558,6 +3563,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 7290BF2F2E5A5AFA00D75022 /* SUCodeSigningVerifier.m in Sources */, 723B5DA71CF7AB0100365F95 /* main.m in Sources */, 72E539121D68C3FA0092CE5E /* SPUDownloadData.m in Sources */, 723B5DA91CF7AB0100365F95 /* SPUDownloader.m in Sources */, diff --git a/Sparkle/InstallerProgress/InstallerProgressAppController.m b/Sparkle/InstallerProgress/InstallerProgressAppController.m index 22a7fd85..ab7a25fe 100644 --- a/Sparkle/InstallerProgress/InstallerProgressAppController.m +++ b/Sparkle/InstallerProgress/InstallerProgressAppController.m @@ -291,7 +291,9 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; NSRunningApplication *firstRunningApplication = runningApplications.firstObject; BOOL targetDead = (firstRunningApplication == nil || firstRunningApplication.terminated); - reply(targetDead); + if (reply != NULL) { + reply(targetDead); + } self->_repliedToRegistration = YES; self->_applicationBundle = applicationBundle; @@ -329,7 +331,9 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; #endif if (self->_targetRunningApplication != nil && self->_terminationCompletionHandler == nil) { if (self->_targetRunningApplication.terminated) { - completionHandler(); + if (completionHandler != NULL) { + completionHandler(); + } } else { self->_terminationCompletionHandler = [completionHandler copy]; diff --git a/Sparkle/SPUDownloadDriver.m b/Sparkle/SPUDownloadDriver.m index 3578b704..091ec681 100644 --- a/Sparkle/SPUDownloadDriver.m +++ b/Sparkle/SPUDownloadDriver.m @@ -81,7 +81,9 @@ if (strongSelf != nil && !strongSelf->_retrievedDownloadResult && !strongSelf->_cleaningUp) { strongSelf->_downloader = nil; - SULog(SULogLevelError, @"Connection to update downloader was invalidated"); + // We can't enforce com.apple.security.network.client == NO or it being absent for sandboxed clients, + // but we should warn about it anyway + SULog(SULogLevelError, @"Error: Connection to update downloader was invalidated. If your app is not sandboxed or has com.apple.security.network.client set to YES, please remove %@ from your Info.plist. Otherwise please check Console logs for "@DOWNLOADER_NAME" if there are any additional details.", SUEnableDownloaderServiceKey); NSDictionary *userInfo = @{ diff --git a/Sparkle/SPUInstallerDriver.m b/Sparkle/SPUInstallerDriver.m index bc8a3519..a9b09776 100644 --- a/Sparkle/SPUInstallerDriver.m +++ b/Sparkle/SPUInstallerDriver.m @@ -167,13 +167,16 @@ NSString *hostBundleIdentifier = _host.bundle.bundleIdentifier; assert(hostBundleIdentifier != nil); + BOOL usingInstallerService; #if INSTALLER_CONNECTION_XPC_SERVICE_EMBEDDED if (SPUXPCServiceIsEnabled(SUEnableInstallerConnectionServiceKey)) { _installerConnection = [[SUXPCInstallerConnection alloc] initWithDelegate:self]; + usingInstallerService = YES; } else #endif { _installerConnection = [[SUInstallerConnection alloc] initWithDelegate:self remote:NO]; + usingInstallerService = NO; } __weak __typeof__(self) weakSelf = self; @@ -181,9 +184,11 @@ dispatch_async(dispatch_get_main_queue(), ^{ __typeof__(self) strongSelf = weakSelf; if (strongSelf != nil && strongSelf->_installerConnection != nil && !strongSelf->_aborted) { + NSString *impactedTools = usingInstallerService ? (@SPARKLE_RELAUNCH_TOOL_NAME" and "@INSTALLER_LAUNCHER_NAME) : @SPARKLE_RELAUNCH_TOOL_NAME; + NSDictionary *genericUserInfo = @{ NSLocalizedDescriptionKey: SULocalizedStringFromTableInBundle(@"An error occurred while running the updater. Please try again later.", SPARKLE_TABLE, SUSparkleBundle(), nil), - NSLocalizedFailureReasonErrorKey:@"The remote port connection was invalidated from the updater. For additional details, please check Console logs for "@SPARKLE_RELAUNCH_TOOL_NAME". If your application is sandboxed, please also ensure Installer Connection & Status entitlements are correctly set up: https://sparkle-project.org/documentation/sandboxing/" + NSLocalizedFailureReasonErrorKey:[NSString stringWithFormat:@"The remote port connection was invalidated from the updater. If your application is sandboxed, please ensure Installer Connection & Status entitlements are correctly set up: https://sparkle-project.org/documentation/sandboxing/ . Otherwise if %@ %@ not adhoc signed, your app must be signed with a matching team ID. For additional details, check Console logs for %@", impactedTools, (usingInstallerService ? @"are" : @"is"), impactedTools] }; [strongSelf _reportInstallerError:strongSelf->_installerError genericErrorCode:SUInstallationError genericUserInfo:genericUserInfo]; @@ -408,7 +413,8 @@ if (!retrievedLaunchStatus) { #pragma clang diagnostic pop NSError *error = - [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey:SULocalizedStringFromTableInBundle(@"An error occurred while connecting to the installer. Please try again later.", SPARKLE_TABLE, SUSparkleBundle(), nil) }]; + [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey:SULocalizedStringFromTableInBundle(@"An error occurred while connecting to the installer. Please try again later.", SPARKLE_TABLE, SUSparkleBundle(), nil), + NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"If your app is not sandboxed, please remove or disable %@ in your app's Info.plist. Otherwise please check Console logs for "@INSTALLER_LAUNCHER_NAME" and "@SPARKLE_RELAUNCH_TOOL_NAME" processes if there are additional details.", SUEnableInstallerLauncherServiceKey]}]; completionHandler(error); @@ -441,26 +447,10 @@ NSString *installationType = _updateItem.installationType; assert(installationType != nil); - // The installer launcher could be in a XPC service, so we don't want to do localization in there - // Make sure the authorization prompt reflects whether or not the updater is updating itself, or - // if the updater is updating another application. We use SUHost.name property, so an application - // or Sparkle helper application can override its name with SUBundleName key - SUHost *mainBundleHost = [[SUHost alloc] initWithBundle:[NSBundle mainBundle]]; + // We use SUHost.name property, so an application + // or Sparkle helper application can override its name with SUBundleName key NSString *mainBundleName = mainBundleHost.name; - NSString *hostName = _host.name; - - // Changing this authorization prompt is a little complicated because the - // Auth database retains and caches the right we use, and there isn't a good way - // of updating the prompt. See code in SUInstallerLauncher.m - // For this reason, we don't provide localized strings for this prompt yet - // (and I believe, the authorization framework has a different way of specifying localizations..) - NSString *authorizationPrompt; - if ([mainBundleName isEqualToString:hostName]) { - authorizationPrompt = [NSString stringWithFormat:@"%1$@ wants permission to update.", hostName]; - } else { - authorizationPrompt = [NSString stringWithFormat:@"%1$@ wants permission to update %2$@.", mainBundleName, hostName]; - } NSString *mainBundleIdentifier; { @@ -468,7 +458,7 @@ mainBundleIdentifier = (bundleIdentifier == nil) ? mainBundleName : bundleIdentifier; } - [installerLauncher launchInstallerWithHostBundlePath:hostBundlePath updaterIdentifier:mainBundleIdentifier authorizationPrompt:authorizationPrompt installationType:installationType allowingDriverInteraction:driverAllowsInteraction completion:^(SUInstallerLauncherStatus result, BOOL systemDomain) { + [installerLauncher launchInstallerWithHostBundlePath:hostBundlePath updaterIdentifier:mainBundleIdentifier mainBundleName:mainBundleName installationType:installationType allowingDriverInteraction:driverAllowsInteraction completion:^(SUInstallerLauncherStatus result, BOOL systemDomain) { dispatch_async(dispatch_get_main_queue(), ^{ #if INSTALLER_LAUNCHER_XPC_SERVICE_EMBEDDED retrievedLaunchStatus = YES; diff --git a/Tests/SUInstallerTest.m b/Tests/SUInstallerTest.m index 9c953008..fce79889 100644 --- a/Tests/SUInstallerTest.m +++ b/Tests/SUInstallerTest.m @@ -56,7 +56,7 @@ NSError *installerError = nil; // Note: we may not be using the "correct" home directory or user name (they will be root) but our test pkg does not have // pre/post install scripts so it doesn't matter - id installer = [SUInstaller installerForHost:host expectedInstallationType:SPUInstallationTypeGuidedPackage updateDirectory:[path stringByDeletingLastPathComponent] homeDirectory:NSHomeDirectory() userName:NSUserName() error:&installerError]; + id installer = [SUInstaller installerForHost:host expectedInstallationType:SPUInstallationTypeGuidedPackage updateDirectory:[path stringByDeletingLastPathComponent] connectionCodeSigningValidationSkipped:NO homeDirectory:NSHomeDirectory() userName:NSUserName() error:&installerError]; if (installer == nil) { XCTFail(@"Installer is nil with error: %@", installerError);