/

Library Injection Detection

Protection Module: LibraryInjectionDetection

Available For

This protection module is available for iOS 12 and later. It provides comprehensive detection of dynamically injected libraries and frameworks.

PlatformSupportNote
iOSiOS 12+ required
ArchitectureARM64, ARM64e compatible

How It Works

Library Injection Detection monitors the dynamic linker (DYLD) and loaded libraries to detect injection attempts. It maintains a baseline of legitimate libraries and alerts when unauthorized libraries are loaded.

Detection Techniques

The module employs multiple detection strategies:

  • DYLD Environment Monitoring: Checks DYLD_INSERT_LIBRARIES environment variable
  • Loaded Library Enumeration: Uses _dyld_image_count and _dyld_get_image_name to enumerate loaded libraries
  • Baseline Comparison: Compares current loaded libraries against known legitimate baseline
  • Known Injector Detection: Identifies signatures of Frida, Substrate, Cycript, fishhook, and Substitute
  • System Library Validation: Verifies legitimate libraries from /usr/lib/ and /System/Library/
  • Dynamic Linker API Monitoring: Tracks dynamic linker operations
  • New Library Detection: Identifies injected libraries added after baseline establishment

Known Malicious Libraries Detected:

  • Frida (libfrida-gadget, frida-gadget)
  • Substrate (CydiaSubstrate, libsubstrate)
  • Cycript (Cycript.framework)
  • fishhook (libhook, hooking libraries)
  • Substitute (libsubstitute)

Confidence Metrics:

  • Known injectors: 0.95
  • Suspicious library patterns: 0.85-0.90
  • Anomalous load patterns: 0.80-0.88

Default Interval: Varies based on detection intensity

JSON Configuration

JSON
{
  "protections": [
    {
      "type": "LibraryInjectionDetection",
      "action": "close",
      "intervalMs": 60000
    }
  ]
}

Code-Based Configuration

Swift

Swift
import ByteHideMonitor

BHMMonitor.configure { config in
    config.enableProtection(.libraryInjectionDetection, action: .close, intervalMs: 60000)
}

Objective-C

OBJC
#import <ByteHideMonitor/ByteHideMonitor.h>

[BHMMonitor configure:^(BHMMonitorConfiguration *config) {
    [config enableProtection:BHMProtectionModuleTypeLibraryInjectionDetection
                      action:BHMActionTypeClose
                  intervalMs:60000];
}];

Available Actions

ActionBehaviorRecommended For
CloseTerminate application immediatelyProduction apps with critical IP
LogRecord incident and continueDevelopment, analytics
EraseSecurely delete data then terminateFinancial, healthcare apps
CustomExecute custom handlerEnterprise integrations
NoneDetect only, no actionTesting configurations

See Actions for detailed action documentation.

When to Use

Enable Library Injection Detection if:

  • Your app handles sensitive data and needs to prevent reverse engineering
  • You want to block code injection frameworks (Frida, Substrate, Cycript)
  • You're deploying production applications with proprietary logic
  • You need to prevent runtime modification of your application
  • You want to stop attackers from intercepting function calls or modifying behavior
  • You need to comply with security standards that require injection prevention
  • You're building enterprise or financial applications

Consider using custom actions to implement detailed logging or security event tracking.

Code Examples

Swift - Basic Configuration

Swift
import ByteHideMonitor

class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        BHMMonitor.configure { config in
            config.enableProtection(
                .libraryInjectionDetection,
                action: .close,
                intervalMs: 60000
            )
        }
        return true
    }
}

Swift - Custom Action with Detailed Logging

