### Scan Running Processes for Dylib Vulnerabilities Source: https://context7.com/objective-see/dylibhijackscanner/llms.txt Scans currently running processes for dylib injection vulnerabilities, offering a faster alternative to full filesystem scans. It utilizes `proc_listpids` to get a list of running process IDs, then retrieves the path for each process using `proc_pidpath`. Each unique binary path is then scanned for vulnerabilities, providing a runtime assessment. Results are reported via callbacks as vulnerabilities are detected. ```objective-c // Quick scan mode: analyze only running processes // Faster than full filesystem scan, good for runtime assessment Scanner* scanner = [[Scanner alloc] initWithOptions:@{ KEY_SCANNER_FULL: @NO, // Partial scan (processes only) KEY_SCANNER_WEAK_HIJACKERS: @YES }]; // Internal implementation scans process list: int numberOfProcesses = proc_listpids(PROC_ALL_PIDS, 0, NULL, 0); pid_t* pids = calloc(numberOfProcesses, sizeof(pid_t)); proc_listpids(PROC_ALL_PIDS, 0, pids, numberOfProcesses * sizeof(pid_t)); NSMutableArray* scannedBinaries = [NSMutableArray array]; for (int i = 0; i < numberOfProcesses; i++) { if (pids[i] == 0) continue; char pathBuffer[PROC_PIDPATHINFO_MAXSIZE] = {0}; if (proc_pidpath(pids[i], pathBuffer, sizeof(pathBuffer)) > 0) { NSString* processPath = [NSString stringWithUTF8String:pathBuffer]; // Skip duplicates (same binary may run multiple times) if ([scannedBinaries containsObject:processPath]) continue; [scannedBinaries addObject:processPath]; // Scan each unique binary Binary* binary = [[Binary alloc] initWithPath:processPath]; [scanner scanBinary:binary]; } } free(pids); // Results are reported via callback to AppDelegate as vulnerabilities are found ``` -------------------------------- ### Initialize DHS Scanner with Options (Objective-C) Source: https://context7.com/objective-see/dylibhijackscanner/llms.txt Initializes the DHS scanner with custom configuration options to control scan depth and detection scope. Options like full filesystem scan and weak hijacker detection can be enabled. ```objective-c // Initialize scanner with configuration options NSDictionary* scannerOptions = @{ KEY_SCANNER_FULL: [NSNumber numberWithBool:YES], // Full filesystem scan KEY_SCANNER_WEAK_HIJACKERS: [NSNumber numberWithBool:YES] // Enable weak hijacker detection }; Scanner* scanner = [[Scanner alloc] initWithOptions:scannerOptions]; // Start the scan (runs on background thread) [scanner scan]; // The scan will automatically invoke callbacks to update UI as vulnerabilities are found // Results are added to the main UI table via: // [((AppDelegate*)[[NSApplication sharedApplication] delegate]) addToTable:binary]; ``` -------------------------------- ### Create and Analyze Binary Object (Objective-C) Source: https://context7.com/objective-see/dylibhijackscanner/llms.txt Creates a Binary object to represent an executable file for security analysis. After scanning, it checks for hijacking status and issue types (rpath or weak import) and can export findings to JSON. ```objective-c // Create a binary object for analysis NSString* appPath = @"/Applications/MyApp.app/Contents/MacOS/MyApp"; Binary* binary = [[Binary alloc] initWithPath:appPath]; // After scanning, the binary object contains vulnerability information if (binary.isHijacked) { // Binary has been hijacked if (binary.issueType == ISSUE_TYPE_RPATH) { NSLog(@"Rpath hijack detected: %@", binary.issueItem); // issueItem contains the path to the hijacker dylib } else if (binary.issueType == ISSUE_TYPE_WEAK) { NSLog(@"Weak import hijack detected: %@", binary.issueItem); } } if (binary.isVulnerable) { // Binary is vulnerable but not currently hijacked NSLog(@"Vulnerable binary: %@ could be hijacked via: %@", binary.path, binary.issueItem); } // Export findings to JSON NSString* jsonOutput = [binary toJSON]; // Returns: "binary path": "/path/to/app", "issue": "rpath", "dylib path": "/path/to/dylib" ``` -------------------------------- ### Resolve Dynamic Library Paths Source: https://context7.com/objective-see/dylibhijackscanner/llms.txt Resolves special path tokens (@executable_path, @loader_path, @rpath) to absolute filesystem paths required for dynamic library loading on macOS. It iterates through LC_RPATH entries to find the correct dylib location, essential for accurately assessing dylib vulnerabilities. This process is fundamental for understanding how the dynamic linker locates libraries at runtime. ```objective-c // macOS uses special tokens in dylib paths that need resolution // @executable_path -> directory containing the main executable // @loader_path -> directory containing the binary that loads the dylib // @rpath -> resolved against LC_RPATH entries in order Binary* binary = [[Binary alloc] initWithPath:@"/Applications/MyApp.app/Contents/MacOS/MyApp"]; // Resolve paths automatically during scanning NSString* unresolvedPath = @"@executable_path/../Frameworks/MyFramework.framework/MyFramework"; // Resolution process: // 1. Get binary directory: /Applications/MyApp.app/Contents/MacOS // 2. Remove @executable_path token // 3. Append remainder: ../Frameworks/MyFramework.framework/MyFramework // 4. Standardize to absolute path: /Applications/MyApp.app/Contents/Frameworks/MyFramework.framework/MyFramework // Internal resolution logic (from resolvePath method): NSString* prefix = EXECUTABLE_PATH; // or LOADER_PATH NSString* resolvedPath = [[[binary.path stringByDeletingLastPathComponent] stringByAppendingPathComponent:[unresolvedPath substringFromIndex:[prefix length]]] stringByStandardizingPath]; // For @rpath resolution, scanner tries each LC_RPATH directory in order: NSMutableArray* rpaths = binary.parserInstance.binaryInfo[KEY_LC_RPATHS]; for (NSString* rpath in rpaths) { NSString* candidate = [rpath stringByAppendingPathComponent: ([@"@rpath/MyLib.dylib" substringFromIndex:[@"@rpath" length]])]; if ([[NSFileManager defaultManager] fileExistsAtPath:candidate]) { // This is the dylib that will be loaded break; } } ``` -------------------------------- ### Full Filesystem Binary Scan Source: https://context7.com/objective-see/dylibhijackscanner/llms.txt Performs a system-wide scan of all executable binaries to detect potential dylib hijacking. This comprehensive scan can be time-consuming and involves iterating through the filesystem, checking file executability, and analyzing individual binaries. It skips protected directories and non-executable files. ```objective-c // Full system scan: analyze all binaries on filesystem // Comprehensive but time-consuming Scanner* scanner = [[Scanner alloc] initWithOptions:@{ KEY_SCANNER_FULL: @YES, // Full filesystem scan KEY_SCANNER_WEAK_HIJACKERS: @YES }]; [scanner scan]; // Triggers scanBinariesFileSys method // Internal implementation: NSDirectoryEnumerator* enumerator = [[NSFileManager defaultManager] enumeratorAtURL:[NSURL URLWithString:@"/"] includingPropertiesForKeys:@[NSURLNameKey, NSURLIsDirectoryKey] options:0 errorHandler:^BOOL(NSURL *url, NSError *error) { return YES; // Continue on errors }]; for (NSURL* fileURL in enumerator) { @autoreleasepool { // Check if scan was cancelled if ([[NSThread currentThread] isCancelled]) { [NSThread exit]; } // Skip protected directories (avoid privacy prompts on macOS Mojave+) NSArray* protectedDirs = @[ @"~/Library/Application Support/AddressBook", @"~/Library/Mail", @"~/Library/Messages", @"~/Pictures" ]; // if in protected dir, skip... // Skip non-executable files BOOL isDirectory = NO; if (![[NSFileManager defaultManager] fileExistsAtPath:fileURL.path isDirectory:&isDirectory] || isDirectory) { continue; } // Check if file is executable (i386/x86_64 binary) if (!isURLExecutable(fileURL)) continue; // Scan the binary Binary* binary = [[Binary alloc] initWithPath:fileURL.path]; [scanner scanBinary:binary]; } } ``` -------------------------------- ### Export Scan Results to JSON (Objective-C) Source: https://context7.com/objective-see/dylibhijackscanner/llms.txt Saves scan findings, separating hijacked and vulnerable applications, into a structured JSON file. This Objective-C code iterates through application data, formats it as JSON, and writes it to a specified output file. It handles the JSON structure manually by appending strings and requires an AppDelegate with 'tableContents'. ```objective-c // Export all findings to JSON file // Separates hijacked applications from vulnerable applications AppDelegate* appDelegate = (AppDelegate*)[[NSApplication sharedApplication] delegate]; NSMutableArray* tableContents = appDelegate.tableContents; NSMutableString* output = [NSMutableString string]; // Start JSON structure [output appendString:@"{\"hijacked applications\":["]; // Add all hijacked binaries for (NSUInteger i = 0; i < tableContents.count; i++) { id item = tableContents[i]; // Skip non-binary items (headers, blank rows) if (![item isKindOfClass:[Binary class]]) continue; Binary* binary = (Binary*)item; // Only process hijacked apps if (!binary.isHijacked) break; // Add JSON for this binary [output appendFormat:@"{%@},", [binary toJSON]]; // Produces: {"binary path": "/path/to/app", "issue": "rpath", "dylib path": "/path/to/hijacker"} } // Remove trailing comma if ([output hasSuffix:@","]) { [output deleteCharactersInRange:NSMakeRange([output length]-1, 1)]; } [output appendString:@"],\"vulnerable applications\":["]; // Add all vulnerable binaries for (NSUInteger i = 0; i < tableContents.count; i++) { Binary* binary = tableContents[i]; if (![binary isKindOfClass:[Binary class]]) continue; if (binary.isHijacked) continue; // Skip hijacked, already processed [output appendFormat:@"{%@},", [binary toJSON]]; } if ([output hasSuffix:@","]) { [output deleteCharactersInRange:NSMakeRange([output length]-1, 1)]; } [output appendString:@"] } // Write to file NSString* outputFile = @"/path/to/dhsFindings.txt"; [output writeToFile:outputFile atomically:YES encoding:NSUTF8StringEncoding error:nil]; // Example output: // { // "hijacked applications": [ // {"binary path": "/Applications/App1.app/Contents/MacOS/App1", "issue": "rpath", "dylib path": "/tmp/evil.dylib"} // ], // "vulnerable applications": [ // {"binary path": "/Applications/App2.app/Contents/MacOS/App2", "issue": "weak", "dylib path": "/path/to/missing.dylib"} // ] // } ``` -------------------------------- ### Scan for Rpath Hijacks (Objective-C) Source: https://context7.com/objective-see/dylibhijackscanner/llms.txt Illustrates the internal logic for detecting rpath-based dylib hijacking. It involves parsing load commands to find multiple instances of the same dylib within different @rpath directories, indicating a potential hijack. ```objective-c // The scanner automatically detects rpath hijacks by: // 1. Parsing LC_LOAD_DYLIBS that use @rpath // 2. Resolving against all LC_RPATH directories // 3. Finding duplicates where the first loaded dylib may be malicious // Example scenario that would be detected: // Binary has: @rpath/mylib.dylib // LC_RPATH entries: /tmp/evil, /Applications/MyApp.app/Contents/Frameworks // If /tmp/evil/mylib.dylib exists AND /Applications/MyApp.app/Contents/Frameworks/mylib.dylib exists // This is flagged as a hijack (first path in search order wins) // Internal scanner logic (simplified): NSUInteger dylibCount = 0; NSString* firstFound = nil; for (NSString* rpath in binary.parserInstance.binaryInfo[KEY_LC_RPATHS]) { NSString* resolved = [rpath stringByAppendingPathComponent: [importedDylib substringFromIndex:[RUN_SEARCH_PATH length]]]; if ([[NSFileManager defaultManager] fileExistsAtPath:resolved]) { if (nil == firstFound) firstFound = resolved; dylibCount++; } } if (dylibCount >= 2) { // Verify signatures don't match to confirm hijack binary.isHijacked = YES; binary.issueType = ISSUE_TYPE_RPATH; binary.issueItem = firstFound; // The dylib that gets loaded first } ``` -------------------------------- ### Detect Vulnerable Applications with Dylib Injection Source: https://context7.com/objective-see/dylibhijackscanner/llms.txt Identifies applications vulnerable to dylib injection by checking for missing dylib dependencies, specifically @rpath and weak import vulnerabilities. It analyzes binary imports and checks if required dylibs exist in the specified rpath directories, considering SIP protection and dyld shared cache status. Returns 'YES' if vulnerable, indicating the missing or injectable dylib and the type of weakness (@rpath or weak import). ```objective-c // Scanner checks for rpath vulnerabilities: // - Binary imports @rpath/SomeLib.dylib // - SomeLib.dylib doesn't exist in first LC_RPATH directory // - Attacker could place malicious SomeLib.dylib there // Check if binary is vulnerable to rpath injection Binary* targetBinary = [[Binary alloc] initWithPath:@"/Applications/Target.app/Contents/MacOS/Target"]; // Scanner automatically checks: // 1. All @rpath'd LC_LOAD_DYLIBS // 2. Whether they exist in the first LC_RPATH directory // 3. If directory is not SIP-protected // 4. If dylib is not in dyld shared cache // Example vulnerable scenario: // LC_LOAD_DYLIB: @rpath/CustomFramework.framework/CustomFramework // LC_RPATH: /Applications/Target.app/Contents/Frameworks // If CustomFramework doesn't exist -> VULNERABLE // Scanner also detects weak import vulnerabilities: // LC_LOAD_WEAK_DYLIB: @rpath/OptionalLib.dylib // If OptionalLib.dylib is missing -> VULNERABLE (can be injected) if (targetBinary.isVulnerable) { NSLog(@"Application is vulnerable to dylib injection"); NSLog(@"Missing/injectable dylib: %@", targetBinary.issueItem); if (targetBinary.issueType == ISSUE_TYPE_WEAK) { NSLog(@"Weakness: weakly imported dylib can be injected"); } else if (targetBinary.issueType == ISSUE_TYPE_RPATH) { NSLog(@"Weakness: @rpath can be exploited"); } } ``` -------------------------------- ### Digital Signature Verification for Dylib Hijacks Source: https://context7.com/objective-see/dylibhijackscanner/llms.txt Verifies the digital signatures of binaries and their associated dylibs to detect potential hijackings. It checks if the dylib's signature authority matches the parent binary's, considering security features like hardened runtime and library validation. Unsigned or mismatched signatures can indicate a confirmed hijack. ```objective-c // Scanner checks digital signatures to identify suspicious hijacks // Legitimate dylibs should be signed by same authority as parent binary Binary* binary = [[Binary alloc] initWithPath:@"/Applications/SignedApp.app/Contents/MacOS/SignedApp"]; // Get signing information NSDictionary* binarySigningInfo = signingInfo(binary.path); // Check if binary has valid signature if ([binarySigningInfo[KEY_SIGNATURE_STATUS] intValue] == STATUS_SUCCESS) { // Binary is validly signed // Check security features BOOL hasHardenedRuntime = [binarySigningInfo[KEY_HARDENED_RUNTIME] boolValue]; BOOL hasLibraryValidation = [binarySigningInfo[KEY_LIBRARY_VALIDATION] boolValue]; BOOL isAppleSigned = [binarySigningInfo[KEY_IS_APPLE] boolValue]; // Skip Apple platform binaries (protected by implicit library validation) if (isAppleSigned && !hasLibraryValidation) { // Still protected, skip scan } // Binaries with hardened runtime + library validation are protected if (hasHardenedRuntime && hasLibraryValidation) { // Cannot be hijacked, skip } } // For detected hijacks, verify signatures don't match NSString* suspiciousDylib = @"/tmp/evil/injected.dylib"; NSDictionary* dylibSigningInfo = signingInfo(suspiciousDylib); // Extract signing authorities NSArray* binarySigningAuths = binarySigningInfo[KEY_SIGNING_AUTHORITIES]; NSArray* dylibSigningAuths = dylibSigningInfo[KEY_SIGNING_AUTHORITIES]; // Compare all signing authorities BOOL signaturesMatch = YES; if (binarySigningAuths.count != dylibSigningAuths.count) { signaturesMatch = NO; } else { for (NSUInteger i = 0; i < binarySigningAuths.count; i++) { if (![binarySigningAuths[i] isEqualToString:dylibSigningAuths[i]]) { signaturesMatch = NO; break; } } } if (!signaturesMatch) { // Confirmed hijack: dylib signature doesn't match parent binary NSLog(@"Hijack confirmed: signature mismatch"); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.