/

Keychain Integrity Detection

Protection Module: KeychainIntegrityDetection

Available For

This protection module is available for iOS 12 and later. It provides comprehensive keychain integrity verification and certificate validation.

PlatformSupportNote
iOSiOS 12+ required
FrameworkSecurity framework required

How It Works

Keychain Integrity Detection monitors the iOS Keychain for signs of tampering, unauthorized modifications, and certificate injection. It validates the integrity of stored certificates, keys, and sensitive data against expected baselines.

Detection Techniques

The module employs the following detection strategies:

  • Certificate Count Anomaly Detection: Monitors certificate count changes and detects unexpected additions
  • Self-Signed Certificate Detection: Identifies suspicious self-signed certificates in trust store
  • Keychain Accessibility Verification: Validates keychain item accessibility attributes
  • Keychain Database Integrity: Checks for signs of keychain corruption or tampering
  • MITM Certificate Detection: Identifies proxy certificates and intercepting CA certificates
  • Trust Store Validation: Validates system and custom trust store integrity
  • Certificate Chain Verification: Ensures certificate chains remain valid and complete

Confidence Metrics:

  • Self-signed certificate detection: 0.90
  • Unexpected certificate addition: 0.88
  • Trust store modification: 0.92
  • Certificate chain anomaly: 0.85

Default Interval: 120 seconds

JSON Configuration

JSON
{
  "protections": [
    {
      "type": "KeychainIntegrityDetection",
      "action": "erase",
      "intervalMs": 120000
    }
  ]
}

Code-Based Configuration

Swift

Swift
import ByteHideMonitor

BHMMonitor.configure { config in
    config.enableProtection(.keychainIntegrityDetection, action: .erase, intervalMs: 120000)
}

Objective-C

OBJC
#import <ByteHideMonitor/ByteHideMonitor.h>

[BHMMonitor configure:^(BHMMonitorConfiguration *config) {
    [config enableProtection:BHMProtectionModuleTypeKeychainIntegrityDetection
                      action:BHMActionTypeErase
                  intervalMs:120000];
}];

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 Keychain Integrity Detection if:

  • Your app stores sensitive credentials or encryption keys
  • You need to prevent MITM attacks and certificate injection
  • You're building banking, payment, or financial applications
  • You need to protect encrypted data and security credentials
  • You want to detect proxy software and intercepting tools
  • You're complying with financial industry security standards
  • You need to protect against enterprise network proxies
  • You want to validate SSL/TLS certificate integrity

Consider using .erase action to securely delete sensitive data when tampering is detected.

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(
                .keychainIntegrityDetection,
                action: .erase,
                intervalMs: 120000  // Check every 2 minutes
            )
        }
        return true
    }
}

Swift - Custom Action with Certificate Analysis

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

        // Log keychain tampering detection
        print("Keychain Integrity Violation: \(description)")
        print("Threat Type: \(threatType)")

        // Extract certificate details
        if let certInfo = metadata?["certificateDetails"] as? [String: Any] {
            print("Certificate Count: \(certInfo["certificateCount"] ?? 0)")
            print("Self-Signed Detected: \(certInfo["selfSignedDetected"] ?? false)")
            print("Anomaly Type: \(certInfo["anomalyType"] ?? "unknown")")
        }

        // Analyze MITM indicators
        if let mitmIndicators = metadata?["mitmIndicators"] as? [String: Any] {
            print("Proxy Certificate Detected: \(mitmIndicators["proxyDetected"] ?? false)")
            print("Intercepting CA: \(mitmIndicators["interceptingCA"] ?? "none")")
        }

        // Perform secure data erasure
        let credentialManager = CredentialManager.shared
        credentialManager.securelyEraseAllCredentials()

        // Notify user
        DispatchQueue.main.async {
            let alert = UIAlertController(
                title: "Security Alert",
                message: "Keychain tampering detected. Credentials have been erased.",
                preferredStyle: .alert
            )
            alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in
                // Force re-login
                self.presentLoginScreen()
            })
            self.window?.rootViewController?.present(alert, animated: true)
        }

        // Log to security audit trail
        SecurityAudit.logKeychainTampering(
            threatType: threatType,
            certificateCount: metadata?["certificateDetails"]?["certificateCount"] as? Int ?? 0,
            confidence: metadata?["confidence"] as? Double ?? 0.0
        )
    }

    config.enableProtection(
        .keychainIntegrityDetection,
        customAction: "keychain-handler",
        intervalMs: 120000
    )
}

