From db6b2b05b3ee2ad40a6aeab70017a2b121caa67d Mon Sep 17 00:00:00 2001 From: mac Date: Thu, 5 Nov 2026 23:06:15 +0800 Subject: [PATCH] Reject modified Dayu Color bundles at registration, service startup and update --- 大鱼调色.xcodeproj/project.pbxproj | 6 ++ 大鱼调色/Plugin/Info.plist | 6 +- 大鱼调色/Plugin/main.m | 20 ++++- 大鱼调色/Shared/DYCodeIntegrity.h | 13 +++ 大鱼调色/Shared/DYCodeIntegrity.m | 88 +++++++++++++++++++ 大鱼调色/Wrapper Application/AppDelegate.m | 82 +++++++++++++++-- 大鱼调色/Wrapper Application/DYBetaUpdater.h | 1 + 大鱼调色/Wrapper Application/DYBetaUpdater.mm | 39 ++++++-- 大鱼调色/Wrapper Application/Info.plist | 4 +- 9 files changed, 237 insertions(+), 22 deletions(-) create mode 100644 大鱼调色/Shared/DYCodeIntegrity.h create mode 100644 大鱼调色/Shared/DYCodeIntegrity.m diff --git a/大鱼调色.xcodeproj/project.pbxproj b/大鱼调色.xcodeproj/project.pbxproj index 8a8d0ec..b2646c5 100644 --- a/大鱼调色.xcodeproj/project.pbxproj +++ b/大鱼调色.xcodeproj/project.pbxproj @@ -7,6 +7,8 @@ objects = { /* Begin PBXBuildFile section */ + 34A97A301E774BF3A13BC6A1 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 34A97A301E774BF3A13BC6A3 /* Security.framework */; }; + 34A97A301E774BF3A13BC6A2 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 34A97A301E774BF3A13BC6A3 /* Security.framework */; }; 04962E563095058F009952AA /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 04962E553095058F009952AA /* Cocoa.framework */; }; 04962E5E3095058F009952AA /* 大鱼调色 XPC Service.pluginkit in Embed PlugIns */ = {isa = PBXBuildFile; fileRef = 04962E5D3095058F009952AA /* 大鱼调色 XPC Service.pluginkit */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 04962E623095058F009952AA /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 04962E613095058F009952AA /* Foundation.framework */; }; @@ -39,6 +41,7 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + 34A97A301E774BF3A13BC6A3 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; }; 04962E523095058F009952AA /* 大鱼调色.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "大鱼调色.app"; sourceTree = BUILT_PRODUCTS_DIR; }; 04962E553095058F009952AA /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = System/Library/Frameworks/Cocoa.framework; sourceTree = SDKROOT; }; 04962E5D3095058F009952AA /* 大鱼调色 XPC Service.pluginkit */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "大鱼调色 XPC Service.pluginkit"; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -153,6 +156,7 @@ isa = PBXFrameworksBuildPhase; files = ( 04962E563095058F009952AA /* Cocoa.framework in Frameworks */, + 34A97A301E774BF3A13BC6A1 /* Security.framework in Frameworks */, ); }; 04962E583095058F009952AA /* Frameworks */ = { @@ -163,6 +167,7 @@ 04962E623095058F009952AA /* Foundation.framework in Frameworks */, 04962E643095058F009952AA /* AppKit.framework in Frameworks */, 04962E6A3095058F009952AA /* FxPlug.framework in Frameworks */, + 34A97A301E774BF3A13BC6A2 /* Security.framework in Frameworks */, ); }; /* End PBXFrameworksBuildPhase section */ @@ -195,6 +200,7 @@ 04962E653095058F009952AA /* Accelerate.framework */, 04962E673095058F009952AA /* PluginManager.framework */, 04962E693095058F009952AA /* FxPlug.framework */, + 34A97A301E774BF3A13BC6A3 /* Security.framework */, ); name = Frameworks; sourceTree = ""; diff --git a/大鱼调色/Plugin/Info.plist b/大鱼调色/Plugin/Info.plist index 140c8f5..f37ea11 100644 --- a/大鱼调色/Plugin/Info.plist +++ b/大鱼调色/Plugin/Info.plist @@ -17,9 +17,9 @@ CFBundlePackageType XPC! CFBundleShortVersionString - 1.13.1 + 1.13.2 CFBundleVersion - 85 + 86 NSHumanReadableCopyright PlugInKit @@ -71,7 +71,7 @@ uuid 1C17B73B-F229-4C09-A434-EAF6DFF5F22A version - 1.13.1 + 1.13.2 className diff --git a/大鱼调色/Plugin/main.m b/大鱼调色/Plugin/main.m index 231d4c0..4ad1bd1 100644 --- a/大鱼调色/Plugin/main.m +++ b/大鱼调色/Plugin/main.m @@ -1,5 +1,23 @@ #import #import "DYDiagnostics.h" #import "../Shared/DYBetaDiagnostics.h" +#import "../Shared/DYCodeIntegrity.h" #include -int main(int argc,const char*argv[]){@autoreleasepool{if(argc==2&&strcmp(argv[1],"--self-test")==0)return DYRunDiagnostics();DYBetaStart();[FxPrincipal startServicePrincipal];DYBetaStop();return 0;}} +#include + +int main(int argc, const char *argv[]) { + @autoreleasepool { + NSString *component = nil; + OSStatus status = DYValidateRunningInstallation(DYCodeRoleService, &component); + if (status != errSecSuccess) { + NSLog(@"大鱼调色拒绝启动插件服务,验签失败 (%@, %d)。%@", component, (int)status, + DYIntegrityRecoveryMessage); + return EX_CONFIG; + } + if (argc == 2 && strcmp(argv[1], "--self-test") == 0) return DYRunDiagnostics(); + DYBetaStart(); + [FxPrincipal startServicePrincipal]; + DYBetaStop(); + return 0; + } +} diff --git a/大鱼调色/Shared/DYCodeIntegrity.h b/大鱼调色/Shared/DYCodeIntegrity.h new file mode 100644 index 0000000..44f3a9e --- /dev/null +++ b/大鱼调色/Shared/DYCodeIntegrity.h @@ -0,0 +1,13 @@ +#import +#import + +typedef NS_ENUM(NSInteger, DYCodeRole) { + DYCodeRoleWrapper, + DYCodeRoleService, +}; + +FOUNDATION_EXPORT NSString *const DYPluginRelativePath; +FOUNDATION_EXPORT NSString *const DYIntegrityRecoveryMessage; + +FOUNDATION_EXPORT OSStatus DYValidateSignedInstallation(NSURL *wrapperURL, NSString **failedComponent); +FOUNDATION_EXPORT OSStatus DYValidateRunningInstallation(DYCodeRole role, NSString **failedComponent); diff --git a/大鱼调色/Shared/DYCodeIntegrity.m b/大鱼调色/Shared/DYCodeIntegrity.m new file mode 100644 index 0000000..3241de5 --- /dev/null +++ b/大鱼调色/Shared/DYCodeIntegrity.m @@ -0,0 +1,88 @@ +#import "DYCodeIntegrity.h" + +NSString *const DYPluginRelativePath = @"Contents/PlugIns/大鱼调色 XPC Service.pluginkit"; +NSString *const DYIntegrityRecoveryMessage = @"大鱼调色未通过官方签名或完整性验证。请使用原始安装包重新安装。"; + +static NSString *const DYWrapperIdentifier = @"com.dayu.color"; +static NSString *const DYServiceIdentifier = @"com.dayu.color.XPC"; + +static OSStatus DYCreateSigningRequirement(NSString *identifier, SecRequirementRef *requirement) { + // Pin the Developer ID team and signing identifier, allowing certificate renewal. + NSString *text = [NSString stringWithFormat: + @"identifier \"%@\" and anchor apple generic and " + "certificate 1[field.1.2.840.113635.100.6.2.6] exists and " + "certificate leaf[field.1.2.840.113635.100.6.1.13] exists and " + "certificate leaf[subject.OU] = \"B3W25FX5H5\"", identifier]; + return SecRequirementCreateWithString((__bridge CFStringRef)text, kSecCSDefaultFlags, requirement); +} + +static OSStatus DYValidateRunningCode(NSString *identifier) { + SecRequirementRef requirement = NULL; + OSStatus status = DYCreateSigningRequirement(identifier, &requirement); + if (status != errSecSuccess) return status; + + SecCodeRef code = NULL; + status = SecCodeCopySelf(kSecCSDefaultFlags, &code); + if (status == errSecSuccess) { + status = SecCodeCheckValidity(code, kSecCSDefaultFlags, requirement); + CFRelease(code); + } + CFRelease(requirement); + return status; +} + +static OSStatus DYValidateBundle(NSURL *url, NSString *identifier, SecCSFlags flags) { + SecRequirementRef requirement = NULL; + OSStatus status = DYCreateSigningRequirement(identifier, &requirement); + if (status != errSecSuccess) return status; + + SecStaticCodeRef code = NULL; + status = SecStaticCodeCreateWithPath((__bridge CFURLRef)url, kSecCSDefaultFlags, &code); + if (status == errSecSuccess) { + status = SecStaticCodeCheckValidity(code, flags | kSecCSStrictValidate | kSecCSCheckAllArchitectures, + requirement); + CFRelease(code); + } + CFRelease(requirement); + return status; +} + +OSStatus DYValidateSignedInstallation(NSURL *wrapperURL, NSString **failedComponent) { + if (failedComponent) *failedComponent = @"wrapper"; + OSStatus status = DYValidateBundle(wrapperURL, DYWrapperIdentifier, kSecCSDefaultFlags); + if (status != errSecSuccess) return status; + + if (failedComponent) *failedComponent = @"service"; + NSURL *serviceURL = [wrapperURL URLByAppendingPathComponent:DYPluginRelativePath isDirectory:YES]; + status = DYValidateBundle(serviceURL, DYServiceIdentifier, kSecCSCheckNestedCode); + if (status != errSecSuccess) return status; + + // A separately signed older service with the same identity must not be mixed into this build. + NSDictionary *wrapper = [NSDictionary dictionaryWithContentsOfURL:[wrapperURL URLByAppendingPathComponent:@"Contents/Info.plist"]]; + NSDictionary *service = [NSDictionary dictionaryWithContentsOfURL:[serviceURL URLByAppendingPathComponent:@"Contents/Info.plist"]]; + if (failedComponent) *failedComponent = @"component-build"; + if (![wrapper[@"CFBundleVersion"] isEqual:service[@"CFBundleVersion"]] || + ![wrapper[@"CFBundleShortVersionString"] isEqual:service[@"CFBundleShortVersionString"]]) return errSecCSReqFailed; + + if (failedComponent) *failedComponent = nil; + return errSecSuccess; +} + +OSStatus DYValidateRunningInstallation(DYCodeRole role, NSString **failedComponent) { + BOOL isService = role == DYCodeRoleService; + if (failedComponent) *failedComponent = isService ? @"running-service" : @"running-wrapper"; + OSStatus status = DYValidateRunningCode(isService ? DYServiceIdentifier : DYWrapperIdentifier); + if (status != errSecSuccess) return status; + + NSURL *bundleURL = NSBundle.mainBundle.bundleURL.URLByResolvingSymlinksInPath; + NSURL *wrapperURL = bundleURL; + if (isService) { + // The service must be embedded in the wrapper being verified. + for (NSInteger level = 0; level < 3; level++) wrapperURL = wrapperURL.URLByDeletingLastPathComponent; + NSURL *expected = [wrapperURL URLByAppendingPathComponent:DYPluginRelativePath isDirectory:YES]; + if (failedComponent) *failedComponent = @"service-location"; + if (![wrapperURL.pathExtension isEqualToString:@"app"] || + ![bundleURL.path isEqualToString:expected.path]) return errSecCSBadBundleFormat; + } + return DYValidateSignedInstallation(wrapperURL, failedComponent); +} diff --git a/大鱼调色/Wrapper Application/AppDelegate.m b/大鱼调色/Wrapper Application/AppDelegate.m index 6f96321..9f9a388 100644 --- a/大鱼调色/Wrapper Application/AppDelegate.m +++ b/大鱼调色/Wrapper Application/AppDelegate.m @@ -1,9 +1,16 @@ #import "AppDelegate.h" #import "DYBetaUpdater.h" #import "../Shared/DYBetaDiagnostics.h" +#import "../Shared/DYCodeIntegrity.h" static NSString *const DYPluginID = @"com.dayu.color.XPC"; static NSString *const DYReleaseAddress = @"https://dayu.media"; +static dispatch_queue_t DYPluginRegistrationQueue(void) { + static dispatch_queue_t queue; + static dispatch_once_t once; + dispatch_once(&once, ^{ queue = dispatch_queue_create("com.dayu.color.registration", DISPATCH_QUEUE_SERIAL); }); + return queue; +} static NSColor *DYColor(CGFloat r, CGFloat g, CGFloat b) { return [NSColor colorWithSRGBRed:r green:g blue:b alpha:1]; } static NSColor *DYBlue(void) { return DYColor(.36,.65,1); } static NSColor *DYGreen(void) { return DYColor(.26,.86,.53); } @@ -125,6 +132,7 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe @property(assign) NSProgressIndicator *updateProgress; @property(retain) NSTimer *updateProgressTimer; @property BOOL updateCheckDone; +@property BOOL integrityRejected; @end @implementation AppDelegate @@ -278,32 +286,84 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe } return NO; } +- (BOOL)registry:(NSDictionary *)query listsExactPath:(NSString *)path { + NSString *suffix = [@"\t" stringByAppendingString:path]; + for (NSString *line in [query[@"output"] componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) { + if ([line hasSuffix:suffix]) return YES; + } + return NO; +} +- (NSString *)removeRejectedPluginRegistration:(NSString *)path { + NSArray *arguments = @[@"-m",@"-A",@"-D",@"-v",@"-i",DYPluginID]; + NSDictionary *before = [self runPluginKit:arguments]; + if ([before[@"code"] intValue] != 0) return @"query-failed"; + if (![self registry:before listsExactPath:path]) return @"not-registered"; + if (![path.stringByStandardizingPath isEqualToString:path.stringByResolvingSymlinksInPath]) return @"skipped-symlink"; + [self runPluginKit:@[@"-r",path]]; + NSDictionary *after = [self runPluginKit:arguments]; + if ([after[@"code"] intValue] != 0 || [self registry:after listsExactPath:path]) return @"removal-unverified"; + return @"removed"; +} +- (void)rejectModifiedInstallation:(NSDictionary *)results { + if (self.integrityRejected || self.terminating) return; + self.integrityRejected = YES; + [self.updater stopForIntegrityFailure]; + [self finishRegistration:NO details:DYIntegrityRecoveryMessage results:results]; + self.retryButton.enabled = NO; + self.exitDetail.stringValue = @"此副本的自动更新已停用。请安装原始安装包后重新打开。"; + + NSString *path = [NSBundle.mainBundle.bundlePath stringByAppendingPathComponent:DYPluginRelativePath]; + dispatch_async(DYPluginRegistrationQueue(), ^{ + @autoreleasepool { + NSString *removal = [self removeRejectedPluginRegistration:path]; + dispatch_async(dispatch_get_main_queue(), ^{ + self.diagnostics[@"registrationRevocation"] = removal; + [self writeDiagnostics]; + }); + } + }); +} - (void)checkRegistration:(id)sender { + if (self.integrityRejected) return; if (self.diagnostics && (self.registrationState == DYChecking || self.registrationState == DYRegistering)) return; [self.exitTimer invalidate]; self.exitTimer = nil; self.registrationState = DYChecking; self.retryButton.enabled = NO; self.retryButton.title = @"检查中…"; self.statusTitle.stringValue = @"正在检查插件…"; self.statusTitle.textColor = NSColor.whiteColor; self.statusDetail.stringValue = @"正在检查本机插件登记,随后自动提交注册。"; self.progress.indeterminate = YES; [self.progress startAnimation:nil]; - NSString *path = [NSBundle.mainBundle.bundlePath stringByAppendingPathComponent:@"Contents/PlugIns/大鱼调色 XPC Service.pluginkit"]; + NSString *path = [NSBundle.mainBundle.bundlePath stringByAppendingPathComponent:DYPluginRelativePath]; self.diagnostics = [NSMutableDictionary dictionaryWithDictionary:@{ - @"bundleID":NSBundle.mainBundle.bundleIdentifier,@"version":[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"], - @"build":[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"],@"executable":NSBundle.mainBundle.executablePath, + @"bundleID":NSBundle.mainBundle.bundleIdentifier ?: @"",@"version":[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"] ?: @"", + @"build":[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"] ?: @"",@"executable":NSBundle.mainBundle.executablePath ?: @"", @"pid":@(NSProcessInfo.processInfo.processIdentifier),@"plugin":path,@"status":@"checking"}]; - dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED,0), ^{ + dispatch_async(DYPluginRegistrationQueue(), ^{ @autoreleasepool { + NSString *failedComponent = nil; + OSStatus status = DYValidateRunningInstallation(DYCodeRoleWrapper, &failedComponent); + if (status != errSecSuccess) { + NSDictionary *results = @{@"integrity":@"rejected", @"integrityComponent":failedComponent, + @"integrityOSStatus":@(status)}; + dispatch_async(dispatch_get_main_queue(), ^{ + [self rejectModifiedInstallation:results]; + }); + return; + } NSBundle *plugin = [NSBundle bundleWithPath:path]; NSDictionary *attributes = [plugin objectForInfoDictionaryKey:@"PlugInKit"][@"Attributes"]; BOOL validComponent = [plugin.bundleIdentifier isEqualToString:DYPluginID] && [[plugin objectForInfoDictionaryKey:@"CFBundleVersion"] isEqual:[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"]] && [attributes[@"com.apple.protocol"] isEqual:@"FxPlug"] && [attributes[@"com.apple.version"] isEqual:@"1.1"]; if (!validComponent) { - dispatch_async(dispatch_get_main_queue(), ^{ [self finishRegistration:NO details:@"未找到完整的插件组件。请从发布地址重新安装大鱼调色。" results:@{}]; }); return; + dispatch_async(dispatch_get_main_queue(), ^{ + if (!self.integrityRejected) + [self finishRegistration:NO details:@"未找到完整的插件组件。请从发布地址重新安装大鱼调色。" results:@{}]; + }); return; } // The stand-alone wrapper can inspect the registry directly. Registration // and actual host rendering remain separate states; the user confirms FCP. NSDictionary *before = [self runPluginKit:@[@"-m",@"-v",@"-i",DYPluginID]]; dispatch_async(dispatch_get_main_queue(), ^{ + if (self.integrityRejected) return; self.registrationState = DYRegistering; self.statusTitle.stringValue = @"正在注册插件…"; self.statusDetail.stringValue = @"正在向系统提交插件注册,并核对当前安装位置。"; }); @@ -318,10 +378,12 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe NSString *message = registered ? @"已确认当前插件登记。请在 Final Cut Pro 中实际应用并确认效果正常;若宿主已打开,请保存后重新打开。" : @"插件注册尚未完成。请点击“重新检查”,或重新安装后再试。窗口将保持打开。"; - NSDictionary *results = @{@"before":before,@"submission":add,@"after":after ?: @{},@"registered":@(registered), + NSDictionary *results = @{@"integrity":@"verified",@"before":before,@"submission":add,@"after":after ?: @{},@"registered":@(registered), @"discoveryVerified":@(registered),@"submissionAccepted":@(submissionAccepted),@"hostVerification":@"awaiting-user-confirmation", @"confirmationMethod":registered ? @"exact-path-discovery" : @"unconfirmed"}; - dispatch_async(dispatch_get_main_queue(), ^{ [self finishRegistration:registered details:message results:results]; }); + dispatch_async(dispatch_get_main_queue(), ^{ + if (!self.integrityRejected) [self finishRegistration:registered details:message results:results]; + }); } }); } @@ -330,7 +392,7 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe self.registrationState = success ? DYReady : DYFailed; [self.progress stopAnimation:nil]; self.progress.indeterminate = NO; self.progress.doubleValue = success ? 100 : 0; self.registrationCard.tint = success ? DYGreen() : DYColor(1,.67,.30); [self.registrationCard setNeedsDisplay:YES]; - self.statusTitle.stringValue = success ? @"✓ 插件注册成功" : @"需要重新检查"; + self.statusTitle.stringValue = success ? @"✓ 插件注册成功" : (self.integrityRejected ? @"安装完整性验证失败" : @"需要重新检查"); self.statusTitle.textColor = success ? DYGreen() : DYColor(1,.75,.4); self.statusDetail.stringValue = details; self.retryButton.title = @"重新检查"; self.retryButton.enabled = YES; self.confirmationButton.enabled = success; @@ -352,12 +414,14 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe - (void)updateChanged:(NSDictionary *)state { if(self.terminating)return; NSString *phase=state[@"phase"]; + BOOL rejected = [phase isEqual:@"integrity_rejected"]; + if (rejected) [self rejectModifiedInstallation:@{@"integrity":@"rejected"}]; BOOL busy=[@[@"checking",@"downloading",@"validating"]containsObject:phase]; BOOL available=[@[@"available",@"ready",@"host_wait",@"installer"]containsObject:phase]; if(![phase isEqual:@"checking"]){self.updateCheckDone=YES;if(available)[self keepIntroduction:nil];} self.updateTitle.stringValue=[phase isEqual:@"available"]?state[@"message"]:@"公测更新"; self.updateDetail.stringValue=state[@"message"]?:@""; - self.updateCheckButton.enabled=!busy; + self.updateCheckButton.enabled=!busy && !rejected; self.updateInstallButton.enabled=[@[@"available",@"ready",@"host_wait",@"installer"]containsObject:phase]; self.updateInstallButton.title=[phase isEqual:@"available"]?@"下载更新":@"安装更新"; self.updateCancelButton.hidden=![phase isEqual:@"downloading"]; diff --git a/大鱼调色/Wrapper Application/DYBetaUpdater.h b/大鱼调色/Wrapper Application/DYBetaUpdater.h index dc7f99e..5e6bdb0 100644 --- a/大鱼调色/Wrapper Application/DYBetaUpdater.h +++ b/大鱼调色/Wrapper Application/DYBetaUpdater.h @@ -6,6 +6,7 @@ - (void)check; - (void)download; - (void)install; +- (void)stopForIntegrityFailure; - (void)cancel; + (BOOL)validateManifest:(NSDictionary *)manifest error:(NSError **)error; + (BOOL)validatePackage:(NSURL *)package manifest:(NSDictionary *)manifest error:(NSError **)error; diff --git a/大鱼调色/Wrapper Application/DYBetaUpdater.mm b/大鱼调色/Wrapper Application/DYBetaUpdater.mm index 1eea0f0..685f746 100644 --- a/大鱼调色/Wrapper Application/DYBetaUpdater.mm +++ b/大鱼调色/Wrapper Application/DYBetaUpdater.mm @@ -1,5 +1,6 @@ #import "DYBetaUpdater.h" #import "../Shared/DYBetaDiagnostics.h" +#import "../Shared/DYCodeIntegrity.h" #import #import #include @@ -31,6 +32,7 @@ static NSString *command(NSString *path,NSArray *arguments,NSError **error) { NSURL *_package; NSDictionary *_state,*_manifest; std::atomic_uint _generation; + BOOL _integrityRejected; } - (void)emit:(NSString *)phase message:(NSString *)message; @end @@ -57,6 +59,21 @@ static NSString *command(NSString *path,NSArray *arguments,NSError **error) { if(!NSThread.isMainThread){dispatch_async(dispatch_get_main_queue(),^{[self emit:phase message:message];});return;} [_state release];_state=[@{@"phase":phase,@"message":message?:@"",@"version":_manifest[@"version"]?:@""}copy];if(self.changed)self.changed(_state); } +- (BOOL)requireOfficialInstallation { + if (_integrityRejected) return NO; + if (DYValidateRunningInstallation(DYCodeRoleWrapper, NULL) == errSecSuccess) return YES; + [self stopForIntegrityFailure]; + return NO; +} +- (void)stopForIntegrityFailure { + if (_integrityRejected) return; + _integrityRejected = YES; + ++_generation; + [_task cancel]; + [_manifest release]; _manifest = nil; + [_package release]; _package = nil; + [self emit:@"integrity_rejected" message:DYIntegrityRecoveryMessage]; +} + (BOOL)validateManifest:(NSDictionary *)manifest error:(NSError **)error { if(![manifest isKindOfClass:NSDictionary.class]){if(error)*error=DYUpdateError(@"公测更新清单格式错误。");return NO;} id build=manifest[@"build"],size=manifest[@"size"]; @@ -90,13 +107,12 @@ static NSString *command(NSString *path,NSArray *arguments,NSError **error) { } if(apps.count!=1){if(error)*error=DYUpdateError(@"更新包必须包含一个完整的大鱼调色 APP。");return NO;} NSURL *app=apps.firstObject;NSDictionary *info=[NSDictionary dictionaryWithContentsOfURL:[app URLByAppendingPathComponent:@"Contents/Info.plist"]]; - NSDictionary *plugin=[NSDictionary dictionaryWithContentsOfURL:[app URLByAppendingPathComponent:@"Contents/PlugIns/大鱼调色 XPC Service.pluginkit/Contents/Info.plist"]]; + NSURL *service=[app URLByAppendingPathComponent:DYPluginRelativePath isDirectory:YES]; + NSDictionary *plugin=[NSDictionary dictionaryWithContentsOfURL:[service URLByAppendingPathComponent:@"Contents/Info.plist"]]; if(![info[@"CFBundleIdentifier"]isEqual:@"com.dayu.color"]||![plugin[@"CFBundleIdentifier"]isEqual:@"com.dayu.color.XPC"]|| [info[@"CFBundleVersion"]integerValue]!=[manifest[@"build"]integerValue]||[plugin[@"CFBundleVersion"]integerValue]!=[manifest[@"build"]integerValue]|| ![info[@"CFBundleShortVersionString"]isEqual:manifest[@"version"]]){if(error)*error=DYUpdateError(@"更新包产品或版本与清单不一致。");return NO;} - if(!command(@"/usr/bin/codesign",@[@"--verify",@"--deep",@"--strict",app.path],error))return NO; - NSString *identity=command(@"/usr/bin/codesign",@[@"-dvvv",app.path],error); - if(![identity containsString:@"TeamIdentifier=B3W25FX5H5"]){if(error)*error=DYUpdateError(@"包内 APP 签名团队不匹配。");return NO;} + if(DYValidateSignedInstallation(app,NULL)!=errSecSuccess){if(error)*error=DYUpdateError(@"更新包内的 APP 或插件未通过官方签名验证。");return NO;} // Product PKGs install the wrapper at its fixed FxPlug location and carry templates. BOOL appTarget=NO,templates=NO; for(NSURL *url in [NSFileManager.defaultManager enumeratorAtURL:inspection includingPropertiesForKeys:nil options:0 errorHandler:nil]){ @@ -116,6 +132,7 @@ static NSString *command(NSString *path,NSArray *arguments,NSError **error) { } - (void)check { NSString *phase=_state[@"phase"];if([@[@"checking",@"downloading",@"validating"]containsObject:phase])return; + if (![self requireOfficialInstallation]) return; unsigned generation=++_generation;[self emit:@"checking" message:@"正在检查公测更新…"]; NSString *url=[NSString stringWithFormat:@"https://dayu.media/wp-json/dayu-color/v1/update?bundle_id=com.dayu.color&channel=beta¤t_build=%@",([NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"]?:@"0")]; NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:6]; @@ -137,6 +154,7 @@ static NSString *command(NSString *path,NSArray *arguments,NSError **error) { } - (void)download { if(![_state[@"phase"]isEqual:@"available"])return;NSError *error=nil; + if (![self requireOfficialInstallation]) return; if(![DYBetaUpdater validateManifest:_manifest error:&error]){[self emit:@"failed" message:error.localizedDescription];return;} if([_manifest[@"build"]integerValue]<=[[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"]integerValue])return; unsigned generation=++_generation;NSDictionary *manifest=[[_manifest copy]autorelease];[self emit:@"downloading" message:@"正在下载公测更新,可随时取消。"]; @@ -147,7 +165,9 @@ static NSString *command(NSString *path,NSArray *arguments,NSError **error) { if(!error&&[(NSHTTPURLResponse*)response statusCode]==200&&DYBetaAllowedURL(response.URL,YES)){ [NSFileManager.defaultManager removeItemAtURL:destination error:nil]; if([NSFileManager.defaultManager moveItemAtURL:temporary toURL:destination error:&error]){ - [self emit:@"validating" message:@"正在验证完整性、签名、公证和插件版本…"]; + dispatch_async(dispatch_get_main_queue(), ^{ + if(generation==self->_generation.load()) [self emit:@"validating" message:@"正在验证完整性、签名、公证和插件版本…"]; + }); BOOL valid=[DYBetaUpdater validatePackage:destination manifest:manifest error:&error]; if(!valid&&!error)error=DYUpdateError(@"更新包未通过验证。"); } @@ -163,15 +183,20 @@ static NSString *command(NSString *path,NSArray *arguments,NSError **error) { } - (void)install { if(![@[@"ready",@"host_wait",@"installer"]containsObject:_state[@"phase"]])return; + if (![self requireOfficialInstallation]) return; for(NSString *ID in @[@"com.apple.FinalCut",@"com.apple.FinalCutApp",@"com.apple.motionapp",@"com.apple.motionappApp"]) if([NSRunningApplication runningApplicationsWithBundleIdentifier:ID].count){[self emit:@"host_wait" message:@"请先保存并正常退出 FCP / Motion,再点击安装更新。不会强制退出宿主。"]; DYBetaEvent(@"update_installer",@{@"status":@"waiting_for_host"});return;} - if(_package&&[NSWorkspace.sharedWorkspace openURL:_package]){ + if (!_package || ![digest(_package) isEqualToString:_manifest[@"sha256"]]) { + [self emit:@"failed" message:@"更新包已更改或不可读。请重新检查并下载更新。"]; + return; + } + if([NSWorkspace.sharedWorkspace openURL:_package]){ [NSUserDefaults.standardUserDefaults setObject:_manifest[@"build"] forKey:@"betaPendingUpdateBuild"];[self emit:@"installer" message:@"已打开系统安装程序,请按提示授权并完成安装。"]; DYBetaEvent(@"update_installer",@{@"status":@"system_installer_opened"});} else [self emit:@"failed" message:@"无法打开系统安装程序,请重试。"]; } -- (void)cancel {++_generation;[_task cancel];BOOL newer=[_manifest[@"build"]integerValue]>[[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"]integerValue];[self emit:newer?@"available":@"idle" message:@"已取消,不影响当前插件。"];} +- (void)cancel {if(_integrityRejected)return;++_generation;[_task cancel];BOOL newer=[_manifest[@"build"]integerValue]>[[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"]integerValue];[self emit:newer?@"available":@"idle" message:@"已取消,不影响当前插件。"];} - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completion { BOOL download=[task isKindOfClass:NSURLSessionDownloadTask.class];completion(DYBetaAllowedURL(request.URL,download)?request:nil); } diff --git a/大鱼调色/Wrapper Application/Info.plist b/大鱼调色/Wrapper Application/Info.plist index 67ccaaf..bacc763 100644 --- a/大鱼调色/Wrapper Application/Info.plist +++ b/大鱼调色/Wrapper Application/Info.plist @@ -17,9 +17,9 @@ CFBundlePackageType APPL CFBundleShortVersionString - 1.13.1 + 1.13.2 CFBundleVersion - 85 + 86 LSMinimumSystemVersion $(MACOSX_DEPLOYMENT_TARGET) NSHumanReadableCopyright