Swift
BHMMonitor.configure { config in
    config.registerCustomAction("injection-handler") { context in
        let threatType = context.threatType
        let description = context.threatDescription
        let metadata = context.metadata

        // Log injection attempt
        print("Library Injection Detected: \(description)")
        print("Threat Type: \(threatType)")

        // Extract injection details
        if let injectionInfo = metadata?["injectionDetails"] as? [String: Any] {
            print("Detected Library: \(injectionInfo["libraryName"] ?? "unknown")")
            print("Injection Method: \(injectionInfo["detectionMethod"] ?? "unknown")")
            print("Confidence: \(injectionInfo["confidence"] ?? 0.0)")
        }

        // Extract loaded libraries
        if let loadedLibs = metadata?["loadedLibraries"] as? [String] {
            print("Total Loaded Libraries: \(loadedLibs.count)")
            loadedLibs.forEach { lib in
                print("  - \(lib)")
            }
        }

        // Log to security event system
        SecurityEvents.logInjectionDetection(
            libraryName: metadata?["injectionDetails"]?["libraryName"] as? String ?? "unknown",
            method: metadata?["injectionDetails"]?["detectionMethod"] as? String ?? "unknown",
            confidence: metadata?["injectionDetails"]?["confidence"] as? Double ?? 0.0
        )

        // Trigger app-level security response
        if let confidence = metadata?["injectionDetails"]?["confidence"] as? Double, confidence > 0.9 {
            // High confidence - immediate termination is warranted
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                UIApplication.shared.terminate(with: 0)
            }
        }
    }

    config.enableProtection(
        .libraryInjectionDetection,
        customAction: "injection-handler",
        intervalMs: 60000
    )
}

Objective-C

OBJC
#import <ByteHideMonitor/ByteHideMonitor.h>

[BHMMonitor configure:^(BHMMonitorConfiguration *config) {
    [config registerCustomAction:@"injection-handler" handler:^(BHMThreatContext *context) {
        NSString *threatType = context.threatType;
        NSString *description = context.threatDescription;
        NSDictionary *metadata = context.metadata;

        NSLog(@"Library Injection Detected: %@", description);
        NSLog(@"Threat Type: %@", threatType);

        NSDictionary *injectionInfo = metadata[@"injectionDetails"];
        if (injectionInfo) {
            NSLog(@"Detected Library: %@", injectionInfo[@"libraryName"]);
            NSLog(@"Injection Method: %@", injectionInfo[@"detectionMethod"]);
            NSLog(@"Confidence: %@", injectionInfo[@"confidence"]);
        }

        NSArray *loadedLibs = metadata[@"loadedLibraries"];
        if (loadedLibs) {
            NSLog(@"Total Loaded Libraries: %lu", (unsigned long)loadedLibs.count);
            for (NSString *lib in loadedLibs) {
                NSLog(@"  - %@", lib);
            }
        }

        // Log to security system
        [SecurityEvents logInjectionDetectionWithLibraryName:injectionInfo[@"libraryName"]
                                                      method:injectionInfo[@"detectionMethod"]
                                                  confidence:[injectionInfo[@"confidence"] doubleValue]];
    }];

    [config enableProtection:BHMProtectionModuleTypeLibraryInjectionDetection
                customAction:@"injection-handler"
                  intervalMs:60000];
}];

Platform Compatibility

ComponentiOS 12iOS 13+iOS 16+Notes
DYLD MonitoringCore detection mechanism
Library EnumerationDYLD API based
Known Injector DetectionSignature-based detection
System Library ValidationBaseline comparison

Performance Impact

Library Injection Detection has moderate performance impact:

  • CPU Usage: 1-2% per check cycle
  • Memory Overhead: ~4-6 MB for library enumeration and baseline storage
  • Check Latency: 200-500ms per detection cycle
  • Background Impact: Moderate - library loading is monitored

To optimize performance:

  • Increase intervalMs to 120000 (2 minutes) for less frequent checks
  • Use .none action during development for detection-only mode
  • Consider running checks less frequently if latency is a concern

Threat Detection Details

When library injection is detected, the threat context includes:

JSON
{
  "moduleType": "LibraryInjectionDetection",
  "threatType": "MaliciousLibraryInjected",
  "threatDescription": "Frida injection framework detected in loaded libraries",
  "detectionResult": {
    "injectedLibrary": "libfrida-gadget.dylib",
    "detectionMethod": "LibraryEnumeration",
    "injectionVector": "DYLD_INSERT_LIBRARIES",
    "confidence": 0.95
  },
  "metadata": {
    "confidence": 0.95,
    "injectionDetails": {
      "libraryName": "libfrida-gadget.dylib",
      "detectionMethod": "KnownInjectorSignature",
      "injectionVector": "DYLD_INSERT_LIBRARIES"
    },
    "loadedLibraries": [
      "/usr/lib/libSystem.B.dylib",
      "/usr/lib/libobjc.A.dylib",
      "/usr/lib/libfrida-gadget.dylib"
    ],
    "timestamp": "2024-03-15T10:30:45Z"
  }
}

Next Steps

Previous
Process Injection