private func presentLoginScreen() {
    // Implement re-authentication logic
}

Objective-C

OBJC
#import <ByteHideMonitor/ByteHideMonitor.h>

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

        NSLog(@"Keychain Integrity Violation: %@", description);
        NSLog(@"Threat Type: %@", threatType);

        NSDictionary *certInfo = metadata[@"certificateDetails"];
        if (certInfo) {
            NSLog(@"Certificate Count: %@", certInfo[@"certificateCount"]);
            NSLog(@"Self-Signed Detected: %@", certInfo[@"selfSignedDetected"]);
            NSLog(@"Anomaly Type: %@", certInfo[@"anomalyType"]);
        }

        NSDictionary *mitmIndicators = metadata[@"mitmIndicators"];
        if (mitmIndicators) {
            NSLog(@"Proxy Certificate Detected: %@", mitmIndicators[@"proxyDetected"]);
            NSLog(@"Intercepting CA: %@", mitmIndicators[@"interceptingCA"]);
        }

        CredentialManager *credentialManager = [CredentialManager shared];
        [credentialManager securelyEraseAllCredentials];

        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertController *alert = [UIAlertController
                alertControllerWithTitle:@"Security Alert"
                message:@"Keychain tampering detected. Credentials have been erased."
                preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK"
                style:UIAlertActionStyleDefault
                handler:^(UIAlertAction *action) {
                    [self presentLoginScreen];
                }];
            [alert addAction:okAction];

            [self.window.rootViewController presentViewController:alert animated:YES completion:nil];
        });

        [SecurityAudit logKeychainTamperingWithThreatType:threatType
                                          certificateCount:[certInfo[@"certificateCount"] intValue]
                                              confidence:[metadata[@"confidence"] doubleValue]];
    }];

    [config enableProtection:BHMProtectionModuleTypeKeychainIntegrityDetection
                customAction:@"keychain-handler"
                  intervalMs:120000];
}];

- (void)presentLoginScreen {
    // Implement re-authentication logic
}

Platform Compatibility

ComponentiOS 12iOS 13+iOS 16+Notes
Certificate ValidationFull support across all versions
Trust Store MonitoringSystem and custom trust validation
Self-Signed DetectionCertificate chain analysis
MITM DetectionProxy and intercepting CA detection

Performance Impact

Keychain Integrity Detection has moderate performance impact:

  • CPU Usage: 1-2% per check cycle
  • Memory Overhead: ~5-8 MB for certificate enumeration and analysis
  • Check Latency: 300-600ms per detection cycle
  • Background Impact: Moderate - comprehensive validation required

To optimize performance:

  • Increase intervalMs to 300000 (5 minutes) for less frequent checks in production
  • Use .none action during development for detection-only mode
  • Consider caching certificate baseline to reduce per-check overhead

Threat Detection Details

When keychain tampering is detected, the threat context includes:

JSON
{
  "moduleType": "KeychainIntegrityDetection",
  "threatType": "CertificateInjectionDetected",
  "threatDescription": "Unauthorized self-signed certificate added to keychain trust store",
  "detectionResult": {
    "certificateCount": 45,
    "expectedCount": 32,
    "selfSignedCount": 5,
    "expectedSelfSignedCount": 0,
    "confidence": 0.9
  },
  "metadata": {
    "confidence": 0.9,
    "certificateDetails": {
      "certificateCount": 45,
      "expectedCertificateCount": 32,
      "selfSignedDetected": true,
      "anomalyType": "UnexpectedCertificateAddition"
    },
    "mitmIndicators": {
      "proxyDetected": true,
      "interceptingCA": "Charles Proxy CA",
      "certificateIssuer": "CN=Charles Proxy, OU=Charles Proxy, O=Charles Proxy, C=US"
    },
    "timestamp": "2024-03-15T10:30:45Z"
  }
}

Next Steps

Previous
Network Tampering