From 0e00237e44b2d8b7c7ea382112cddfac62140606 Mon Sep 17 00:00:00 2001 From: Russell Hancox Date: Thu, 10 Mar 2016 15:53:06 -0500 Subject: [PATCH] Project: Add clang-format file, apply most of the fixes it suggested --- .clang-format | 22 +++ Source/SantaGUI/SNTAppDelegate.m | 12 +- Source/SantaGUI/SNTMessageWindow.m | 8 +- Source/SantaGUI/SNTNotificationManager.m | 3 +- Source/common/SNTCommonEnums.h | 26 ++-- Source/common/SNTConfigurator.h | 2 +- Source/common/SNTConfigurator.m | 64 ++++---- Source/common/SNTFileInfo.m | 30 ++-- Source/common/SNTFileWatcher.m | 46 +++--- Source/common/SNTLogging.m | 42 ++++-- Source/common/SNTRule.m | 2 +- Source/common/SNTStoredEvent.h | 1 - Source/common/SNTStoredEvent.m | 4 +- Source/common/SNTXPCConnection.m | 9 +- Source/santa-driver/SantaDecisionManager.cc | 17 ++- Source/santa-driver/SantaDecisionManager.h | 3 +- Source/santa-driver/SantaDriver.h | 2 +- Source/santa-driver/SantaDriverClient.cc | 2 +- Source/santa-driver/SantaDriverClient.h | 4 +- Source/santactl/SNTCommandController.h | 2 +- Source/santactl/SNTCommandController.m | 8 +- Source/santactl/fileinfo/SNTCommandFileInfo.m | 33 +++-- .../flushcache/SNTCommandFlushCache.m | 14 +- Source/santactl/main.m | 2 +- Source/santactl/rule/SNTCommandRule.m | 21 ++- Source/santactl/status/SNTCommandStatus.m | 81 +++++----- .../sync/SNTAuthenticatingURLSession.m | 35 +++-- Source/santactl/sync/SNTCommandSync.m | 10 +- .../santactl/sync/SNTCommandSyncConstants.h | 140 +++++++++--------- .../santactl/sync/SNTCommandSyncConstants.m | 140 +++++++++--------- .../santactl/sync/SNTCommandSyncEventUpload.m | 92 ++++++------ .../santactl/sync/SNTCommandSyncLogUpload.m | 2 +- .../santactl/sync/SNTCommandSyncPreflight.m | 66 ++++----- .../sync/SNTCommandSyncRuleDownload.m | 83 +++++------ Source/santactl/sync/SNTDERDecoder.m | 36 ++--- Source/santactl/version/SNTCommandVersion.m | 15 +- Source/santad/SNTApplication.m | 13 +- Source/santad/SNTDaemonControlController.m | 20 +-- Source/santad/SNTDatabaseController.m | 36 +++-- Source/santad/SNTDatabaseTable.m | 10 +- Source/santad/SNTDriverManager.m | 5 +- Source/santad/SNTEventLog.h | 1 - Source/santad/SNTEventLog.m | 72 ++++++--- Source/santad/SNTEventTable.m | 51 +++---- Source/santad/SNTExecutionController.m | 5 +- Source/santad/SNTRuleTable.m | 103 +++++++------ Source/santad/main.m | 2 +- Tests/KernelTests/main.m | 10 +- Tests/LogicTests/SNTDERDecoderTest.m | 4 +- Tests/LogicTests/SNTEventTableTest.m | 14 +- 50 files changed, 745 insertions(+), 680 deletions(-) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 000000000..aad86da4a --- /dev/null +++ b/.clang-format @@ -0,0 +1,22 @@ +BasedOnStyle: Google +Language: Cpp +Standard: Cpp11 + +# Disable ColumnLimit because it causes some very weird line breaks. +# For ObjC the limit is 100 +# For Cpp the limit is 80 +ColumnLimit: 0 + +# Allow short case statements to be on a single line +AllowShortCaseLabelsOnASingleLine: true + +# Ban short loops and functions on a single line +AllowShortLoopsOnASingleLine: false +AllowShortFunctionsOnASingleLine: false + +# Allow spaces in NSArray/NSDictionary literals @[ and @{ +SpacesInContainerLiterals: true + +# For pointers, always put the * next to the variable name. +DerivePointerAlignment: false +PointerAlignment: Right diff --git a/Source/SantaGUI/SNTAppDelegate.m b/Source/SantaGUI/SNTAppDelegate.m index 243007ff8..c859f1917 100644 --- a/Source/SantaGUI/SNTAppDelegate.m +++ b/Source/SantaGUI/SNTAppDelegate.m @@ -36,7 +36,7 @@ - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { self.configFileWatcher = [[SNTFileWatcher alloc] initWithFilePath:kDefaultConfigFilePath handler:^{ - [[SNTConfigurator configurator] reloadConfigData]; + [[SNTConfigurator configurator] reloadConfigData]; }]; self.notificationManager = [[SNTNotificationManager alloc] init]; @@ -47,16 +47,16 @@ - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *note) { - self.listener.invalidationHandler = nil; - self.listener.rejectedHandler = nil; - [self.listener invalidate]; - self.listener = nil; + self.listener.invalidationHandler = nil; + self.listener.rejectedHandler = nil; + [self.listener invalidate]; + self.listener = nil; }]; [workspaceNotifications addObserverForName:NSWorkspaceSessionDidBecomeActiveNotification object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *note) { - [self attemptReconnection]; + [self attemptReconnection]; }]; [self createConnection]; diff --git a/Source/SantaGUI/SNTMessageWindow.m b/Source/SantaGUI/SNTMessageWindow.m index ba3a53247..37aea13bf 100644 --- a/Source/SantaGUI/SNTMessageWindow.m +++ b/Source/SantaGUI/SNTMessageWindow.m @@ -31,7 +31,7 @@ - (IBAction)fadeIn:(id)sender { [NSAnimationContext beginGrouping]; [[NSAnimationContext currentContext] setDuration:0.15f]; [[NSAnimationContext currentContext] setCompletionHandler:^{ - [NSApp activateIgnoringOtherApps:YES]; + [NSApp activateIgnoringOtherApps:YES]; }]; [[self animator] setAlphaValue:1.f]; [NSAnimationContext endGrouping]; @@ -43,9 +43,9 @@ - (IBAction)fadeOut:(id)sender { [NSAnimationContext beginGrouping]; [[NSAnimationContext currentContext] setDuration:0.15f]; [[NSAnimationContext currentContext] setCompletionHandler:^{ - [weakSelf.windowController windowWillClose:sender]; - [weakSelf orderOut:sender]; - [weakSelf setAlphaValue:1.f]; + [weakSelf.windowController windowWillClose:sender]; + [weakSelf orderOut:sender]; + [weakSelf setAlphaValue:1.f]; }]; [[self animator] setAlphaValue:0.f]; [NSAnimationContext endGrouping]; diff --git a/Source/SantaGUI/SNTNotificationManager.m b/Source/SantaGUI/SNTNotificationManager.m index 9cbdd6b94..17d117222 100644 --- a/Source/SantaGUI/SNTNotificationManager.m +++ b/Source/SantaGUI/SNTNotificationManager.m @@ -67,7 +67,8 @@ - (void)postBlockNotification:(SNTStoredEvent *)event withCustomMessage:(NSStrin // Notifications arrive on a background thread but UI updates must happen on the main thread. // This includes making windows. [self performSelectorOnMainThread:@selector(postBlockNotificationMainThread:) - withObject:@{ @"event": event, @"custommsg": message } + withObject:@{ @"event" : event, + @"custommsg" : message } waitUntilDone:NO]; } diff --git a/Source/common/SNTCommonEnums.h b/Source/common/SNTCommonEnums.h index 61075c816..d898cba71 100644 --- a/Source/common/SNTCommonEnums.h +++ b/Source/common/SNTCommonEnums.h @@ -23,8 +23,8 @@ typedef enum { RULETYPE_UNKNOWN, - RULETYPE_BINARY = 1, - RULETYPE_CERT = 2, + RULETYPE_BINARY = 1, + RULETYPE_CERT = 2, RULETYPE_MAX } santa_ruletype_t; @@ -32,10 +32,10 @@ typedef enum { typedef enum { RULESTATE_UNKNOWN, - RULESTATE_WHITELIST = 1, - RULESTATE_BLACKLIST = 2, + RULESTATE_WHITELIST = 1, + RULESTATE_BLACKLIST = 2, RULESTATE_SILENT_BLACKLIST = 3, - RULESTATE_REMOVE = 4, + RULESTATE_REMOVE = 4, RULESTATE_MAX } santa_rulestate_t; @@ -43,7 +43,7 @@ typedef enum { typedef enum { CLIENTMODE_UNKNOWN, - CLIENTMODE_MONITOR = 1, + CLIENTMODE_MONITOR = 1, CLIENTMODE_LOCKDOWN = 2, CLIENTMODE_MAX @@ -52,17 +52,17 @@ typedef enum { typedef enum { EVENTSTATE_UNKNOWN, - EVENTSTATE_ALLOW_UNKNOWN = 1, - EVENTSTATE_ALLOW_BINARY = 2, + EVENTSTATE_ALLOW_UNKNOWN = 1, + EVENTSTATE_ALLOW_BINARY = 2, EVENTSTATE_ALLOW_CERTIFICATE = 3, - EVENTSTATE_ALLOW_SCOPE = 4, + EVENTSTATE_ALLOW_SCOPE = 4, - EVENTSTATE_BLOCK_UNKNOWN = 5, - EVENTSTATE_BLOCK_BINARY = 6, + EVENTSTATE_BLOCK_UNKNOWN = 5, + EVENTSTATE_BLOCK_BINARY = 6, EVENTSTATE_BLOCK_CERTIFICATE = 7, - EVENTSTATE_BLOCK_SCOPE = 8, + EVENTSTATE_BLOCK_SCOPE = 8, - EVENTSTATE_RELATED_BINARY = 9, + EVENTSTATE_RELATED_BINARY = 9, EVENTSTATE_MAX } santa_eventstate_t; diff --git a/Source/common/SNTConfigurator.h b/Source/common/SNTConfigurator.h index ee08a4864..8229e9000 100644 --- a/Source/common/SNTConfigurator.h +++ b/Source/common/SNTConfigurator.h @@ -21,7 +21,7 @@ @interface SNTConfigurator : NSObject /// Default config file path -extern NSString * const kDefaultConfigFilePath; +extern NSString *const kDefaultConfigFilePath; #pragma mark - Daemon Settings diff --git a/Source/common/SNTConfigurator.m b/Source/common/SNTConfigurator.m index b0fbce8fd..eef963968 100644 --- a/Source/common/SNTConfigurator.m +++ b/Source/common/SNTConfigurator.m @@ -33,39 +33,39 @@ @interface SNTConfigurator () @implementation SNTConfigurator /// The hard-coded path to the config file -NSString * const kDefaultConfigFilePath = @"/var/db/santa/config.plist"; +NSString *const kDefaultConfigFilePath = @"/var/db/santa/config.plist"; /// The keys in the config file -static NSString * const kClientModeKey = @"ClientMode"; -static NSString * const kFileChangesRegexKey = @"FileChangesRegex"; -static NSString * const kWhitelistRegexKey = @"WhitelistRegex"; -static NSString * const kBlacklistRegexKey = @"BlacklistRegex"; -static NSString * const kEnablePageZeroProtectionKey = @"EnablePageZeroProtection"; - -static NSString * const kMoreInfoURLKey = @"MoreInfoURL"; -static NSString * const kEventDetailURLKey = @"EventDetailURL"; -static NSString * const kEventDetailTextKey = @"EventDetailText"; -static NSString * const kUnknownBlockMessage = @"UnknownBlockMessage"; -static NSString * const kBannedBlockMessage = @"BannedBlockMessage"; - -static NSString * const kSyncBaseURLKey = @"SyncBaseURL"; -static NSString * const kSyncLastSuccess = @"SyncLastSuccess"; -static NSString * const kSyncCleanRequired = @"SyncCleanRequired"; -static NSString * const kClientAuthCertificateFileKey = @"ClientAuthCertificateFile"; -static NSString * const kClientAuthCertificatePasswordKey = @"ClientAuthCertificatePassword"; -static NSString * const kClientAuthCertificateCNKey = @"ClientAuthCertificateCN"; -static NSString * const kClientAuthCertificateIssuerKey = @"ClientAuthCertificateIssuerCN"; -static NSString * const kServerAuthRootsDataKey = @"ServerAuthRootsData"; -static NSString * const kServerAuthRootsFileKey = @"ServerAuthRootsFile"; - -static NSString * const kMachineOwnerKey = @"MachineOwner"; -static NSString * const kMachineIDKey = @"MachineID"; - -static NSString * const kMachineOwnerPlistFileKey = @"MachineOwnerPlist"; -static NSString * const kMachineOwnerPlistKeyKey = @"MachineOwnerKey"; - -static NSString * const kMachineIDPlistFileKey = @"MachineIDPlist"; -static NSString * const kMachineIDPlistKeyKey = @"MachineIDKey"; +static NSString *const kClientModeKey = @"ClientMode"; +static NSString *const kFileChangesRegexKey = @"FileChangesRegex"; +static NSString *const kWhitelistRegexKey = @"WhitelistRegex"; +static NSString *const kBlacklistRegexKey = @"BlacklistRegex"; +static NSString *const kEnablePageZeroProtectionKey = @"EnablePageZeroProtection"; + +static NSString *const kMoreInfoURLKey = @"MoreInfoURL"; +static NSString *const kEventDetailURLKey = @"EventDetailURL"; +static NSString *const kEventDetailTextKey = @"EventDetailText"; +static NSString *const kUnknownBlockMessage = @"UnknownBlockMessage"; +static NSString *const kBannedBlockMessage = @"BannedBlockMessage"; + +static NSString *const kSyncBaseURLKey = @"SyncBaseURL"; +static NSString *const kSyncLastSuccess = @"SyncLastSuccess"; +static NSString *const kSyncCleanRequired = @"SyncCleanRequired"; +static NSString *const kClientAuthCertificateFileKey = @"ClientAuthCertificateFile"; +static NSString *const kClientAuthCertificatePasswordKey = @"ClientAuthCertificatePassword"; +static NSString *const kClientAuthCertificateCNKey = @"ClientAuthCertificateCN"; +static NSString *const kClientAuthCertificateIssuerKey = @"ClientAuthCertificateIssuerCN"; +static NSString *const kServerAuthRootsDataKey = @"ServerAuthRootsData"; +static NSString *const kServerAuthRootsFileKey = @"ServerAuthRootsFile"; + +static NSString *const kMachineOwnerKey = @"MachineOwner"; +static NSString *const kMachineIDKey = @"MachineID"; + +static NSString *const kMachineOwnerPlistFileKey = @"MachineOwnerPlist"; +static NSString *const kMachineOwnerPlistKeyKey = @"MachineOwnerKey"; + +static NSString *const kMachineIDPlistFileKey = @"MachineIDPlist"; +static NSString *const kMachineIDPlistKeyKey = @"MachineIDKey"; - (instancetype)initWithFilePath:(NSString *)filePath { self = [super init]; @@ -82,7 +82,7 @@ + (instancetype)configurator { static SNTConfigurator *sharedConfigurator = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - sharedConfigurator = [[SNTConfigurator alloc] initWithFilePath:kDefaultConfigFilePath]; + sharedConfigurator = [[SNTConfigurator alloc] initWithFilePath:kDefaultConfigFilePath]; }); return sharedConfigurator; } diff --git a/Source/common/SNTFileInfo.m b/Source/common/SNTFileInfo.m index 59a92e121..2d0ae6b1f 100644 --- a/Source/common/SNTFileInfo.m +++ b/Source/common/SNTFileInfo.m @@ -69,7 +69,7 @@ - (instancetype)initWithPath:(NSString *)path error:(NSError **)error { if (path) errStr = [@"Unable to resolve path: " stringByAppendingString:path]; *error = [NSError errorWithDomain:@"com.google.santa.fileinfo" code:260 - userInfo:@{ NSLocalizedDescriptionKey: errStr }]; + userInfo:@{NSLocalizedDescriptionKey : errStr}]; } return nil; } @@ -97,7 +97,7 @@ - (instancetype)initWithPath:(NSString *)path { return [self initWithPath:path error:NULL]; } -# pragma mark Hashing +#pragma mark Hashing - (NSString *)SHA1 { const int chunkSize = 4096; @@ -126,7 +126,7 @@ - (NSString *)SHA1 { CC_SHA1_Final(sha1, &c); NSMutableString *buf = [[NSMutableString alloc] initWithCapacity:CC_SHA1_DIGEST_LENGTH * 2]; - for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) { + for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; ++i) { [buf appendFormat:@"%02x", (unsigned char)sha1[i]]; } @@ -160,20 +160,19 @@ - (NSString *)SHA256 { CC_SHA256_Final(sha256, &c); NSMutableString *buf = [[NSMutableString alloc] initWithCapacity:CC_SHA256_DIGEST_LENGTH * 2]; - for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) { + for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; ++i) { [buf appendFormat:@"%02x", (unsigned char)sha256[i]]; } - + return buf; } -# pragma mark File Type Info +#pragma mark File Type Info - (NSArray *)architectures { return [self.machHeaders allKeys]; } - - (BOOL)isExecutable { struct mach_header *mach_header = [self firstMachHeader]; if (mach_header && mach_header->filetype == MH_EXECUTE) return YES; @@ -371,7 +370,7 @@ - (NSDictionary *)machHeaders { NSMutableData *fatArchs = [[self safeSubdataWithRange:range] mutableCopy]; if (fatArchs) { struct fat_arch *fat_arch = (struct fat_arch *)[fatArchs mutableBytes]; - for (int i = 0; i < nfat_arch; i++) { + for (int i = 0; i < nfat_arch; ++i) { int offset = OSSwapBigToHostInt32(fat_arch[i].offset); int size = OSSwapBigToHostInt32(fat_arch[i].size); int cputype = OSSwapBigToHostInt(fat_arch[i].cputype); @@ -434,7 +433,7 @@ - (NSDictionary *)embeddedPlist { offset += sz_header; // Loop through the load commands looking for the segment named __TEXT - for (uint32_t i = 0; i < ncmds; i++) { + for (uint32_t i = 0; i < ncmds; ++i) { NSData *cmdData = [self safeSubdataWithRange:NSMakeRange(offset, sz_segment)]; if (!cmdData) return nil; struct segment_command_64 *lc = (struct segment_command_64 *)[cmdData bytes]; @@ -449,7 +448,7 @@ - (NSDictionary *)embeddedPlist { } // Loop through the sections in the __TEXT segment looking for an __info_plist section. - for (uint32_t i = 0; i < nsects; i++) { + for (uint32_t i = 0; i < nsects; ++i) { NSData *sectData = [self safeSubdataWithRange:NSMakeRange(offset, sz_section)]; if (!sectData) return nil; struct section_64 *sect = (struct section_64 *)[sectData bytes]; @@ -527,14 +526,17 @@ - (NSDictionary *)quarantineData { } NSURL *dbPath = [NSURL fileURLWithPathComponents:@[ - fileOwnerHomeDir, @"Library", @"Preferences", - @"com.apple.LaunchServices.QuarantineEventsV2" ]]; + fileOwnerHomeDir, + @"Library", + @"Preferences", + @"com.apple.LaunchServices.QuarantineEventsV2" + ]]; FMDatabase *db = [FMDatabase databaseWithPath:[dbPath absoluteString]]; db.logsErrors = NO; if ([db open]) { FMResultSet *rs = [db executeQuery:@"SELECT * FROM LSQuarantineEvent " - @"WHERE LSQuarantineEventIdentifier=?", - d[@"LSQuarantineEventIdentifier"]]; + @"WHERE LSQuarantineEventIdentifier=?", + d[@"LSQuarantineEventIdentifier"]]; if ([rs next]) { NSString *agentBundleID = [rs stringForColumn:@"LSQuarantineAgentBundleIdentifier"]; NSString *dataURLString = [rs stringForColumn:@"LSQuarantineDataURLString"]; diff --git a/Source/common/SNTFileWatcher.m b/Source/common/SNTFileWatcher.m index 7af61ab6d..9a9a75ff8 100644 --- a/Source/common/SNTFileWatcher.m +++ b/Source/common/SNTFileWatcher.m @@ -54,34 +54,34 @@ - (void)beginWatchingFile { dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0); self.internalEventHandler = ^{ - unsigned long l = dispatch_source_get_data(weakSelf.monitoringSource); - if (l & DISPATCH_VNODE_DELETE || l & DISPATCH_VNODE_RENAME) { - if (weakSelf.monitoringSource) dispatch_source_cancel(weakSelf.monitoringSource); - } else { - weakSelf.eventHandler(); - } + unsigned long l = dispatch_source_get_data(weakSelf.monitoringSource); + if (l & DISPATCH_VNODE_DELETE || l & DISPATCH_VNODE_RENAME) { + if (weakSelf.monitoringSource) dispatch_source_cancel(weakSelf.monitoringSource); + } else { + weakSelf.eventHandler(); + } }; self.internalCancelHandler = ^{ - int fd; + int fd; - if (weakSelf.monitoringSource) { - fd = (int)dispatch_source_get_handle(weakSelf.monitoringSource); - close(fd); - } + if (weakSelf.monitoringSource) { + fd = (int)dispatch_source_get_handle(weakSelf.monitoringSource); + close(fd); + } - const char *filePathCString = [weakSelf.filePath fileSystemRepresentation]; - while ((fd = open(filePathCString, O_EVTONLY)) < 0) { - usleep(1000); - } + const char *filePathCString = [weakSelf.filePath fileSystemRepresentation]; + while ((fd = open(filePathCString, O_EVTONLY)) < 0) { + usleep(1000); + } - weakSelf.monitoringSource = - dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, fd, mask, queue); - dispatch_source_set_event_handler(weakSelf.monitoringSource, weakSelf.internalEventHandler); - dispatch_source_set_cancel_handler(weakSelf.monitoringSource, weakSelf.internalCancelHandler); - dispatch_resume(weakSelf.monitoringSource); + weakSelf.monitoringSource = + dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, fd, mask, queue); + dispatch_source_set_event_handler(weakSelf.monitoringSource, weakSelf.internalEventHandler); + dispatch_source_set_cancel_handler(weakSelf.monitoringSource, weakSelf.internalCancelHandler); + dispatch_resume(weakSelf.monitoringSource); - weakSelf.eventHandler(); + weakSelf.eventHandler(); }; dispatch_async(queue, self.internalCancelHandler); @@ -92,7 +92,9 @@ - (void)stopWatchingFile { int fd = (int)dispatch_source_get_handle(self.monitoringSource); dispatch_source_set_event_handler_f(self.monitoringSource, NULL); - dispatch_source_set_cancel_handler(self.monitoringSource, ^{ close(fd); }); + dispatch_source_set_cancel_handler(self.monitoringSource, ^{ + close(fd); + }); dispatch_source_cancel(self.monitoringSource); self.monitoringSource = nil; diff --git a/Source/common/SNTLogging.m b/Source/common/SNTLogging.m index b95ba2076..af4ddd876 100644 --- a/Source/common/SNTLogging.m +++ b/Source/common/SNTLogging.m @@ -34,20 +34,20 @@ void logMessage(LogLevel level, FILE *destination, NSString *format, ...) { static pthread_key_t syslogKey = 0; dispatch_once(&pred, ^{ - binaryName = [[[NSProcessInfo processInfo] processName] UTF8String]; + binaryName = [[[NSProcessInfo processInfo] processName] UTF8String]; - // If debug logging is enabled, the process must be restarted. - if ([[[NSProcessInfo processInfo] arguments] containsObject:@"--debug"]) { - logLevel = LOG_LEVEL_DEBUG; - } + // If debug logging is enabled, the process must be restarted. + if ([[[NSProcessInfo processInfo] arguments] containsObject:@"--debug"]) { + logLevel = LOG_LEVEL_DEBUG; + } - // If requested, redirect output to syslog. - if ([[[NSProcessInfo processInfo] arguments] containsObject:@"--syslog"] || - strcmp(binaryName, "santad") == 0) { - useSyslog = YES; + // If requested, redirect output to syslog. + if ([[[NSProcessInfo processInfo] arguments] containsObject:@"--syslog"] || + strcmp(binaryName, "santad") == 0) { + useSyslog = YES; - pthread_key_create(&syslogKey, syslogClientDestructor); - } + pthread_key_create(&syslogKey, syslogClientDestructor); + } }); if (logLevel < level) return; @@ -68,10 +68,22 @@ void logMessage(LogLevel level, FILE *destination, NSString *format, ...) { char *levelName; int syslogLevel = ASL_LEVEL_DEBUG; switch (level) { - case LOG_LEVEL_ERROR: levelName = "E"; syslogLevel = ASL_LEVEL_ERR; break; - case LOG_LEVEL_WARN: levelName = "W"; syslogLevel = ASL_LEVEL_WARNING; break; - case LOG_LEVEL_INFO: levelName = "I"; syslogLevel = ASL_LEVEL_INFO; break; - case LOG_LEVEL_DEBUG: levelName = "D"; syslogLevel = ASL_LEVEL_DEBUG; break; + case LOG_LEVEL_ERROR: + levelName = "E"; + syslogLevel = ASL_LEVEL_ERR; + break; + case LOG_LEVEL_WARN: + levelName = "W"; + syslogLevel = ASL_LEVEL_WARNING; + break; + case LOG_LEVEL_INFO: + levelName = "I"; + syslogLevel = ASL_LEVEL_INFO; + break; + case LOG_LEVEL_DEBUG: + levelName = "D"; + syslogLevel = ASL_LEVEL_DEBUG; + break; } asl_log(client, NULL, syslogLevel, "%s %s: %s", levelName, binaryName, [s UTF8String]); diff --git a/Source/common/SNTRule.m b/Source/common/SNTRule.m index 6104d6472..2b454b546 100644 --- a/Source/common/SNTRule.m +++ b/Source/common/SNTRule.m @@ -78,7 +78,7 @@ - (NSUInteger)hash { - (NSString *)description { return [NSString stringWithFormat:@"SNTRule: SHA-256: %@, State: %d, Type: %d", - self.shasum, self.state, self.type]; + self.shasum, self.state, self.type]; } @end diff --git a/Source/common/SNTStoredEvent.h b/Source/common/SNTStoredEvent.h index 63cbcc4f9..184b9dd90 100644 --- a/Source/common/SNTStoredEvent.h +++ b/Source/common/SNTStoredEvent.h @@ -108,5 +108,4 @@ @property NSDate *quarantineTimestamp; @property NSString *quarantineAgentBundleID; - @end diff --git a/Source/common/SNTStoredEvent.m b/Source/common/SNTStoredEvent.m index 9eb334297..293f70df2 100644 --- a/Source/common/SNTStoredEvent.m +++ b/Source/common/SNTStoredEvent.m @@ -22,7 +22,7 @@ @implementation SNTStoredEvent #define DECODE(cls, key) [decoder decodeObjectOfClass:[cls class] forKey:key] #define DECODEARRAY(cls, key) \ [decoder decodeObjectOfClasses:[NSSet setWithObjects:[NSArray class], [cls class], nil] \ - forKey:key] + forKey:key] + (BOOL)supportsSecureCoding { return YES; @@ -53,7 +53,7 @@ - (void)encodeWithCoder:(NSCoder *)coder { ENCODE(self.quarantineDataURL, @"quarantineDataURL"); ENCODE(self.quarantineRefererURL, @"quarantineRefererURL"); ENCODE(self.quarantineTimestamp, @"quarantineTimestamp"); - ENCODE(self.quarantineAgentBundleID, @"quarantineAgentBundleID"); + ENCODE(self.quarantineAgentBundleID, @"quarantineAgentBundleID"); } - (instancetype)initWithCoder:(NSCoder *)decoder { diff --git a/Source/common/SNTXPCConnection.m b/Source/common/SNTXPCConnection.m index ac0d04f5e..d5ac39717 100644 --- a/Source/common/SNTXPCConnection.m +++ b/Source/common/SNTXPCConnection.m @@ -78,7 +78,6 @@ @interface SNTXPCConnection () /// @property NSXPCInterface *validatorInterface; - @property NSMutableArray *pendingConnections; @property NSMutableArray *acceptedConnections; @@ -137,12 +136,14 @@ - (void)resume { self.currentConnection = nil; }; - connection.interruptionHandler = ^{ [self.currentConnection invalidate]; }; + connection.interruptionHandler = ^{ + [self.currentConnection invalidate]; + }; [connection resume]; dispatch_semaphore_t sema = dispatch_semaphore_create(0); - [[connection remoteObjectProxy] isConnectionValidWithBlock:^void(BOOL response) { + [[connection remoteObjectProxy] isConnectionValidWithBlock:^(BOOL response) { pid_t pid = self.currentConnection.processIdentifier; MOLCodesignChecker *selfCS = [[MOLCodesignChecker alloc] initWithSelf]; @@ -178,7 +179,7 @@ - (BOOL)listener:(NSXPCListener *)listener shouldAcceptNewConnection:(NSXPCConne SNTXPCConnectionValidator *connectionValidator = [[SNTXPCConnectionValidator alloc] init]; connectionValidator.connection = connection; - + connectionValidator.acceptedHandler = ^{ [self.pendingConnections removeObject:weakConnection]; [self.acceptedConnections addObject:weakConnection]; diff --git a/Source/santa-driver/SantaDecisionManager.cc b/Source/santa-driver/SantaDecisionManager.cc index d6456c808..43a3611bd 100644 --- a/Source/santa-driver/SantaDecisionManager.cc +++ b/Source/santa-driver/SantaDecisionManager.cc @@ -535,15 +535,20 @@ void SantaDecisionManager::FileOpCallback( switch (action) { case KAUTH_FILEOP_CLOSE: - message->action = ACTION_NOTIFY_WRITE; break; + message->action = ACTION_NOTIFY_WRITE; + break; case KAUTH_FILEOP_RENAME: - message->action = ACTION_NOTIFY_RENAME; break; + message->action = ACTION_NOTIFY_RENAME; + break; case KAUTH_FILEOP_LINK: - message->action = ACTION_NOTIFY_LINK; break; + message->action = ACTION_NOTIFY_LINK; + break; case KAUTH_FILEOP_EXCHANGE: - message->action = ACTION_NOTIFY_EXCHANGE; break; + message->action = ACTION_NOTIFY_EXCHANGE; + break; case KAUTH_FILEOP_DELETE: - message->action = ACTION_NOTIFY_DELETE; break; + message->action = ACTION_NOTIFY_DELETE; + break; default: delete message; return; } @@ -567,7 +572,7 @@ extern "C" int fileop_scope_callback( switch (action) { case KAUTH_FILEOP_CLOSE: if (!(arg2 & KAUTH_FILEOP_CLOSE_MODIFIED)) return KAUTH_RESULT_DEFER; - // Intentional fall-through + // Intentional fall-through case KAUTH_FILEOP_DELETE: case KAUTH_FILEOP_EXEC: vp = reinterpret_cast(arg0); diff --git a/Source/santa-driver/SantaDecisionManager.h b/Source/santa-driver/SantaDecisionManager.h index d89cdf7a4..529198080 100644 --- a/Source/santa-driver/SantaDecisionManager.h +++ b/Source/santa-driver/SantaDecisionManager.h @@ -24,9 +24,9 @@ #include #include -#include "SantaCachedDecision.h" #include "SNTKernelCommon.h" #include "SNTLogging.h" +#include "SantaCachedDecision.h" #include "SantaPIDAndPPID.h" /// @@ -276,5 +276,4 @@ extern "C" int fileop_scope_callback( kauth_cred_t credential, void *idata, kauth_action_t action, uintptr_t arg0, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3); - #endif // SANTA__SANTA_DRIVER__SANTADECISIONMANAGER_H diff --git a/Source/santa-driver/SantaDriver.h b/Source/santa-driver/SantaDriver.h index 8abae1787..41c712fef 100644 --- a/Source/santa-driver/SantaDriver.h +++ b/Source/santa-driver/SantaDriver.h @@ -18,8 +18,8 @@ #include #include -#include "SantaDecisionManager.h" #include "SNTLogging.h" +#include "SantaDecisionManager.h" /// /// The driver class, which provides the start/stop functions and holds diff --git a/Source/santa-driver/SantaDriverClient.cc b/Source/santa-driver/SantaDriverClient.cc index e99713770..485df6646 100644 --- a/Source/santa-driver/SantaDriverClient.cc +++ b/Source/santa-driver/SantaDriverClient.cc @@ -25,7 +25,7 @@ OSDefineMetaClassAndStructors(com_google_SantaDriverClient, IOUserClient); bool SantaDriverClient::initWithTask( task_t owningTask, void *securityID, UInt32 type) { if (clientHasPrivilege( - owningTask, kIOClientPrivilegeAdministrator) != KERN_SUCCESS) { + owningTask, kIOClientPrivilegeAdministrator) != KERN_SUCCESS) { LOGW("Unprivileged client attempted to connect."); return false; } diff --git a/Source/santa-driver/SantaDriverClient.h b/Source/santa-driver/SantaDriverClient.h index 300804216..e1bb48e49 100644 --- a/Source/santa-driver/SantaDriverClient.h +++ b/Source/santa-driver/SantaDriverClient.h @@ -17,12 +17,12 @@ #include #include -#include #include +#include +#include "SNTKernelCommon.h" #include "SantaDecisionManager.h" #include "SantaDriver.h" -#include "SNTKernelCommon.h" /// /// This class is instantiated by IOKit when a new client process attempts to diff --git a/Source/santactl/SNTCommandController.h b/Source/santactl/SNTCommandController.h index d8fc85dc5..72de9ea42 100644 --- a/Source/santactl/SNTCommandController.h +++ b/Source/santactl/SNTCommandController.h @@ -17,7 +17,7 @@ /// /// Protocol that each command must adhere to. /// -@protocol SNTCommand +@protocol SNTCommand /// /// @return YES if command requires root. diff --git a/Source/santactl/SNTCommandController.m b/Source/santactl/SNTCommandController.m index e82608f38..ad0809ee5 100644 --- a/Source/santactl/SNTCommandController.m +++ b/Source/santactl/SNTCommandController.m @@ -72,13 +72,13 @@ + (SNTXPCConnection *)connectToDaemon { daemonConn.remoteInterface = [SNTXPCControlInterface controlInterface]; daemonConn.rejectedHandler = ^{ - printf("The daemon rejected the connection\n"); - exit(1); + printf("The daemon rejected the connection\n"); + exit(1); }; daemonConn.invalidationHandler = ^{ - printf("An error occurred communicating with the daemon, is it running?\n"); - exit(1); + printf("An error occurred communicating with the daemon, is it running?\n"); + exit(1); }; [daemonConn resume]; diff --git a/Source/santactl/fileinfo/SNTCommandFileInfo.m b/Source/santactl/fileinfo/SNTCommandFileInfo.m index 0a0c66cd3..56e403865 100644 --- a/Source/santactl/fileinfo/SNTCommandFileInfo.m +++ b/Source/santactl/fileinfo/SNTCommandFileInfo.m @@ -87,7 +87,8 @@ + (void)runWithArguments:(NSArray *)arguments daemonConnection:(SNTXPCConnection } NSString *s = [NSString stringWithFormat:@"%@ (%@)", - [self humanReadableFileType:fileInfo], [archs componentsJoinedByString:@", "]]; + [self humanReadableFileType:fileInfo], + [archs componentsJoinedByString:@", "]]; [self printKey:@"Type" value:s]; if ([fileInfo isMissingPageZero]) { @@ -102,16 +103,16 @@ + (void)runWithArguments:(NSArray *)arguments daemonConnection:(SNTXPCConnection [csc.certificates enumerateObjectsUsingBlock:^(MOLCertificate *c, unsigned long idx, BOOL *stop) { - printf(" %2lu. %-20s: %s\n", idx + 1, "SHA-256", [c.SHA256 UTF8String]); - printf(" %-20s: %s\n", "SHA-1", [c.SHA1 UTF8String]); - printf(" %-20s: %s\n", "Common Name", [c.commonName UTF8String]); - printf(" %-20s: %s\n", "Organization", [c.orgName UTF8String]); - printf(" %-20s: %s\n", "Organizational Unit", [c.orgUnit UTF8String]); - printf(" %-20s: %s\n", "Valid From", - [[dateFormatter stringFromDate:c.validFrom] UTF8String]); - printf(" %-20s: %s\n", "Valid Until", - [[dateFormatter stringFromDate:c.validUntil] UTF8String]); - printf("\n"); + printf(" %2lu. %-20s: %s\n", idx + 1, "SHA-256", [c.SHA256 UTF8String]); + printf(" %-20s: %s\n", "SHA-1", [c.SHA1 UTF8String]); + printf(" %-20s: %s\n", "Common Name", [c.commonName UTF8String]); + printf(" %-20s: %s\n", "Organization", [c.orgName UTF8String]); + printf(" %-20s: %s\n", "Organizational Unit", [c.orgUnit UTF8String]); + printf(" %-20s: %s\n", "Valid From", + [[dateFormatter stringFromDate:c.validFrom] UTF8String]); + printf(" %-20s: %s\n", "Valid Until", + [[dateFormatter stringFromDate:c.validUntil] UTF8String]); + printf("\n"); }]; } @@ -124,12 +125,12 @@ + (void)printKey:(NSString *)key value:(NSString *)value { } + (NSString *)humanReadableFileType:(SNTFileInfo *)fi { - if ([fi isScript]) return @"Script"; + if ([fi isScript]) return @"Script"; if ([fi isXARArchive]) return @"XAR Archive"; - if ([fi isDylib]) return @"Dynamic Library"; - if ([fi isKext]) return @"Kernel Extension"; - if ([fi isFat]) return @"Fat Binary"; - if ([fi isMachO]) return @"Thin Binary"; + if ([fi isDylib]) return @"Dynamic Library"; + if ([fi isKext]) return @"Kernel Extension"; + if ([fi isFat]) return @"Fat Binary"; + if ([fi isMachO]) return @"Thin Binary"; return @"Unknown"; } diff --git a/Source/santactl/flushcache/SNTCommandFlushCache.m b/Source/santactl/flushcache/SNTCommandFlushCache.m index dabf03658..7035c2cbe 100644 --- a/Source/santactl/flushcache/SNTCommandFlushCache.m +++ b/Source/santactl/flushcache/SNTCommandFlushCache.m @@ -44,13 +44,13 @@ + (NSString *)longHelpText { + (void)runWithArguments:(NSArray *)arguments daemonConnection:(SNTXPCConnection *)daemonConn { [[daemonConn remoteObjectProxy] flushCache:^(BOOL success) { - if (success) { - LOGI(@"Cache flush requested"); - exit(0); - } else { - LOGE(@"Cache flush failed"); - exit(1); - } + if (success) { + LOGI(@"Cache flush requested"); + exit(0); + } else { + LOGE(@"Cache flush failed"); + exit(1); + } }]; } diff --git a/Source/santactl/main.m b/Source/santactl/main.m index 9a5501b5a..9eae345d4 100644 --- a/Source/santactl/main.m +++ b/Source/santactl/main.m @@ -47,7 +47,7 @@ int main(int argc, const char *argv[]) { [commandName isEqualToString:@"usage"] || [commandName isEqualToString:@"commands"]) { print_usage(); - return 1;; + return 1; } [arguments removeObjectAtIndex:0]; diff --git a/Source/santactl/rule/SNTCommandRule.m b/Source/santactl/rule/SNTCommandRule.m index 2663a5d9a..1832190c0 100644 --- a/Source/santactl/rule/SNTCommandRule.m +++ b/Source/santactl/rule/SNTCommandRule.m @@ -25,7 +25,6 @@ #import "SNTXPCConnection.h" #import "SNTXPCControlInterface.h" - @interface SNTCommandRule : NSObject @property SNTXPCConnection *daemonConn; @end @@ -84,7 +83,7 @@ + (void)runWithArguments:(NSArray *)arguments daemonConnection:(SNTXPCConnection NSString *path; // Parse arguments - for (NSUInteger i = 0; i < arguments.count ; i++ ) { + for (NSUInteger i = 0; i < arguments.count; ++i) { NSString *arg = arguments[i]; if ([arg caseInsensitiveCompare:@"--whitelist"] == NSOrderedSame) { @@ -137,17 +136,17 @@ + (void)runWithArguments:(NSArray *)arguments daemonConnection:(SNTXPCConnection } [[daemonConn remoteObjectProxy] databaseRuleAddRule:newRule cleanSlate:NO reply:^(BOOL success) { - if (!success) { - printf("Failed to modify rules."); - exit(1); + if (!success) { + printf("Failed to modify rules."); + exit(1); + } else { + if (newRule.state == RULESTATE_REMOVE) { + printf("Removed rule for SHA-256: %s.\n", [newRule.shasum UTF8String]); } else { - if (newRule.state == RULESTATE_REMOVE) { - printf("Removed rule for SHA-256: %s.\n", [newRule.shasum UTF8String]); - } else { - printf("Added rule for SHA-256: %s.\n", [newRule.shasum UTF8String]); - } - exit(0); + printf("Added rule for SHA-256: %s.\n", [newRule.shasum UTF8String]); } + exit(0); + } }]; } diff --git a/Source/santactl/status/SNTCommandStatus.m b/Source/santactl/status/SNTCommandStatus.m index 27d293b22..7482610fb 100644 --- a/Source/santactl/status/SNTCommandStatus.m +++ b/Source/santactl/status/SNTCommandStatus.m @@ -51,21 +51,24 @@ + (void)runWithArguments:(NSArray *)arguments daemonConnection:(SNTXPCConnection __block double cpuPeak, ramPeak; dispatch_group_enter(group); [[daemonConn remoteObjectProxy] clientMode:^(santa_clientmode_t cm) { - switch (cm) { - case CLIENTMODE_MONITOR: - clientMode = @"Monitor"; break; - case CLIENTMODE_LOCKDOWN: - clientMode = @"Lockdown"; break; - default: - clientMode = [NSString stringWithFormat:@"Unknown (%d)", cm]; break; - } - dispatch_group_leave(group); + switch (cm) { + case CLIENTMODE_MONITOR: + clientMode = @"Monitor"; + break; + case CLIENTMODE_LOCKDOWN: + clientMode = @"Lockdown"; + break; + default: + clientMode = [NSString stringWithFormat:@"Unknown (%d)", cm]; + break; + } + dispatch_group_leave(group); }]; dispatch_group_enter(group); [[daemonConn remoteObjectProxy] watchdogInfo:^(uint64_t wd_cpuEvents, uint64_t wd_ramEvents, double wd_cpuPeak, double wd_ramPeak) { cpuEvents = wd_cpuEvents; - cpuPeak = wd_cpuPeak; + cpuPeak = wd_cpuPeak; ramEvents = wd_ramEvents; ramPeak = wd_ramPeak; dispatch_group_leave(group); @@ -77,22 +80,22 @@ + (void)runWithArguments:(NSArray *)arguments daemonConnection:(SNTXPCConnection __block int64_t cacheCount = -1; dispatch_group_enter(group); [[daemonConn remoteObjectProxy] cacheCount:^(int64_t count) { - cacheCount = count; - dispatch_group_leave(group); + cacheCount = count; + dispatch_group_leave(group); }]; // Database counts __block int64_t eventCount = -1, binaryRuleCount = -1, certRuleCount = -1; dispatch_group_enter(group); [[daemonConn remoteObjectProxy] databaseRuleCounts:^(int64_t binary, int64_t certificate) { - binaryRuleCount = binary; - certRuleCount = certificate; - dispatch_group_leave(group); + binaryRuleCount = binary; + certRuleCount = certificate; + dispatch_group_leave(group); }]; dispatch_group_enter(group); [[daemonConn remoteObjectProxy] databaseEventCount:^(int64_t count) { - eventCount = count; - dispatch_group_leave(group); + eventCount = count; + dispatch_group_leave(group); }]; // Sync status @@ -110,33 +113,33 @@ + (void)runWithArguments:(NSArray *)arguments daemonConnection:(SNTXPCConnection if ([arguments containsObject:@"--json"]) { NSDictionary *stats = @{ - @"daemon": @{ - @"mode": clientMode, - @"file_logging": @(fileLogging), - @"watchdog_cpu_events": @(cpuEvents), - @"watchdog_ram_events": @(ramEvents), - @"watchdog_cpu_peak": @(cpuPeak), - @"watchdog_ram_peak": @(ramPeak), - }, - @"kernel": @{ - @"cache_count": @(cacheCount), - }, - @"database": @{ - @"binary_rules": @(binaryRuleCount), - @"certificate_rules": @(certRuleCount), - @"events_pending_upload": @(eventCount), - }, - @"sync": @{ - @"server": syncURLStr, - @"clean_required": @(syncCleanReqd), - @"last_successful": lastSyncSuccessStr - }, + @"daemon" : @{ + @"mode" : clientMode, + @"file_logging" : @(fileLogging), + @"watchdog_cpu_events" : @(cpuEvents), + @"watchdog_ram_events" : @(ramEvents), + @"watchdog_cpu_peak" : @(cpuPeak), + @"watchdog_ram_peak" : @(ramPeak), + }, + @"kernel" : @{ + @"cache_count" : @(cacheCount), + }, + @"database" : @{ + @"binary_rules" : @(binaryRuleCount), + @"certificate_rules" : @(certRuleCount), + @"events_pending_upload" : @(eventCount), + }, + @"sync" : @{ + @"server" : syncURLStr, + @"clean_required" : @(syncCleanReqd), + @"last_successful" : lastSyncSuccessStr + }, }; NSData *statsData = [NSJSONSerialization dataWithJSONObject:stats options:NSJSONWritingPrettyPrinted error:nil]; NSString *statsStr = [[NSString alloc] initWithData:statsData encoding:NSUTF8StringEncoding]; - printf("%s\n", [statsStr UTF8String]); + printf("%s\n", [statsStr UTF8String]); } else { printf(">>> Daemon Info\n"); printf(" %-22s | %s\n", "Mode", [clientMode UTF8String]); diff --git a/Source/santactl/sync/SNTAuthenticatingURLSession.m b/Source/santactl/sync/SNTAuthenticatingURLSession.m index 007497eaf..8322e8455 100644 --- a/Source/santactl/sync/SNTAuthenticatingURLSession.m +++ b/Source/santactl/sync/SNTAuthenticatingURLSession.m @@ -111,13 +111,13 @@ - (void)URLSession:(NSURLSession *)session willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler { - if (self.refusesRedirects) { - LOGD(@"Rejected redirection to: %@", request.URL); - [task cancel]; // without this, the connection hangs until timeout!?! - completionHandler(NULL); - } else { - completionHandler(request); - } + if (self.refusesRedirects) { + LOGD(@"Rejected redirection to: %@", request.URL); + [task cancel]; // without this, the connection hangs until timeout!?! + completionHandler(NULL); + } else { + completionHandler(request); + } } #pragma mark Private Helpers for URLSession:didReceiveChallenge:completionHandler: @@ -144,10 +144,10 @@ - (NSURLCredential *)clientCredentialForProtectionSpace:(NSURLProtectionSpace *) foundIdentity = [self identityFromFile:self.clientCertFile password:self.clientCertPassword]; } else { CFArrayRef cfResults = NULL; - SecItemCopyMatching((__bridge CFDictionaryRef)@{ - (id)kSecClass: (id)kSecClassCertificate, - (id)kSecReturnRef: @YES, - (id)kSecMatchLimit: (id)kSecMatchLimitAll + SecItemCopyMatching((__bridge CFDictionaryRef) @{ + (id)kSecClass : (id)kSecClassCertificate, + (id)kSecReturnRef : @YES, + (id)kSecMatchLimit : (id)kSecMatchLimitAll }, (CFTypeRef *)&cfResults); NSArray *results = CFBridgingRelease(cfResults); @@ -202,7 +202,6 @@ - (NSURLCredential *)clientCredentialForProtectionSpace:(NSURLProtectionSpace *) [NSURLCredential credentialWithIdentity:foundIdentity certificates:nil persistence:NSURLCredentialPersistenceForSession]; -// CFRelease(foundIdentity); return cred; } else { LOGD(@"Client Trust: No valid identity found."); @@ -289,23 +288,23 @@ - (SecIdentityRef)identityByFilteringArray:(NSArray *)array if (commonName) { [predicates addObject:[NSPredicate predicateWithFormat:@"SELF.commonName == %@", - commonName]]; + commonName]]; } if (issuerCommonName) { [predicates addObject:[NSPredicate predicateWithFormat:@"SELF.issuerCommonName == %@", - issuerCommonName]]; + issuerCommonName]]; } if (issuerCountryName) { [predicates addObject:[NSPredicate predicateWithFormat:@"SELF.issuerCountryName == %@", - issuerCountryName]]; + issuerCountryName]]; } if (issuerOrgName) { [predicates addObject:[NSPredicate predicateWithFormat:@"SELF.issuerOrgName == %@", - issuerOrgName]]; + issuerOrgName]]; } if (issuerOrgUnit) { [predicates addObject:[NSPredicate predicateWithFormat:@"SELF.issuerOrgUnit == %@", - issuerOrgUnit]]; + issuerOrgUnit]]; } NSCompoundPredicate *andPreds = [NSCompoundPredicate andPredicateWithSubpredicates:predicates]; @@ -348,7 +347,7 @@ - (SecIdentityRef)identityFromFile:(NSString *)file password:(NSString *)passwor return nil; } - NSDictionary *options = (password ? @{(__bridge id)kSecImportExportPassphrase: password} : @{}); + NSDictionary *options = (password ? @{(__bridge id)kSecImportExportPassphrase : password} : @{}); CFArrayRef cfIdentities; OSStatus err = SecPKCS12Import( (__bridge CFDataRef)data, (__bridge CFDictionaryRef)options, &cfIdentities); diff --git a/Source/santactl/sync/SNTCommandSync.m b/Source/santactl/sync/SNTCommandSync.m index f632bee95..e2c02161e 100644 --- a/Source/santactl/sync/SNTCommandSync.m +++ b/Source/santactl/sync/SNTCommandSync.m @@ -75,7 +75,7 @@ + (void)runWithArguments:(NSArray *)arguments daemonConnection:(SNTXPCConnection authURLSession.userAgent = @"santactl-sync/"; NSString *santactlVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]; if (santactlVersion) { - authURLSession.userAgent = [authURLSession.userAgent stringByAppendingString:santactlVersion]; + authURLSession.userAgent = [authURLSession.userAgent stringByAppendingString:santactlVersion]; } authURLSession.refusesRedirects = YES; @@ -89,10 +89,10 @@ + (void)runWithArguments:(NSArray *)arguments daemonConnection:(SNTXPCConnection authURLSession.serverRootsPemData = rootsData; if (!rootsData) { - LOGE(@"Couldn't open server root certificate file %@ with error: %@.", - [config syncServerAuthRootsFile], - [error localizedDescription]); - exit(1); + LOGE(@"Couldn't open server root certificate file %@ with error: %@.", + [config syncServerAuthRootsFile], + [error localizedDescription]); + exit(1); } } else if ([config syncServerAuthRootsData]) { authURLSession.serverRootsPemData = [config syncServerAuthRootsData]; diff --git a/Source/santactl/sync/SNTCommandSyncConstants.h b/Source/santactl/sync/SNTCommandSyncConstants.h index 7d92b70b4..6c1349862 100644 --- a/Source/santactl/sync/SNTCommandSyncConstants.h +++ b/Source/santactl/sync/SNTCommandSyncConstants.h @@ -12,78 +12,78 @@ /// See the License for the specific language governing permissions and /// limitations under the License. -extern NSString * const kURLPreflight; -extern NSString * const kURLEventUpload; -extern NSString * const kURLRuleDownload; -extern NSString * const kURLPostflight; +extern NSString *const kURLPreflight; +extern NSString *const kURLEventUpload; +extern NSString *const kURLRuleDownload; +extern NSString *const kURLPostflight; -extern NSString * const kSerialNumber; -extern NSString * const kHostname; -extern NSString * const kSantaVer; -extern NSString * const kOSVer; -extern NSString * const kOSBuild; -extern NSString * const kPrimaryUser; -extern NSString * const kRequestCleanSync; -extern NSString * const kBatchSize; -extern NSString * const kUploadLogsURL; -extern NSString * const kClientMode; -extern NSString * const kClientModeMonitor; -extern NSString * const kClientModeLockdown; -extern NSString * const kCleanSync; -extern NSString * const kWhitelistRegex; -extern NSString * const kBlacklistRegex; +extern NSString *const kSerialNumber; +extern NSString *const kHostname; +extern NSString *const kSantaVer; +extern NSString *const kOSVer; +extern NSString *const kOSBuild; +extern NSString *const kPrimaryUser; +extern NSString *const kRequestCleanSync; +extern NSString *const kBatchSize; +extern NSString *const kUploadLogsURL; +extern NSString *const kClientMode; +extern NSString *const kClientModeMonitor; +extern NSString *const kClientModeLockdown; +extern NSString *const kCleanSync; +extern NSString *const kWhitelistRegex; +extern NSString *const kBlacklistRegex; -extern NSString * const kEvents; -extern NSString * const kFileSHA256; -extern NSString * const kFilePath; -extern NSString * const kFileName; -extern NSString * const kExecutingUser; -extern NSString * const kExecutionTime; -extern NSString * const kDecision; -extern NSString * const kDecisionAllowUnknown; -extern NSString * const kDecisionAllowBinary; -extern NSString * const kDecisionAllowCertificate; -extern NSString * const kDecisionAllowScope; -extern NSString * const kDecisionBlockUnknown; -extern NSString * const kDecisionBlockBinary; -extern NSString * const kDecisionBlockCertificate; -extern NSString * const kDecisionBlockScope; -extern NSString * const kDecisionUnknown; -extern NSString * const kDecisionRelatedBinary; -extern NSString * const kLoggedInUsers; -extern NSString * const kCurrentSessions; -extern NSString * const kFileBundleID; -extern NSString * const kFileBundleName; -extern NSString * const kFileBundleVersion; -extern NSString * const kFileBundleShortVersionString; -extern NSString * const kPID; -extern NSString * const kPPID; -extern NSString * const kParentName; -extern NSString * const kSigningChain; -extern NSString * const kCertSHA256; -extern NSString * const kCertCN; -extern NSString * const kCertOrg; -extern NSString * const kCertOU; -extern NSString * const kCertValidFrom; -extern NSString * const kCertValidUntil; -extern NSString * const kQuarantineDataURL; -extern NSString * const kQuarantineRefererURL; -extern NSString * const kQuarantineTimestamp; -extern NSString * const kQuarantineAgentBundleID; +extern NSString *const kEvents; +extern NSString *const kFileSHA256; +extern NSString *const kFilePath; +extern NSString *const kFileName; +extern NSString *const kExecutingUser; +extern NSString *const kExecutionTime; +extern NSString *const kDecision; +extern NSString *const kDecisionAllowUnknown; +extern NSString *const kDecisionAllowBinary; +extern NSString *const kDecisionAllowCertificate; +extern NSString *const kDecisionAllowScope; +extern NSString *const kDecisionBlockUnknown; +extern NSString *const kDecisionBlockBinary; +extern NSString *const kDecisionBlockCertificate; +extern NSString *const kDecisionBlockScope; +extern NSString *const kDecisionUnknown; +extern NSString *const kDecisionRelatedBinary; +extern NSString *const kLoggedInUsers; +extern NSString *const kCurrentSessions; +extern NSString *const kFileBundleID; +extern NSString *const kFileBundleName; +extern NSString *const kFileBundleVersion; +extern NSString *const kFileBundleShortVersionString; +extern NSString *const kPID; +extern NSString *const kPPID; +extern NSString *const kParentName; +extern NSString *const kSigningChain; +extern NSString *const kCertSHA256; +extern NSString *const kCertCN; +extern NSString *const kCertOrg; +extern NSString *const kCertOU; +extern NSString *const kCertValidFrom; +extern NSString *const kCertValidUntil; +extern NSString *const kQuarantineDataURL; +extern NSString *const kQuarantineRefererURL; +extern NSString *const kQuarantineTimestamp; +extern NSString *const kQuarantineAgentBundleID; -extern NSString * const kLogUploadField; +extern NSString *const kLogUploadField; -extern NSString * const kRules; -extern NSString * const kRuleSHA256; -extern NSString * const kRulePolicy; -extern NSString * const kRulePolicyWhitelist; -extern NSString * const kRulePolicyBlacklist; -extern NSString * const kRulePolicySilentBlacklist; -extern NSString * const kRulePolicyRemove; -extern NSString * const kRuleType; -extern NSString * const kRuleTypeBinary; -extern NSString * const kRuleTypeCertificate; -extern NSString * const kRuleCustomMsg; -extern NSString * const kCursor; +extern NSString *const kRules; +extern NSString *const kRuleSHA256; +extern NSString *const kRulePolicy; +extern NSString *const kRulePolicyWhitelist; +extern NSString *const kRulePolicyBlacklist; +extern NSString *const kRulePolicySilentBlacklist; +extern NSString *const kRulePolicyRemove; +extern NSString *const kRuleType; +extern NSString *const kRuleTypeBinary; +extern NSString *const kRuleTypeCertificate; +extern NSString *const kRuleCustomMsg; +extern NSString *const kCursor; -extern NSString * const kBackoffInterval; +extern NSString *const kBackoffInterval; diff --git a/Source/santactl/sync/SNTCommandSyncConstants.m b/Source/santactl/sync/SNTCommandSyncConstants.m index d9bf46217..498342650 100644 --- a/Source/santactl/sync/SNTCommandSyncConstants.m +++ b/Source/santactl/sync/SNTCommandSyncConstants.m @@ -14,78 +14,78 @@ #import "SNTCommandSyncConstants.h" -NSString * const kURLPreflight = @"preflight/"; -NSString * const kURLEventUpload = @"eventupload/"; -NSString * const kURLRuleDownload = @"ruledownload/"; -NSString * const kURLPostflight = @"postflight/"; +NSString *const kURLPreflight = @"preflight/"; +NSString *const kURLEventUpload = @"eventupload/"; +NSString *const kURLRuleDownload = @"ruledownload/"; +NSString *const kURLPostflight = @"postflight/"; -NSString * const kSerialNumber = @"serial_num"; -NSString * const kHostname = @"hostname"; -NSString * const kSantaVer = @"santa_version"; -NSString * const kOSVer = @"os_version"; -NSString * const kOSBuild = @"os_build"; -NSString * const kPrimaryUser = @"primary_user"; -NSString * const kRequestCleanSync = @"request_clean_sync"; -NSString * const kBatchSize = @"batch_size"; -NSString * const kUploadLogsURL = @"upload_logs_url"; -NSString * const kClientMode = @"client_mode"; -NSString * const kClientModeMonitor = @"MONITOR"; -NSString * const kClientModeLockdown = @"LOCKDOWN"; -NSString * const kCleanSync = @"clean_sync"; -NSString * const kWhitelistRegex = @"whitelist_regex"; -NSString * const kBlacklistRegex = @"blacklist_regex"; +NSString *const kSerialNumber = @"serial_num"; +NSString *const kHostname = @"hostname"; +NSString *const kSantaVer = @"santa_version"; +NSString *const kOSVer = @"os_version"; +NSString *const kOSBuild = @"os_build"; +NSString *const kPrimaryUser = @"primary_user"; +NSString *const kRequestCleanSync = @"request_clean_sync"; +NSString *const kBatchSize = @"batch_size"; +NSString *const kUploadLogsURL = @"upload_logs_url"; +NSString *const kClientMode = @"client_mode"; +NSString *const kClientModeMonitor = @"MONITOR"; +NSString *const kClientModeLockdown = @"LOCKDOWN"; +NSString *const kCleanSync = @"clean_sync"; +NSString *const kWhitelistRegex = @"whitelist_regex"; +NSString *const kBlacklistRegex = @"blacklist_regex"; -NSString * const kEvents = @"events"; -NSString * const kFileSHA256 = @"file_sha256"; -NSString * const kFilePath = @"file_path"; -NSString * const kFileName = @"file_name"; -NSString * const kExecutingUser = @"executing_user"; -NSString * const kExecutionTime = @"execution_time"; -NSString * const kDecision = @"decision"; -NSString * const kDecisionAllowUnknown = @"ALLOW_UNKNOWN"; -NSString * const kDecisionAllowBinary = @"ALLOW_BINARY"; -NSString * const kDecisionAllowCertificate = @"ALLOW_CERTIFICATE"; -NSString * const kDecisionAllowScope = @"ALLOW_SCOPE"; -NSString * const kDecisionBlockUnknown = @"BLOCK_UNKNOWN"; -NSString * const kDecisionBlockBinary = @"BLOCK_BINARY"; -NSString * const kDecisionBlockCertificate = @"BLOCK_CERTIFICATE"; -NSString * const kDecisionBlockScope = @"BLOCK_SCOPE"; -NSString * const kDecisionUnknown = @"UNKNOWN"; -NSString * const kDecisionRelatedBinary = @"RELATED_BINARY"; -NSString * const kLoggedInUsers = @"logged_in_users"; -NSString * const kCurrentSessions = @"current_sessions"; -NSString * const kFileBundleID = @"file_bundle_id"; -NSString * const kFileBundleName = @"file_bundle_name"; -NSString * const kFileBundleVersion = @"file_bundle_version"; -NSString * const kFileBundleShortVersionString = @"file_bundle_version_string"; -NSString * const kPID = @"pid"; -NSString * const kPPID = @"ppid"; -NSString * const kParentName = @"parent_name"; -NSString * const kSigningChain = @"signing_chain"; -NSString * const kCertSHA256 = @"sha256"; -NSString * const kCertCN = @"cn"; -NSString * const kCertOrg = @"org"; -NSString * const kCertOU = @"ou"; -NSString * const kCertValidFrom = @"valid_from"; -NSString * const kCertValidUntil = @"valid_until"; -NSString * const kQuarantineDataURL = @"quarantine_data_url"; -NSString * const kQuarantineRefererURL = @"quarantine_referer_url"; -NSString * const kQuarantineTimestamp = @"quarantine_timestamp"; -NSString * const kQuarantineAgentBundleID = @"quarantine_agent_bundle_id"; +NSString *const kEvents = @"events"; +NSString *const kFileSHA256 = @"file_sha256"; +NSString *const kFilePath = @"file_path"; +NSString *const kFileName = @"file_name"; +NSString *const kExecutingUser = @"executing_user"; +NSString *const kExecutionTime = @"execution_time"; +NSString *const kDecision = @"decision"; +NSString *const kDecisionAllowUnknown = @"ALLOW_UNKNOWN"; +NSString *const kDecisionAllowBinary = @"ALLOW_BINARY"; +NSString *const kDecisionAllowCertificate = @"ALLOW_CERTIFICATE"; +NSString *const kDecisionAllowScope = @"ALLOW_SCOPE"; +NSString *const kDecisionBlockUnknown = @"BLOCK_UNKNOWN"; +NSString *const kDecisionBlockBinary = @"BLOCK_BINARY"; +NSString *const kDecisionBlockCertificate = @"BLOCK_CERTIFICATE"; +NSString *const kDecisionBlockScope = @"BLOCK_SCOPE"; +NSString *const kDecisionUnknown = @"UNKNOWN"; +NSString *const kDecisionRelatedBinary = @"RELATED_BINARY"; +NSString *const kLoggedInUsers = @"logged_in_users"; +NSString *const kCurrentSessions = @"current_sessions"; +NSString *const kFileBundleID = @"file_bundle_id"; +NSString *const kFileBundleName = @"file_bundle_name"; +NSString *const kFileBundleVersion = @"file_bundle_version"; +NSString *const kFileBundleShortVersionString = @"file_bundle_version_string"; +NSString *const kPID = @"pid"; +NSString *const kPPID = @"ppid"; +NSString *const kParentName = @"parent_name"; +NSString *const kSigningChain = @"signing_chain"; +NSString *const kCertSHA256 = @"sha256"; +NSString *const kCertCN = @"cn"; +NSString *const kCertOrg = @"org"; +NSString *const kCertOU = @"ou"; +NSString *const kCertValidFrom = @"valid_from"; +NSString *const kCertValidUntil = @"valid_until"; +NSString *const kQuarantineDataURL = @"quarantine_data_url"; +NSString *const kQuarantineRefererURL = @"quarantine_referer_url"; +NSString *const kQuarantineTimestamp = @"quarantine_timestamp"; +NSString *const kQuarantineAgentBundleID = @"quarantine_agent_bundle_id"; -NSString * const kLogUploadField = @"files"; +NSString *const kLogUploadField = @"files"; -NSString * const kRules = @"rules"; -NSString * const kRuleSHA256 = @"sha256"; -NSString * const kRulePolicy = @"policy"; -NSString * const kRulePolicyWhitelist = @"WHITELIST"; -NSString * const kRulePolicyBlacklist = @"BLACKLIST"; -NSString * const kRulePolicySilentBlacklist = @"SILENT_BLACKLIST"; -NSString * const kRulePolicyRemove = @"REMOVE"; -NSString * const kRuleType = @"rule_type"; -NSString * const kRuleTypeBinary = @"BINARY"; -NSString * const kRuleTypeCertificate = @"CERTIFICATE"; -NSString * const kRuleCustomMsg = @"custom_msg"; -NSString * const kCursor = @"cursor"; +NSString *const kRules = @"rules"; +NSString *const kRuleSHA256 = @"sha256"; +NSString *const kRulePolicy = @"policy"; +NSString *const kRulePolicyWhitelist = @"WHITELIST"; +NSString *const kRulePolicyBlacklist = @"BLACKLIST"; +NSString *const kRulePolicySilentBlacklist = @"SILENT_BLACKLIST"; +NSString *const kRulePolicyRemove = @"REMOVE"; +NSString *const kRuleType = @"rule_type"; +NSString *const kRuleTypeBinary = @"BINARY"; +NSString *const kRuleTypeCertificate = @"CERTIFICATE"; +NSString *const kRuleCustomMsg = @"custom_msg"; +NSString *const kCursor = @"cursor"; -NSString * const kBackoffInterval = @"backoff"; +NSString *const kBackoffInterval = @"backoff"; diff --git a/Source/santactl/sync/SNTCommandSyncEventUpload.m b/Source/santactl/sync/SNTCommandSyncEventUpload.m index 50ea049fe..690bc2558 100644 --- a/Source/santactl/sync/SNTCommandSyncEventUpload.m +++ b/Source/santactl/sync/SNTCommandSyncEventUpload.m @@ -16,9 +16,9 @@ #include "SNTLogging.h" -#import "NSData+Zlib.h" #import "MOLCertificate.h" #import "MOLCodesignChecker.h" +#import "NSData+Zlib.h" #import "SNTCommandSyncConstants.h" #import "SNTCommandSyncState.h" #import "SNTFileInfo.h" @@ -36,16 +36,16 @@ + (void)performSyncInSession:(NSURLSession *)session relativeToURL:syncState.syncBaseURL]; [[daemonConn remoteObjectProxy] databaseEventsPending:^(NSArray *events) { - if ([events count] == 0) { - handler(YES); - } else { - [self uploadEventsFromArray:events - toURL:url - inSession:session - batchSize:syncState.eventBatchSize - daemonConn:daemonConn - completionHandler:handler]; - } + if ([events count] == 0) { + handler(YES); + } else { + [self uploadEventsFromArray:events + toURL:url + inSession:session + batchSize:syncState.eventBatchSize + daemonConn:daemonConn + completionHandler:handler]; + } }]; } @@ -57,17 +57,17 @@ + (void)uploadSingleEventWithSHA256:(NSString *)SHA256 NSURL *url = [NSURL URLWithString:[kURLEventUpload stringByAppendingString:syncState.machineID] relativeToURL:syncState.syncBaseURL]; [[daemonConn remoteObjectProxy] databaseEventForSHA256:SHA256 reply:^(SNTStoredEvent *event) { - if (!event) { - handler(YES); - return; - } + if (!event) { + handler(YES); + return; + } - [self uploadEventsFromArray:@[ event ] - toURL:url - inSession:session - batchSize:1 - daemonConn:daemonConn - completionHandler:handler]; + [self uploadEventsFromArray:@[ event ] + toURL:url + inSession:session + batchSize:1 + daemonConn:daemonConn + completionHandler:handler]; }]; } @@ -92,7 +92,7 @@ + (void)uploadEventsFromArray:(NSArray *)events if (eventIds.count >= batchSize) break; } - NSDictionary *uploadReq = @{ kEvents: uploadEvents }; + NSDictionary *uploadReq = @{kEvents : uploadEvents}; NSData *requestBody; @try { @@ -117,31 +117,31 @@ + (void)uploadEventsFromArray:(NSArray *)events [[session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - long statusCode = [(NSHTTPURLResponse *)response statusCode]; - if (statusCode != 200) { - LOGE(@"HTTP Response: %ld %@", - statusCode, - [[NSHTTPURLResponse localizedStringForStatusCode:statusCode] capitalizedString]); - LOGD(@"%@", error); - handler(NO); + long statusCode = [(NSHTTPURLResponse *)response statusCode]; + if (statusCode != 200) { + LOGE(@"HTTP Response: %ld %@", + statusCode, + [[NSHTTPURLResponse localizedStringForStatusCode:statusCode] capitalizedString]); + LOGD(@"%@", error); + handler(NO); + } else { + LOGI(@"Uploaded %lu events", eventIds.count); + + [[daemonConn remoteObjectProxy] databaseRemoveEventsWithIDs:eventIds]; + + NSArray *nextEvents = [events subarrayWithRange:NSMakeRange(eventIds.count, + events.count - eventIds.count)]; + if (nextEvents.count == 0) { + handler(YES); } else { - LOGI(@"Uploaded %lu events", eventIds.count); - - [[daemonConn remoteObjectProxy] databaseRemoveEventsWithIDs:eventIds]; - - NSArray *nextEvents = [events subarrayWithRange:NSMakeRange(eventIds.count, - events.count - eventIds.count)]; - if (nextEvents.count == 0) { - handler(YES); - } else { - [self uploadEventsFromArray:nextEvents - toURL:url - inSession:session - batchSize:batchSize - daemonConn:daemonConn - completionHandler:handler]; - } + [self uploadEventsFromArray:nextEvents + toURL:url + inSession:session + batchSize:batchSize + daemonConn:daemonConn + completionHandler:handler]; } + } }] resume]; } @@ -189,7 +189,7 @@ + (NSDictionary *)dictionaryForEvent:(SNTStoredEvent *)event { ADDKEY(newEvent, kQuarantineAgentBundleID, event.quarantineAgentBundleID); NSMutableArray *signingChain = [NSMutableArray arrayWithCapacity:event.signingChain.count]; - for (NSUInteger i = 0; i < event.signingChain.count; i++) { + for (NSUInteger i = 0; i < event.signingChain.count; ++i) { MOLCertificate *cert = [event.signingChain objectAtIndex:i]; NSMutableDictionary *certDict = [NSMutableDictionary dictionary]; diff --git a/Source/santactl/sync/SNTCommandSyncLogUpload.m b/Source/santactl/sync/SNTCommandSyncLogUpload.m index cc26850e9..1c49d5934 100644 --- a/Source/santactl/sync/SNTCommandSyncLogUpload.m +++ b/Source/santactl/sync/SNTCommandSyncLogUpload.m @@ -90,7 +90,7 @@ + (NSArray *)logsToUpload { NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:diagsDir]; NSString *file; while (file = [dirEnum nextObject]) { - if ([[file pathExtension] isEqualToString: @"panic"] || + if ([[file pathExtension] isEqualToString:@"panic"] || [file hasPrefix:@"santad"] || [file hasPrefix:@"santactl"]) { [logsToUpload addObject:[diagsDir stringByAppendingString:file]]; diff --git a/Source/santactl/sync/SNTCommandSyncPreflight.m b/Source/santactl/sync/SNTCommandSyncPreflight.m index 968668779..3a4adf6bd 100644 --- a/Source/santactl/sync/SNTCommandSyncPreflight.m +++ b/Source/santactl/sync/SNTCommandSyncPreflight.m @@ -62,44 +62,44 @@ + (void)performSyncInSession:(NSURLSession *)session [req setValue:@"zlib" forHTTPHeaderField:@"Content-Encoding"]; } - [req setHTTPBody:requestBody]; + [req setHTTPBody:requestBody]; [[session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - long statusCode = [(NSHTTPURLResponse *)response statusCode]; - if (statusCode != 200) { - LOGE(@"HTTP Response: %ld %@", - statusCode, - [[NSHTTPURLResponse localizedStringForStatusCode:statusCode] capitalizedString]); - LOGD(@"%@", error); - handler(NO); - } else { - NSDictionary *r = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; - - syncState.eventBatchSize = [r[kBatchSize] intValue]; - syncState.uploadLogURL = [NSURL URLWithString:r[kUploadLogsURL]]; - - if ([r[kClientMode] isEqual:kClientModeMonitor]) { - syncState.newClientMode = CLIENTMODE_MONITOR; - } else if ([r[kClientMode] isEqual:kClientModeLockdown]) { - syncState.newClientMode = CLIENTMODE_LOCKDOWN; - } - - if ([r[kWhitelistRegex] isKindOfClass:[NSString class]]) { - [[daemonConn remoteObjectProxy] setWhitelistPathRegex:r[kWhitelistRegex] reply:^{}]; - } - - if ([r[kBlacklistRegex] isKindOfClass:[NSString class]]) { - [[daemonConn remoteObjectProxy] setBlacklistPathRegex:r[kBlacklistRegex] reply:^{}]; - } - - if ([r[kCleanSync] boolValue]) { - syncState.cleanSync = YES; - } - - handler(YES); + long statusCode = [(NSHTTPURLResponse *)response statusCode]; + if (statusCode != 200) { + LOGE(@"HTTP Response: %ld %@", + statusCode, + [[NSHTTPURLResponse localizedStringForStatusCode:statusCode] capitalizedString]); + LOGD(@"%@", error); + handler(NO); + } else { + NSDictionary *r = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; + + syncState.eventBatchSize = [r[kBatchSize] intValue]; + syncState.uploadLogURL = [NSURL URLWithString:r[kUploadLogsURL]]; + + if ([r[kClientMode] isEqual:kClientModeMonitor]) { + syncState.newClientMode = CLIENTMODE_MONITOR; + } else if ([r[kClientMode] isEqual:kClientModeLockdown]) { + syncState.newClientMode = CLIENTMODE_LOCKDOWN; } + + if ([r[kWhitelistRegex] isKindOfClass:[NSString class]]) { + [[daemonConn remoteObjectProxy] setWhitelistPathRegex:r[kWhitelistRegex] reply:^{}]; + } + + if ([r[kBlacklistRegex] isKindOfClass:[NSString class]]) { + [[daemonConn remoteObjectProxy] setBlacklistPathRegex:r[kBlacklistRegex] reply:^{}]; + } + + if ([r[kCleanSync] boolValue]) { + syncState.cleanSync = YES; + } + + handler(YES); + } }] resume]; } diff --git a/Source/santactl/sync/SNTCommandSyncRuleDownload.m b/Source/santactl/sync/SNTCommandSyncRuleDownload.m index c6d477c5b..43d5e71d5 100644 --- a/Source/santactl/sync/SNTCommandSyncRuleDownload.m +++ b/Source/santactl/sync/SNTCommandSyncRuleDownload.m @@ -44,8 +44,7 @@ + (void)ruleDownloadWithCursor:(NSString *)cursor syncState:(SNTCommandSyncState *)syncState daemonConn:(SNTXPCConnection *)daemonConn completionHandler:(void (^)(BOOL success))handler { - - NSDictionary *requestDict = (cursor ? @{ kCursor: cursor } : @{}); + NSDictionary *requestDict = (cursor ? @{kCursor : cursor} : @{}); if (!syncState.downloadedRules) { syncState.downloadedRules = [NSMutableArray array]; @@ -60,52 +59,52 @@ + (void)ruleDownloadWithCursor:(NSString *)cursor [[session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - long statusCode = [(NSHTTPURLResponse *)response statusCode]; - if (statusCode != 200) { - LOGE(@"HTTP Response: %ld %@", - statusCode, - [[NSHTTPURLResponse localizedStringForStatusCode:statusCode] capitalizedString]); - LOGD(@"%@", error); + long statusCode = [(NSHTTPURLResponse *)response statusCode]; + if (statusCode != 200) { + LOGE(@"HTTP Response: %ld %@", + statusCode, + [[NSHTTPURLResponse localizedStringForStatusCode:statusCode] capitalizedString]); + LOGD(@"%@", error); + handler(NO); + } else { + NSDictionary *resp = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; + if (!resp) { + LOGE(@"Failed to decode server's response"); handler(NO); - } else { - NSDictionary *resp = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; - if (!resp) { - LOGE(@"Failed to decode server's response"); - handler(NO); - return; - } + return; + } - NSArray *receivedRules = resp[kRules]; - for (NSDictionary *rule in receivedRules) { - SNTRule *r = [self ruleFromDictionary:rule]; - if (r) [syncState.downloadedRules addObject:r]; - } + NSArray *receivedRules = resp[kRules]; + for (NSDictionary *rule in receivedRules) { + SNTRule *r = [self ruleFromDictionary:rule]; + if (r) [syncState.downloadedRules addObject:r]; + } - if (resp[kCursor]) { - [self ruleDownloadWithCursor:resp[kCursor] - url:url - session:session - syncState:syncState - daemonConn:daemonConn - completionHandler:handler]; + if (resp[kCursor]) { + [self ruleDownloadWithCursor:resp[kCursor] + url:url + session:session + syncState:syncState + daemonConn:daemonConn + completionHandler:handler]; + } else { + if (syncState.downloadedRules.count) { + [[daemonConn remoteObjectProxy] databaseRuleAddRules:syncState.downloadedRules + cleanSlate:syncState.cleanSync + reply:^(BOOL success) { + if (success) { + LOGI(@"Added %lu rule(s)", syncState.downloadedRules.count); + handler(YES); + } else { + LOGE(@"Failed to add rules to database"); + handler(NO); + } + }]; } else { - if (syncState.downloadedRules.count) { - [[daemonConn remoteObjectProxy] databaseRuleAddRules:syncState.downloadedRules - cleanSlate:syncState.cleanSync - reply:^(BOOL success) { - if (success) { - LOGI(@"Added %lu rule(s)", syncState.downloadedRules.count); - handler(YES); - } else { - LOGE(@"Failed to add rules to database"); - handler(NO); - } - }]; - } else { - handler(YES); - } + handler(YES); } } + } }] resume]; } diff --git a/Source/santactl/sync/SNTDERDecoder.m b/Source/santactl/sync/SNTDERDecoder.m index f671c1a65..df2e700f1 100644 --- a/Source/santactl/sync/SNTDERDecoder.m +++ b/Source/santactl/sync/SNTDERDecoder.m @@ -43,13 +43,13 @@ - (instancetype)init { - (NSString *)description { return [NSString stringWithFormat:@"/C=%@/O=%@/OU=%@/CN=%@", - self.countryName, - self.organizationName, - self.organizationalUnit, - self.commonName]; + self.countryName, + self.organizationName, + self.organizationalUnit, + self.commonName]; } -# pragma mark Accessors +#pragma mark Accessors - (NSString *)commonName { return self.decodedObjects[(__bridge id)kSecOIDCommonName]; @@ -98,29 +98,26 @@ - (NSDictionary *)decodeData:(NSData *)data { } OIDKeyValue; static const SecAsn1Template kOIDValueTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(OIDKeyValue) }, - { SEC_ASN1_OBJECT_ID, offsetof(OIDKeyValue, oid), NULL, 0 }, - { SEC_ASN1_ANY_CONTENTS, offsetof(OIDKeyValue, value), NULL, 0 }, - { 0, 0, NULL, 0 } - }; + {SEC_ASN1_SEQUENCE, 0, NULL, sizeof(OIDKeyValue)}, + {SEC_ASN1_OBJECT_ID, offsetof(OIDKeyValue, oid), NULL, 0}, + {SEC_ASN1_ANY_CONTENTS, offsetof(OIDKeyValue, value), NULL, 0}, + {0, 0, NULL, 0}}; typedef struct { OIDKeyValue **vals; } OIDKeyValueList; static const SecAsn1Template kSetOfOIDValueTemplate[] = { - { SEC_ASN1_SET_OF, 0, kOIDValueTemplate, sizeof(OIDKeyValueList) }, - { 0, 0, NULL, 0 } - }; + {SEC_ASN1_SET_OF, 0, kOIDValueTemplate, sizeof(OIDKeyValueList)}, + {0, 0, NULL, 0}}; typedef struct { OIDKeyValueList **lists; } OIDKeyValueListSeq; static const SecAsn1Template kSequenceOfSetOfOIDValueTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, kSetOfOIDValueTemplate, sizeof(OIDKeyValueListSeq) }, - { 0, 0, NULL, 0 } - }; + {SEC_ASN1_SEQUENCE_OF, 0, kSetOfOIDValueTemplate, sizeof(OIDKeyValueListSeq)}, + {0, 0, NULL, 0}}; OSStatus err = errSecSuccess; SecAsn1CoderRef coder; @@ -143,7 +140,7 @@ - (NSDictionary *)decodeData:(NSData *)data { // Massage that into a nice dictionary of OID->String pairs. NSMutableDictionary *dict = [NSMutableDictionary dictionary]; OIDKeyValueList *anAttr; - for (NSUInteger i = 0; (anAttr = a.lists[i]); i++) { + for (NSUInteger i = 0; (anAttr = a.lists[i]); ++i) { OIDKeyValue *keyValue = anAttr->vals[0]; // Sanity check @@ -178,7 +175,6 @@ - (NSDictionary *)decodeData:(NSData *)data { return dict; } - /** * Decodes an ASN.1 Object Identifier into a string separated by periods. * See http://msdn.microsoft.com/en-us/library/bb540809(v=vs.85).aspx for @@ -200,11 +196,11 @@ + (NSString *)decodeOIDWithBytes:(unsigned char *)bytes length:(NSUInteger)lengt if (byte & 0x80) { inVariableLengthByte = YES; - NSUInteger a = (NSUInteger) (byte & ~0x80); + NSUInteger a = (NSUInteger)(byte & ~0x80); variableLength = variableLength << 7; variableLength += a; } else if (inVariableLengthByte) { - NSUInteger a = (NSUInteger) (byte & ~0x80); + NSUInteger a = (NSUInteger)(byte & ~0x80); variableLength = variableLength << 7; variableLength += a; inVariableLengthByte = NO; diff --git a/Source/santactl/version/SNTCommandVersion.m b/Source/santactl/version/SNTCommandVersion.m index 6ec0b9b42..d25e7f190 100644 --- a/Source/santactl/version/SNTCommandVersion.m +++ b/Source/santactl/version/SNTCommandVersion.m @@ -48,17 +48,17 @@ + (NSString *)longHelpText { + (void)runWithArguments:(NSArray *)arguments daemonConnection:(SNTXPCConnection *)daemonConn { if ([arguments containsObject:@"--json"]) { NSDictionary *versions = @{ - @"santa-driver": [self santaKextVersion], - @"santad": [self santadVersion], - @"santactl": [self santactlVersion], - @"SantaGUI": [self santaAppVersion], + @"santa-driver" : [self santaKextVersion], + @"santad" : [self santadVersion], + @"santactl" : [self santactlVersion], + @"SantaGUI" : [self santaAppVersion], }; NSData *versionsData = [NSJSONSerialization dataWithJSONObject:versions options:NSJSONWritingPrettyPrinted error:nil]; NSString *versionsStr = [[NSString alloc] initWithData:versionsData encoding:NSUTF8StringEncoding]; - printf("%s\n", [versionsStr UTF8String]); + printf("%s\n", [versionsStr UTF8String]); } else { printf("%-15s | %s\n", "santa-driver", [[self santaKextVersion] UTF8String]); printf("%-15s | %s\n", "santad", [[self santadVersion] UTF8String]); @@ -70,9 +70,8 @@ + (void)runWithArguments:(NSArray *)arguments daemonConnection:(SNTXPCConnection + (NSString *)santaKextVersion { NSDictionary *loadedKexts = CFBridgingRelease( - KextManagerCopyLoadedKextInfo((__bridge CFArrayRef)@[ @(USERCLIENT_ID) ], - (__bridge CFArrayRef)@[ @"CFBundleVersion" ]) - ); + KextManagerCopyLoadedKextInfo((__bridge CFArrayRef) @[ @(USERCLIENT_ID) ], + (__bridge CFArrayRef) @[ @"CFBundleVersion" ])); if (loadedKexts[@(USERCLIENT_ID)][@"CFBundleVersion"]) { return loadedKexts[@(USERCLIENT_ID)][@"CFBundleVersion"]; diff --git a/Source/santad/SNTApplication.m b/Source/santad/SNTApplication.m index 7ab0f927a..9b44b3e1a 100644 --- a/Source/santad/SNTApplication.m +++ b/Source/santad/SNTApplication.m @@ -86,13 +86,12 @@ - (instancetype)init { [[SNTDaemonControlController alloc] initWithDriverManager:_driverManager]; [_controlConnection resume]; - _configFileWatcher = [[SNTFileWatcher alloc] initWithFilePath:kDefaultConfigFilePath - handler:^{ - [[SNTConfigurator configurator] reloadConfigData]; + _configFileWatcher = [[SNTFileWatcher alloc] initWithFilePath:kDefaultConfigFilePath handler:^{ + [[SNTConfigurator configurator] reloadConfigData]; - // Ensure config file remains root:wheel 0644 - chown([kDefaultConfigFilePath fileSystemRepresentation], 0, 0); - chmod([kDefaultConfigFilePath fileSystemRepresentation], 0644); + // Ensure config file remains root:wheel 0644 + chown([kDefaultConfigFilePath fileSystemRepresentation], 0, 0); + chmod([kDefaultConfigFilePath fileSystemRepresentation], 0644); }]; _eventLog = [[SNTEventLog alloc] init]; @@ -130,7 +129,7 @@ - (void)beginListeningForDecisionRequests { } case ACTION_REQUEST_CHECKBW: { dispatch_async(exec_queue, ^{ - [self.execController validateBinaryWithMessage:message]; + [self.execController validateBinaryWithMessage:message]; }); break; } diff --git a/Source/santad/SNTDaemonControlController.m b/Source/santad/SNTDaemonControlController.m index 4aa151842..19ca41575 100644 --- a/Source/santad/SNTDaemonControlController.m +++ b/Source/santad/SNTDaemonControlController.m @@ -52,19 +52,19 @@ - (dispatch_source_t)createSyncTimer { dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)); dispatch_source_set_event_handler(syncTimerQ, ^{ - [self rescheduleSyncSecondsFromNow:600]; + [self rescheduleSyncSecondsFromNow:600]; - if (![[SNTConfigurator configurator] syncBaseURL]) return; - [[SNTConfigurator configurator] setSyncBackOff:NO]; + if (![[SNTConfigurator configurator] syncBaseURL]) return; + [[SNTConfigurator configurator] setSyncBackOff:NO]; - if (fork() == 0) { - // Ensure we have no privileges - if (!DropRootPrivileges()) { - _exit(EPERM); - } - - _exit(execl(kSantaCtlPath, kSantaCtlPath, "sync", "--syslog", NULL)); + if (fork() == 0) { + // Ensure we have no privileges + if (!DropRootPrivileges()) { + _exit(EPERM); } + + _exit(execl(kSantaCtlPath, kSantaCtlPath, "sync", "--syslog", NULL)); + } }); dispatch_resume(syncTimerQ); diff --git a/Source/santad/SNTDatabaseController.m b/Source/santad/SNTDatabaseController.m index 0f4b67a7f..2f87741b4 100644 --- a/Source/santad/SNTDatabaseController.m +++ b/Source/santad/SNTDatabaseController.m @@ -14,8 +14,8 @@ #import "SNTDatabaseController.h" -#include #include +#include #import "SNTEventTable.h" #import "SNTLogging.h" @@ -23,22 +23,24 @@ @implementation SNTDatabaseController -static NSString * const kDatabasePath = @"/var/db/santa"; -static NSString * const kRulesDatabaseName = @"rules.db"; -static NSString * const kEventsDatabaseName = @"events.db"; +static NSString *const kDatabasePath = @"/var/db/santa"; +static NSString *const kRulesDatabaseName = @"rules.db"; +static NSString *const kEventsDatabaseName = @"events.db"; + (SNTEventTable *)eventTable { static FMDatabaseQueue *eventDatabaseQueue = nil; static dispatch_once_t eventDatabaseToken; dispatch_once(&eventDatabaseToken, ^{ - [self createDatabasePath]; - NSString *fullPath = [kDatabasePath stringByAppendingPathComponent:kEventsDatabaseName]; - eventDatabaseQueue = [[FMDatabaseQueue alloc] initWithPath:fullPath]; - chown([fullPath UTF8String], 0, 0); - chmod([fullPath UTF8String], 0600); + [self createDatabasePath]; + NSString *fullPath = [kDatabasePath stringByAppendingPathComponent:kEventsDatabaseName]; + eventDatabaseQueue = [[FMDatabaseQueue alloc] initWithPath:fullPath]; + chown([fullPath UTF8String], 0, 0); + chmod([fullPath UTF8String], 0600); #ifndef DEBUG - [eventDatabaseQueue inDatabase:^(FMDatabase *db) { db.logsErrors = NO; }]; + [eventDatabaseQueue inDatabase:^(FMDatabase *db) { + db.logsErrors = NO; + }]; #endif }); @@ -49,14 +51,16 @@ + (SNTRuleTable *)ruleTable { static FMDatabaseQueue *ruleDatabaseQueue = nil; static dispatch_once_t ruleDatabaseToken; dispatch_once(&ruleDatabaseToken, ^{ - [self createDatabasePath]; - NSString *fullPath = [kDatabasePath stringByAppendingPathComponent:kRulesDatabaseName]; - ruleDatabaseQueue = [[FMDatabaseQueue alloc] initWithPath:fullPath]; - chown([fullPath UTF8String], 0, 0); - chmod([fullPath UTF8String], 0600); + [self createDatabasePath]; + NSString *fullPath = [kDatabasePath stringByAppendingPathComponent:kRulesDatabaseName]; + ruleDatabaseQueue = [[FMDatabaseQueue alloc] initWithPath:fullPath]; + chown([fullPath UTF8String], 0, 0); + chmod([fullPath UTF8String], 0600); #ifndef DEBUG - [ruleDatabaseQueue inDatabase:^(FMDatabase *db) { db.logsErrors = NO; }]; + [ruleDatabaseQueue inDatabase:^(FMDatabase *db) { + db.logsErrors = NO; + }]; #endif }); return [[SNTRuleTable alloc] initWithDatabaseQueue:ruleDatabaseQueue]; diff --git a/Source/santad/SNTDatabaseTable.m b/Source/santad/SNTDatabaseTable.m index 7d24119f0..95507eeef 100644 --- a/Source/santad/SNTDatabaseTable.m +++ b/Source/santad/SNTDatabaseTable.m @@ -56,13 +56,13 @@ - (uint32_t)initializeDatabase:(FMDatabase *)db fromVersion:(uint32_t)version { /// database exists and uses the latest schema. - (void)updateTableSchema { [self inTransaction:^(FMDatabase *db, BOOL *rollback) { - uint32_t currentVersion = [db userVersion]; - uint32_t newVersion = [self initializeDatabase:db fromVersion:currentVersion]; - if (newVersion < 1) return; + uint32_t currentVersion = [db userVersion]; + uint32_t newVersion = [self initializeDatabase:db fromVersion:currentVersion]; + if (newVersion < 1) return; - LOGI(@"Updated %@ from version %d to %d", [self className], currentVersion, newVersion); + LOGI(@"Updated %@ from version %d to %d", [self className], currentVersion, newVersion); - [db setUserVersion:newVersion]; + [db setUserVersion:newVersion]; }]; } diff --git a/Source/santad/SNTDriverManager.m b/Source/santad/SNTDriverManager.m index d97c2d719..adef70285 100644 --- a/Source/santad/SNTDriverManager.m +++ b/Source/santad/SNTDriverManager.m @@ -141,7 +141,6 @@ - (void)listenForRequestsOfType:(santa_queuetype_t)type IOConnectUnmapMemory(self.connection, type, mach_task_self(), address); mach_port_destroy(mach_task_self(), receivePort); - } #pragma mark Outgoing messages @@ -181,8 +180,8 @@ - (uint64_t)cacheCount { } - (BOOL)flushCache { - return IOConnectCallScalarMethod( - self.connection, kSantaUserClientClearCache, 0, 0, 0, 0) == KERN_SUCCESS; + return IOConnectCallScalarMethod(self.connection, + kSantaUserClientClearCache, 0, 0, 0, 0) == KERN_SUCCESS; } @end diff --git a/Source/santad/SNTEventLog.h b/Source/santad/SNTEventLog.h index 97ed902aa..f64a23f2a 100644 --- a/Source/santad/SNTEventLog.h +++ b/Source/santad/SNTEventLog.h @@ -12,7 +12,6 @@ /// See the License for the specific language governing permissions and /// limitations under the License. - #import "SNTKernelCommon.h" @class SNTCachedDecision; diff --git a/Source/santad/SNTEventLog.m b/Source/santad/SNTEventLog.m index 94da269f8..3ef8abab8 100644 --- a/Source/santad/SNTEventLog.m +++ b/Source/santad/SNTEventLog.m @@ -19,8 +19,8 @@ #include #include -#import "SNTCachedDecision.h" #import "MOLCertificate.h" +#import "SNTCachedDecision.h" #import "SNTCommonEnums.h" #import "SNTFileInfo.h" #import "SNTKernelCommon.h" @@ -99,8 +99,8 @@ - (void)logFileModification:(santa_message_t)message { outStr = [outStr stringByAppendingFormat:(@"|pid=%d|ppid=%d|process=%s|processpath=%s|" @"uid=%d|user=%@|gid=%d|group=%@"), - message.pid, message.ppid, message.pname, ppath, - message.uid, user, message.gid, group]; + message.pid, message.ppid, message.pname, ppath, + message.uid, user, message.gid, group]; if (sha256) { outStr = [outStr stringByAppendingFormat:@"|sha256=%@", sha256]; } @@ -122,23 +122,46 @@ - (void)logExecution:(santa_message_t)message withDecision:(SNTCachedDecision *) switch (cd.decision) { case EVENTSTATE_ALLOW_BINARY: - d = @"ALLOW"; r = @"BINARY"; args = [self argsForPid:message.pid]; break; + d = @"ALLOW"; + r = @"BINARY"; + args = [self argsForPid:message.pid]; + break; case EVENTSTATE_ALLOW_CERTIFICATE: - d = @"ALLOW"; r = @"CERTIFICATE"; args = [self argsForPid:message.pid]; break; + d = @"ALLOW"; + r = @"CERTIFICATE"; + args = [self argsForPid:message.pid]; + break; case EVENTSTATE_ALLOW_SCOPE: - d = @"ALLOW"; r = @"SCOPE"; args = [self argsForPid:message.pid]; break; + d = @"ALLOW"; + r = @"SCOPE"; + args = [self argsForPid:message.pid]; + break; case EVENTSTATE_ALLOW_UNKNOWN: - d = @"ALLOW"; r = @"UNKNOWN"; args = [self argsForPid:message.pid]; break; + d = @"ALLOW"; + r = @"UNKNOWN"; + args = [self argsForPid:message.pid]; + break; case EVENTSTATE_BLOCK_BINARY: - d = @"DENY"; r = @"BINARY"; break; + d = @"DENY"; + r = @"BINARY"; + break; case EVENTSTATE_BLOCK_CERTIFICATE: - d = @"DENY"; r = @"CERT"; break; + d = @"DENY"; + r = @"CERT"; + break; case EVENTSTATE_BLOCK_SCOPE: - d = @"DENY"; r = @"SCOPE"; break; + d = @"DENY"; + r = @"SCOPE"; + break; case EVENTSTATE_BLOCK_UNKNOWN: - d = @"DENY"; r = @"UNKNOWN"; break; + d = @"DENY"; + r = @"UNKNOWN"; + break; default: - d = @"ALLOW"; r = @"NOTRUNNING"; args = [self argsForPid:message.pid]; break; + d = @"ALLOW"; + r = @"NOTRUNNING"; + args = [self argsForPid:message.pid]; + break; } outLog = [NSString stringWithFormat:@"action=EXEC|decision=%@|reason=%@", d, r]; @@ -147,17 +170,18 @@ - (void)logExecution:(santa_message_t)message withDecision:(SNTCachedDecision *) outLog = [outLog stringByAppendingFormat:@"|explain=%@", cd.decisionExtra]; } - outLog = [outLog stringByAppendingFormat:@"|sha256=%@|path=%@|args=%@", - cd.sha256, [self sanitizeString:@(message.path)], [self sanitizeString:args]]; + outLog = [outLog stringByAppendingFormat:@"|sha256=%@|path=%@|args=%@", cd.sha256, + [self sanitizeString:@(message.path)], + [self sanitizeString:args]]; if (cd.certSHA256) { - outLog = [outLog stringByAppendingFormat:@"|cert_sha256=%@|cert_cn=%@", - cd.certSHA256, [self sanitizeString:cd.certCommonName]]; + outLog = [outLog stringByAppendingFormat:@"|cert_sha256=%@|cert_cn=%@", cd.certSHA256, + [self sanitizeString:cd.certCommonName]]; } if (cd.quarantineURL) { outLog = [outLog stringByAppendingFormat:@"|quarantine_url=%@", - [self sanitizeString:cd.quarantineURL]]; + [self sanitizeString:cd.quarantineURL]]; } NSString *user, *group; @@ -167,7 +191,8 @@ - (void)logExecution:(santa_message_t)message withDecision:(SNTCachedDecision *) if (gr) group = @(gr->gr_name); outLog = [outLog stringByAppendingFormat:@"|pid=%d|ppid=%d|uid=%d|user=%@|gid=%d|group=%@", - message.pid, message.ppid, message.uid, user, message.gid, group]; + message.pid, message.ppid, message.uid, user, + message.gid, group]; LOGI(@"%@", outLog); } @@ -208,11 +233,10 @@ - (NSString *)argsForPid:(pid_t)pid { memcpy(&argc, argsdatabytes, sizeof(argc)); // Get pointer to beginning of string space - char *cp; - cp = (char *) argsdatabytes + sizeof(argc); + char *cp = (char *)argsdatabytes + sizeof(argc); // Skip over exec_path - for (; cp < &argsdatabytes[size]; cp++) { + for (; cp < &argsdatabytes[size]; ++cp) { if (*cp == '\0') { cp++; break; @@ -220,11 +244,13 @@ - (NSString *)argsForPid:(pid_t)pid { } // Skip trailing NULL bytes - for (; cp < &argsdatabytes[size]; cp++) if (*cp != '\0') break; + for (; cp < &argsdatabytes[size]; ++cp) { + if (*cp != '\0') break; + } // Loop over the argv array, stripping newlines in each arg and putting in a new array. NSMutableArray *args = [NSMutableArray arrayWithCapacity:argc]; - for (int i = 0; i < argc; i++) { + for (int i = 0; i < argc; ++i) { NSString *arg = @(cp); if (arg) [args addObject:arg]; diff --git a/Source/santad/SNTEventTable.m b/Source/santad/SNTEventTable.m index 7f7b0c240..b74de43cd 100644 --- a/Source/santad/SNTEventTable.m +++ b/Source/santad/SNTEventTable.m @@ -86,8 +86,8 @@ - (BOOL)addStoredEvent:(SNTStoredEvent *)event { __block BOOL success = NO; [self inTransaction:^(FMDatabase *db, BOOL *rollback) { - success = [db executeUpdate:@"INSERT INTO 'events' (filesha256, eventdata) VALUES (?, ?)", - event.fileSHA256, eventData]; + success = [db executeUpdate:@"INSERT INTO 'events' (filesha256, eventdata) VALUES (?, ?)", + event.fileSHA256, eventData]; }]; return success; @@ -98,7 +98,7 @@ - (BOOL)addStoredEvent:(SNTStoredEvent *)event { - (NSUInteger)pendingEventsCount { __block NSUInteger eventsPending = 0; [self inDatabase:^(FMDatabase *db) { - eventsPending = [db intForQuery:@"SELECT COUNT(*) FROM events"]; + eventsPending = [db intForQuery:@"SELECT COUNT(*) FROM events"]; }]; return eventsPending; } @@ -107,17 +107,17 @@ - (SNTStoredEvent *)pendingEventForSHA256:(NSString *)sha256 { __block SNTStoredEvent *storedEvent; [self inDatabase:^(FMDatabase *db) { - FMResultSet *rs = - [db executeQuery:@"SELECT * FROM events WHERE filesha256=? LIMIT 1;", sha256]; - - if ([rs next]) { - storedEvent = [self eventFromResultSet:rs]; - if (!storedEvent) { - [db executeUpdate:@"DELETE FROM events WHERE idx=?", [rs objectForColumnName:@"idx"]]; - } + FMResultSet *rs = + [db executeQuery:@"SELECT * FROM events WHERE filesha256=? LIMIT 1;", sha256]; + + if ([rs next]) { + storedEvent = [self eventFromResultSet:rs]; + if (!storedEvent) { + [db executeUpdate:@"DELETE FROM events WHERE idx=?", [rs objectForColumnName:@"idx"]]; } + } - [rs close]; + [rs close]; }]; return storedEvent; @@ -127,18 +127,18 @@ - (NSArray *)pendingEvents { NSMutableArray *pendingEvents = [[NSMutableArray alloc] init]; [self inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT * FROM events"]; - - while ([rs next]) { - id obj = [self eventFromResultSet:rs]; - if (obj) { - [pendingEvents addObject:obj]; - } else { - [db executeUpdate:@"DELETE FROM events WHERE idx=?", [rs objectForColumnName:@"idx"]]; - } + FMResultSet *rs = [db executeQuery:@"SELECT * FROM events"]; + + while ([rs next]) { + id obj = [self eventFromResultSet:rs]; + if (obj) { + [pendingEvents addObject:obj]; + } else { + [db executeUpdate:@"DELETE FROM events WHERE idx=?", [rs objectForColumnName:@"idx"]]; } + } - [rs close]; + [rs close]; }]; return pendingEvents; @@ -153,7 +153,8 @@ - (SNTStoredEvent *)eventFromResultSet:(FMResultSet *)rs { @try { event = [NSKeyedUnarchiver unarchiveObjectWithData:eventData]; event.idx = @([rs intForColumn:@"idx"]); - } @catch (NSException *exception) {} + } @catch (NSException *exception) { + } return event; } @@ -162,7 +163,7 @@ - (SNTStoredEvent *)eventFromResultSet:(FMResultSet *)rs { - (void)deleteEventWithId:(NSNumber *)index { [self inDatabase:^(FMDatabase *db) { - [db executeUpdate:@"DELETE FROM events WHERE idx=?", index]; + [db executeUpdate:@"DELETE FROM events WHERE idx=?", index]; }]; } @@ -171,7 +172,7 @@ - (void)deleteEventsWithIds:(NSArray *)indexes { [self deleteEventWithId:index]; } [self inDatabase:^(FMDatabase *db) { - [db executeUpdate:@"VACUUM"]; + [db executeUpdate:@"VACUUM"]; }]; } diff --git a/Source/santad/SNTExecutionController.m b/Source/santad/SNTExecutionController.m index 391dfa3f2..e6cef44ed 100644 --- a/Source/santad/SNTExecutionController.m +++ b/Source/santad/SNTExecutionController.m @@ -20,9 +20,9 @@ #include "SNTLogging.h" -#import "SNTCachedDecision.h" #import "MOLCertificate.h" #import "MOLCodesignChecker.h" +#import "SNTCachedDecision.h" #import "SNTCommonEnums.h" #import "SNTConfigurator.h" #import "SNTDriverManager.h" @@ -144,7 +144,6 @@ - (void)validateBinaryWithMessage:(santa_message_t)message { if (cd.decision != EVENTSTATE_ALLOW_BINARY && cd.decision != EVENTSTATE_ALLOW_CERTIFICATE && cd.decision != EVENTSTATE_ALLOW_SCOPE) { - SNTStoredEvent *se = [[SNTStoredEvent alloc] init]; se.occurrenceDate = [[NSDate alloc] init]; se.fileSHA256 = cd.sha256; @@ -180,7 +179,7 @@ - (void)validateBinaryWithMessage:(santa_message_t)message { se.quarantineDataURL = binInfo.quarantineDataURL; se.quarantineRefererURL = binInfo.quarantineRefererURL; se.quarantineTimestamp = binInfo.quarantineTimestamp; - se.quarantineAgentBundleID = binInfo.quarantineAgentBundleID; + se.quarantineAgentBundleID = binInfo.quarantineAgentBundleID; [self.eventTable addStoredEvent:se]; diff --git a/Source/santad/SNTRuleTable.m b/Source/santad/SNTRuleTable.m index b8e13bf2f..2f8e24d1c 100644 --- a/Source/santad/SNTRuleTable.m +++ b/Source/santad/SNTRuleTable.m @@ -28,7 +28,6 @@ @interface SNTRuleTable () @implementation SNTRuleTable - (uint32_t)initializeDatabase:(FMDatabase *)db fromVersion:(uint32_t)version { - // Save hashes of the signing certs for launchd and santad self.santadCertSHA = [[[[MOLCodesignChecker alloc] initWithSelf] leafCertificate] SHA256]; self.launchdCertSHA = [[[[MOLCodesignChecker alloc] initWithPID:1] leafCertificate] SHA256]; @@ -37,11 +36,11 @@ - (uint32_t)initializeDatabase:(FMDatabase *)db fromVersion:(uint32_t)version { if (version < 1) { [db executeUpdate:@"CREATE TABLE 'rules' (" - @"'shasum' TEXT NOT NULL, " - @"'state' INTEGER NOT NULL, " - @"'type' INTEGER NOT NULL, " - @"'custommsg' TEXT" - @")"]; + @"'shasum' TEXT NOT NULL, " + @"'state' INTEGER NOT NULL, " + @"'type' INTEGER NOT NULL, " + @"'custommsg' TEXT" + @")"]; [db executeUpdate:@"CREATE VIEW binrules AS SELECT * FROM rules WHERE type=1"]; [db executeUpdate:@"CREATE VIEW certrules AS SELECT * FROM rules WHERE type=2"]; @@ -52,9 +51,9 @@ - (uint32_t)initializeDatabase:(FMDatabase *)db fromVersion:(uint32_t)version { // This helps prevent accidentally denying critical system components while the database // is empty. This 'initial database' will then be cleared on the first successful sync. [db executeUpdate:@"INSERT INTO rules (shasum, state, type) VALUES (?, ?, ?)", - self.santadCertSHA, @(RULESTATE_WHITELIST), @(RULETYPE_CERT)]; + self.santadCertSHA, @(RULESTATE_WHITELIST), @(RULETYPE_CERT)]; [db executeUpdate:@"INSERT INTO rules (shasum, state, type) VALUES (?, ?, ?)", - self.launchdCertSHA, @(RULESTATE_WHITELIST), @(RULETYPE_CERT)]; + self.launchdCertSHA, @(RULESTATE_WHITELIST), @(RULETYPE_CERT)]; newVersion = 1; @@ -77,7 +76,7 @@ - (NSUInteger)ruleCount { - (NSUInteger)binaryRuleCount { __block NSUInteger count = 0; [self inDatabase:^(FMDatabase *db) { - count = [db longForQuery:@"SELECT COUNT(*) FROM binrules"]; + count = [db longForQuery:@"SELECT COUNT(*) FROM binrules"]; }]; return count; } @@ -85,7 +84,7 @@ - (NSUInteger)binaryRuleCount { - (NSUInteger)certificateRuleCount { __block NSUInteger count = 0; [self inDatabase:^(FMDatabase *db) { - count = [db longForQuery:@"SELECT COUNT(*) FROM certrules"]; + count = [db longForQuery:@"SELECT COUNT(*) FROM certrules"]; }]; return count; } @@ -105,11 +104,11 @@ - (SNTRule *)certificateRuleForSHA256:(NSString *)SHA256 { __block SNTRule *rule; [self inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT * FROM certrules WHERE shasum=? LIMIT 1", SHA256]; - if ([rs next]) { - rule = [self ruleFromResultSet:rs]; - } - [rs close]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM certrules WHERE shasum=? LIMIT 1", SHA256]; + if ([rs next]) { + rule = [self ruleFromResultSet:rs]; + } + [rs close]; }]; return rule; @@ -119,11 +118,11 @@ - (SNTRule *)binaryRuleForSHA256:(NSString *)SHA256 { __block SNTRule *rule; [self inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT * FROM binrules WHERE shasum=? LIMIT 1", SHA256]; - if ([rs next]) { - rule = [self ruleFromResultSet:rs]; - } - [rs close]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM binrules WHERE shasum=? LIMIT 1", SHA256]; + if ([rs next]) { + rule = [self ruleFromResultSet:rs]; + } + [rs close]; }]; return rule; @@ -140,47 +139,47 @@ - (BOOL)addRules:(NSArray *)rules cleanSlate:(BOOL)cleanSlate { __block BOOL failed = NO; [self inTransaction:^(FMDatabase *db, BOOL *rollback) { - // Protect rules for santad/launchd certificates. - NSPredicate *p = [NSPredicate predicateWithFormat: - @"(SELF.shasum = %@ OR SELF.shasum = %@) AND SELF.type = %d", - self.santadCertSHA, self.launchdCertSHA, RULETYPE_CERT]; - NSArray *requiredHashes = [rules filteredArrayUsingPredicate:p]; - p = [NSPredicate predicateWithFormat:@"SELF.state == %d", RULESTATE_WHITELIST]; - NSArray *requiredHashesWhitelist = [requiredHashes filteredArrayUsingPredicate:p]; - if ((cleanSlate && requiredHashesWhitelist.count != 2) || - (requiredHashes.count != requiredHashesWhitelist.count)) { - LOGE(@"Received request to remove whitelist for launchd/santad ceritifcates."); + // Protect rules for santad/launchd certificates. + NSPredicate *p = [NSPredicate predicateWithFormat: + @"(SELF.shasum = %@ OR SELF.shasum = %@) AND SELF.type = %d", + self.santadCertSHA, self.launchdCertSHA, RULETYPE_CERT]; + NSArray *requiredHashes = [rules filteredArrayUsingPredicate:p]; + p = [NSPredicate predicateWithFormat:@"SELF.state == %d", RULESTATE_WHITELIST]; + NSArray *requiredHashesWhitelist = [requiredHashes filteredArrayUsingPredicate:p]; + if ((cleanSlate && requiredHashesWhitelist.count != 2) || + (requiredHashes.count != requiredHashesWhitelist.count)) { + LOGE(@"Received request to remove whitelist for launchd/santad ceritifcates."); + *rollback = failed = YES; + return; + } + + if (cleanSlate) { + [db executeUpdate:@"DELETE FROM rules"]; + } + + for (SNTRule *rule in rules) { + if (![rule isKindOfClass:[SNTRule class]] || rule.shasum.length == 0 || + rule.state == RULESTATE_UNKNOWN || rule.type == RULETYPE_UNKNOWN) { *rollback = failed = YES; return; } - if (cleanSlate) { - [db executeUpdate:@"DELETE FROM rules"]; - } - - for (SNTRule *rule in rules) { - if (![rule isKindOfClass:[SNTRule class]] || rule.shasum.length == 0 || - rule.state == RULESTATE_UNKNOWN || rule.type == RULETYPE_UNKNOWN) { + if (rule.state == RULESTATE_REMOVE) { + if (![db executeUpdate:@"DELETE FROM rules WHERE shasum=? AND type=?", + rule.shasum, @(rule.type)]) { *rollback = failed = YES; return; } - - if (rule.state == RULESTATE_REMOVE) { - if (![db executeUpdate:@"DELETE FROM rules WHERE shasum=? AND type=?", - rule.shasum, @(rule.type)]) { - *rollback = failed = YES; - return; - } - } else { - if (![db executeUpdate:@"INSERT OR REPLACE INTO rules " - @"(shasum, state, type, custommsg) " - @"VALUES (?, ?, ?, ?);", - rule.shasum, @(rule.state), @(rule.type), rule.customMsg]) { - *rollback = failed = YES; - return; - } + } else { + if (![db executeUpdate:@"INSERT OR REPLACE INTO rules " + @"(shasum, state, type, custommsg) " + @"VALUES (?, ?, ?, ?);", + rule.shasum, @(rule.state), @(rule.type), rule.customMsg]) { + *rollback = failed = YES; + return; } } + } }]; return !failed; diff --git a/Source/santad/main.m b/Source/santad/main.m index 2cbdd6895..ba3ab6470 100644 --- a/Source/santad/main.m +++ b/Source/santad/main.m @@ -50,7 +50,7 @@ static inline double timeval_to_double(time_value_t tv) { struct mach_task_basic_info taskInfo; mach_msg_type_number_t taskInfoCount = MACH_TASK_BASIC_INFO_COUNT; - while(true) { + while (true) { @autoreleasepool { if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO, (task_info_t)&taskInfo, &taskInfoCount) == KERN_SUCCESS) { diff --git a/Tests/KernelTests/main.m b/Tests/KernelTests/main.m index d16471cb1..aef00eff0 100644 --- a/Tests/KernelTests/main.m +++ b/Tests/KernelTests/main.m @@ -77,8 +77,8 @@ - (NSString *)sha256ForPath:(NSString *)path { error:nil]; CC_SHA256([fData bytes], (unsigned int)[fData length], sha256); char buf[CC_SHA256_DIGEST_LENGTH * 2 + 1]; - for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) { - snprintf(buf + (2*i), 4, "%02x", (unsigned char)sha256[i]); + for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; ++i) { + snprintf(buf + (2 * i), 4, "%02x", (unsigned char)sha256[i]); } buf[CC_SHA256_DIGEST_LENGTH * 2] = '\0'; return @(buf); @@ -262,7 +262,7 @@ - (void)beginListening { TFAILINFO("Error receiving data: %d", kr); } } - } while (IODataQueueWaitForAvailableData(queueMemory, receivePort) == kIOReturnSuccess); + } while (IODataQueueWaitForAvailableData(queueMemory, receivePort) == kIOReturnSuccess); IOConnectUnmapMemory(self.connection, kIODefaultMemoryType, mach_task_self(), address); mach_port_destroy(mach_task_self(), receivePort); @@ -429,10 +429,10 @@ - (void)handlesLotsOfBinaries { const int LIMIT = 12000; - for (int i = 0; i < LIMIT; i++) { + for (int i = 0; i < LIMIT; ++i) { printf("\033[s"); // save cursor position - printf("%d/%i", i+1, LIMIT); + printf("%d/%i", i + 1, LIMIT); NSString *fname = [@"testexe" stringByAppendingFormat:@".%i", i]; [[NSFileManager defaultManager] copyItemAtPath:@"/bin/hostname" toPath:fname error:NULL]; diff --git a/Tests/LogicTests/SNTDERDecoderTest.m b/Tests/LogicTests/SNTDERDecoderTest.m index 634d1f624..7986e289d 100644 --- a/Tests/LogicTests/SNTDERDecoderTest.m +++ b/Tests/LogicTests/SNTDERDecoderTest.m @@ -49,13 +49,13 @@ - (void)testOIDDecoding { NSString *oidStr = [SNTDERDecoder decodeOIDWithBytes:oidBytes1 length:sizeof(oidBytes1)]; XCTAssertEqualObjects(oidStr, @"1.3.6.1.4.1.311.21.20"); - unsigned char oidBytes2[] = {0x2b, 0x06, 0x01, 0x04, 0x01, 0xAB, 0x0E, 0x01, 0x05, 0x2F }; + unsigned char oidBytes2[] = {0x2b, 0x06, 0x01, 0x04, 0x01, 0xAB, 0x0E, 0x01, 0x05, 0x2F}; oidStr = [SNTDERDecoder decodeOIDWithBytes:oidBytes2 length:sizeof(oidBytes2)]; XCTAssertEqualObjects(oidStr, @"1.3.6.1.4.1.5518.1.5.47"); unsigned char oidBytes3[] = {0x56, 0x04, 0x0A}; oidStr = [SNTDERDecoder decodeOIDWithBytes:oidBytes3 length:sizeof(oidBytes3)]; - XCTAssertEqualObjects(oidStr, @"2.6.4.10"); + XCTAssertEqualObjects(oidStr, @"2.6.4.10"); } @end diff --git a/Tests/LogicTests/SNTEventTableTest.m b/Tests/LogicTests/SNTEventTableTest.m index 0d01ef320..0e5bdb533 100644 --- a/Tests/LogicTests/SNTEventTableTest.m +++ b/Tests/LogicTests/SNTEventTableTest.m @@ -88,7 +88,7 @@ - (void)testDeleteEventWithId { - (void)testDeleteEventsWithIds { // Add 50 events to the database - for (int i = 0; i < 50; i++) { + for (int i = 0; i < 50; ++i) { SNTStoredEvent *newEvent = [self createTestEvent]; [self.sut addStoredEvent:newEvent]; } @@ -115,7 +115,7 @@ - (void)testDeleteEventsWithIds { - (void)testDeleteCorruptEvent { [self.dbq inDatabase:^(FMDatabase *db) { - [db executeUpdate:@"INSERT INTO events (filesha256) VALUES ('deadbeef')"]; + [db executeUpdate:@"INSERT INTO events (filesha256) VALUES ('deadbeef')"]; }]; NSArray *events = [self.sut pendingEvents]; @@ -124,11 +124,11 @@ - (void)testDeleteCorruptEvent { } [self.dbq inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT * FROM events WHERE filesha256='deadbeef'"]; - if ([rs next]) { - XCTFail("Bad event was not deleted."); - } - [rs close]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM events WHERE filesha256='deadbeef'"]; + if ([rs next]) { + XCTFail("Bad event was not deleted."); + } + [rs close]; }]; }