From f6bc73a38cab825765435af34f7e1dc8bb04242b Mon Sep 17 00:00:00 2001 From: Zorg Date: Sat, 8 Aug 2026 20:50:29 -0700 Subject: [PATCH] Harden safety of installer moving the download archive --- Autoupdate/AppInstaller.m | 54 ++++++++++++++++-- Sparkle/SUFileManager.h | 24 ++++++++ Sparkle/SUFileManager.m | 114 +++++++++++++++++++++++++++++++++++++- 3 files changed, 183 insertions(+), 9 deletions(-) diff --git a/Autoupdate/AppInstaller.m b/Autoupdate/AppInstaller.m index ddbc9ede..742c7863 100644 --- a/Autoupdate/AppInstaller.m +++ b/Autoupdate/AppInstaller.m @@ -481,9 +481,21 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; return; } + // Try to resolve the download URL from symlinks + SUFileManager *fileManager = [[SUFileManager alloc] init]; + NSError *resolveError = nil; + NSURL *resolvedDownloadURL = [fileManager resolveSymlinksInURL:downloadURL isDirectory:NO error:&resolveError]; + if (resolvedDownloadURL == nil) { + SULogError(resolveError); + + // Try to fallback onto regular downloadURL if resolving fails + // Later file operations are performed safely even if the URL doesn't have symlinks resolved. + resolvedDownloadURL = downloadURL; + } + // Validate the download URL before moving it { - NSArray *downloadURLPathComponents = downloadURL.URLByResolvingSymlinksInPath.pathComponents; + NSArray *downloadURLPathComponents = resolvedDownloadURL.pathComponents; if (downloadURLPathComponents == nil) { [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Error: Failed to retrieve path components from download URL" }]]; @@ -546,12 +558,42 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; // This prevents eg: if a bug exists in the updater that removes files we are trying to install // When this tool is ran as root, we are moving it into a directory that only root will have access to - NSURL *downloadDestinationURL = [[NSURL fileURLWithPath:cacheInstallationPath] URLByAppendingPathComponent:downloadName]; + NSURL *cacheInstallationURL = [NSURL fileURLWithPath:cacheInstallationPath isDirectory:YES]; - NSError *moveError = nil; - if (![[[SUFileManager alloc] init] moveItemAtURL:downloadURL toURL:downloadDestinationURL error:&moveError]) { - [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Error: Failed to move download archive to new location", NSUnderlyingErrorKey: moveError }]]; - return; + NSError *resolvedCacheInstallationError = nil; + NSURL *resolvedCacheInstallationURL = [fileManager resolveSymlinksInURL:cacheInstallationURL isDirectory:YES error:&resolvedCacheInstallationError]; + if (resolvedCacheInstallationURL == nil) { + // Fallback to original cache installation URL if resolving fails + SULogError(resolvedCacheInstallationError); + resolvedCacheInstallationURL = cacheInstallationURL; + } + + NSURL *downloadDestinationURL = [resolvedCacheInstallationURL URLByAppendingPathComponent:downloadName isDirectory:NO]; + + BOOL fallbackToFileCopy; + if (@available(macOS 11, *)) { + NSError *renameError = nil; + if (![fileManager renameItemAtResolvedSymlinkURL:resolvedDownloadURL toResolvedSymlinkURL:downloadDestinationURL error:&renameError]) { + SULog(SULogLevelError, @"Error: failed to rename '%@' to '%@'. Falling back to copy operation.", resolvedDownloadURL.path, downloadDestinationURL.path); + + SULogError(renameError); + + fallbackToFileCopy = YES; + } else { + fallbackToFileCopy = NO; + } + } else { + fallbackToFileCopy = YES; + } + + if (fallbackToFileCopy) { + // The client will be responsible for cleaning up the download. + // We will not risk removing it here if rename failed. Copying the file is safer. + NSError *copyError = nil; + if (![fileManager copyItemAtURL:resolvedDownloadURL toURL:downloadDestinationURL error:©Error]) { + [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Error: Failed to copy download archive to new location", NSUnderlyingErrorKey: copyError }]]; + return; + } } // Make sure the downloaded archive we moved over is a regular file and not a symbolic link placed by an attacker diff --git a/Sparkle/SUFileManager.h b/Sparkle/SUFileManager.h index 34e33afb..83b13f30 100644 --- a/Sparkle/SUFileManager.h +++ b/Sparkle/SUFileManager.h @@ -58,6 +58,30 @@ SUFileManagerDefinitionAttribute */ - (BOOL)moveItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError **)error; +/** + * Renames an item from a source to a destination assuming source and destination URLs have symbolic links resolved. + * @param sourceURL A URL pointing to the item to rename. The item at this URL must exist. + * @param destinationURL A URL pointing to the destination the item will be moved at. + * @param error if an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL. + * @return YES if the time was renamed successfully, otherwise NO along with a pouplated error object. + * + * sourceURL and destinationURL must reside on the same volume otherwise this operation will fail. + * If any symbolic links are encountered in these paths during path resolution, this operation will fail. + */ +- (BOOL)renameItemAtResolvedSymlinkURL:(NSURL *)sourceURL toResolvedSymlinkURL:(NSURL *)destinationURL error:(NSError *__autoreleasing *)error API_AVAILABLE(macosx(11.0)); + +/** + * Returns a URL by resolving links in path. + * @param url A URL pointing to a real file to resolve symlinks in path. + * @param isDirectory Indicates if the URL is a directory. + * @param error if an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL. + * @return A URL that is resolved and has no symlinks in its path. + * + * This method is suitable to resolving a URL before passing it to -renameItemAtResolvedSymlinkURL:toResolvedSymlinkURL:error: + * -[NSURL URLByResolvingSymlinksInPath] does not resolve symlinks for file paths starting with /private/ hence the need for this method. + */ +- (NSURL * _Nullable)resolveSymlinksInURL:(NSURL *)url isDirectory:(BOOL)isDirectory error:(NSError * __autoreleasing *)error; + /** * Swaps an original item with a new item atomically. * @param originalItemURL A URL pointing to the original item to replace. The item at this URL must exist. diff --git a/Sparkle/SUFileManager.m b/Sparkle/SUFileManager.m index a80614ba..5c0970f3 100644 --- a/Sparkle/SUFileManager.m +++ b/Sparkle/SUFileManager.m @@ -225,7 +225,28 @@ SPU_OBJC_DIRECT return [_fileManager moveItemAtURL:sourceURL toURL:destinationURL error:error]; } -- (BOOL)swapItemAtURL:(NSURL *)originalItemURL withItemAtURL:(NSURL *)newItemURL error:(NSError * __autoreleasing *)error +- (NSURL * _Nullable)resolveSymlinksInURL:(NSURL *)url isDirectory:(BOOL)isDirectory error:(NSError * __autoreleasing *)error +{ + char path[PATH_MAX] = {0}; + if (![url.path getFileSystemRepresentation:path maxLength:sizeof(path)]) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to retrieve file system representation before resolving symlinks in %@", url.path] }]; + } + return nil; + } + + char resolvedPath[PATH_MAX] = {0}; + if (realpath(path, resolvedPath) == NULL) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to resolve symlinks in %@", url.path] }]; + } + return nil; + } + + return [[NSURL alloc] initFileURLWithFileSystemRepresentation:resolvedPath isDirectory:isDirectory relativeToURL:nil]; +} + +static BOOL renameFile(NSURL *originalItemURL, NSURL *newItemURL, unsigned int renameFlags, NSError * __autoreleasing *error) { char originalPath[PATH_MAX] = {0}; if (![originalItemURL.path getFileSystemRepresentation:originalPath maxLength:sizeof(originalPath)]) { @@ -243,10 +264,10 @@ SPU_OBJC_DIRECT return NO; } - int status = renamex_np(newPath, originalPath, RENAME_SWAP); + int status = renamex_np(originalPath, newPath, renameFlags); if (status != 0) { if (error != NULL) { - *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to replace %@ with %@.", originalItemURL.lastPathComponent, newItemURL.lastPathComponent] }]; + *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to renamex_np %@ with %@.", originalItemURL.lastPathComponent, newItemURL.lastPathComponent] }]; } return NO; } @@ -254,6 +275,93 @@ SPU_OBJC_DIRECT return YES; } +- (BOOL)renameItemAtResolvedSymlinkURL:(NSURL *)sourceURL toResolvedSymlinkURL:(NSURL *)destinationURL error:(NSError *__autoreleasing *)error +{ + if (@available(macOS 13, *)) { + // RENAME_NOFOLLOW_ANY option requires macOS 13+ + return renameFile(sourceURL, destinationURL, RENAME_NOFOLLOW_ANY, error); + } + + // The old path for renaming the file will involve opening file descriptors to parent directories + // and using renameat() without following any symlinks + + NSURL *sourceParentDirectoryURL = sourceURL.URLByDeletingLastPathComponent; + + char sourceParentDirectoryPath[PATH_MAX] = {0}; + if (![sourceParentDirectoryURL getFileSystemRepresentation:sourceParentDirectoryPath maxLength:sizeof(sourceParentDirectoryPath)]) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Source item parent directory %@ to rename cannot be represented as a valid file name", sourceParentDirectoryURL.lastPathComponent] }]; + } + return NO; + } + + char sourceLastPathComponentPath[PATH_MAX] = {0}; + if (![sourceURL.lastPathComponent getFileSystemRepresentation:sourceLastPathComponentPath maxLength:sizeof(sourceLastPathComponentPath)]) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Source item last path component %@ to rename cannot be represented as a valid file name", sourceURL.lastPathComponent] }]; + } + return NO; + } + + char destinationParentDirectoryPath[PATH_MAX] = {0}; + NSURL *destinationParentDirectoryURL = destinationURL.URLByDeletingLastPathComponent; + if (![destinationParentDirectoryURL getFileSystemRepresentation:destinationParentDirectoryPath maxLength:sizeof(destinationParentDirectoryPath)]) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination item parent directory %@ to rename cannot be represented as a valid file name", destinationParentDirectoryURL.lastPathComponent] }]; + } + return NO; + } + + char destinationLastPathComponentPath[PATH_MAX] = {0}; + if (![destinationURL.lastPathComponent getFileSystemRepresentation:destinationLastPathComponentPath maxLength:sizeof(destinationLastPathComponentPath)]) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination item last path component %@ to rename cannot be represented as a valid file name", destinationURL.lastPathComponent] }]; + } + return NO; + } + + // sourceURL and destinationURL is required to have symlinks already resolved so we will use O_NOFOLLOW_ANY to open the parent directories without following symlinks in any of intermediate directories + + int sourceParentDirectoryFileDescriptor = open(sourceParentDirectoryPath, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW_ANY); + if (sourceParentDirectoryFileDescriptor == -1) { + if (error != nil) { + *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open file descriptor to %@", sourceParentDirectoryURL.path.lastPathComponent] }]; + } + return NO; + } + + int destinationParentDirectoryFileDescriptor = open(destinationParentDirectoryPath, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW_ANY); + if (destinationParentDirectoryFileDescriptor == -1) { + if (error != nil) { + *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open file descriptor to %@", destinationParentDirectoryURL.path.lastPathComponent] }]; + } + close(sourceParentDirectoryFileDescriptor); + return NO; + } + + BOOL success = (renameat(sourceParentDirectoryFileDescriptor, sourceLastPathComponentPath, destinationParentDirectoryFileDescriptor, destinationLastPathComponentPath) == 0); + if (!success) { + if (error != nil) { + *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to rename '%@' to '%@'", sourceURL.path, destinationURL.path] }]; + } + } + + if (sourceParentDirectoryFileDescriptor != -1) { + close(sourceParentDirectoryFileDescriptor); + } + + if (destinationParentDirectoryFileDescriptor != -1) { + close(destinationParentDirectoryFileDescriptor); + } + + return success; +} + +- (BOOL)swapItemAtURL:(NSURL *)originalItemURL withItemAtURL:(NSURL *)newItemURL error:(NSError * __autoreleasing *)error +{ + return renameFile(originalItemURL, newItemURL, RENAME_SWAP, error); +} + - (BOOL)changeOwnerAndGroupOfItemAtURL:(NSURL *)targetURL ownerID:(uid_t)ownerID groupID:(gid_t)groupID error:(NSError * __autoreleasing *)error { char path[PATH_MAX] = {0};