/

Custom Action

Action Type: CUSTOM

Execute your own handler logic when security threats are detected. This is the most flexible action type, enabling advanced threat response scenarios.

Available for: All platforms (Mobile and Desktop)


How It Works

Custom actions provide complete control over threat response:

  1. Receive detailed threat information (type, confidence, metadata)
  2. Analyze threat properties
  3. Execute custom business logic
  4. Send notifications or alerts
  5. Track analytics and monitoring
  6. Continue, suspend, or terminate the application

When to Use

Recommended for:

  • Integration with analytics and monitoring systems
  • Sending notifications to security teams
  • Displaying user-friendly security alerts
  • Conditional responses based on threat severity
  • Implementing complex business-specific logic

Not recommended for:

  • Simple binary responses (use Log, Close, or Erase instead)
  • Performance-critical code paths (handlers should be lightweight)

Threat Information Available

When your custom handler is invoked, you receive a BHMThreatContext object with these properties:

Swift (property syntax):

  • context.moduleType: Protection module that detected the threat (BHMProtectionModuleType)
  • context.threatType: Classification of detected threat (String)
  • context.threatDescription: Human-readable threat description (String)
  • context.detectionResult: Full detection result with confidence and evidence (BHMDetectionResult)
  • context.metadata: Additional context data (Dictionary)

BHMDetectionResult properties:

  • result.isThreat: Boolean indicating if threat was confirmed
  • result.category: Threat classification category (String)
  • result.threatDescription: Detailed description (String)
  • result.confidence: Confidence score 0.0-1.0 (Double)
  • result.evidence: Additional context data (Dictionary)
  • result.timestamp: When the threat was detected (Date)

Configuration

JSON Configuration

JSON
{
  "protections": [
    {
      "type": "DebuggerDetection",
      "action": "log_threat",
      "intervalMs": 2000
    },
    {
      "type": "MemoryDumpDetection",
      "action": "email_alert",
      "intervalMs": 1000
    },
    {
      "type": "TamperingDetection",
      "action": "track_analytics",
      "intervalMs": 3000
    }
  ]
}

Code Examples

Basic Custom Action (Swift)

Register a simple custom action that logs threat information:

Swift
import ByteHideMonitor

BHMMonitor.configure { config in
    config.registerCustomAction("log_threat") { context in
        print("Threat detected: \(context.threatType ?? "unknown")")
        print("Description: \(context.threatDescription ?? "none")")
        if let confidence = context.detectionResult?.confidence {
            print("Confidence: \(Int(confidence * 100))%")
        }
    }

    config.enableProtection(
        .debuggerDetection,
        customAction: "log_threat",
        intervalMs: 2000
    )
}

Basic Custom Action (Objective-C)

OBJC
#import <ByteHideMonitor/ByteHideMonitor.h>

[BHMMonitor configure:^(BHMMonitorConfiguration *config) {
    [config registerCustomAction:@"log_threat"
                         handler:^(BHMThreatContext *context) {
        NSLog(@"Threat detected: %@", context.threatType);
        NSLog(@"Description: %@", context.threatDescription);
        if (context.detectionResult) {
            NSLog(@"Confidence: %d%%", (int)(context.detectionResult.confidence * 100));
        }
    }];

    [config enableProtection:BHMProtectionModuleTypeDebuggerDetection
                customAction:@"log_threat"
                  intervalMs:2000];
}];

Custom Action with User Alert (Swift)

Display an alert to the user with conditional actions:

Swift
import ByteHideMonitor
import UIKit

BHMMonitor.configure { config in
    config.registerCustomAction("show_user_alert") { context in
        DispatchQueue.main.async {
            guard let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
                  let rootVC = scene.windows.first?.rootViewController else { return }

            let confidence = context.detectionResult?.confidence ?? 0
            let message = """
            A security issue was detected:
            \(context.threatDescription ?? "Unknown threat")

            Confidence: \(Int(confidence * 100))%

            Please update your app or contact support.
            """

            let alert = UIAlertController(
                title: "Security Warning",
                message: message,
                preferredStyle: .alert
            )

            alert.addAction(UIAlertAction(title: "Restart App", style: .destructive) { _ in
                exit(1)
            })

            alert.addAction(UIAlertAction(title: "Continue", style: .cancel))

            rootVC.present(alert, animated: true)
        }
    }

    config.enableProtection(
        .debuggerDetection,
        customAction: "show_user_alert",
        intervalMs: 2000
    )
}

Custom Action with Analytics Tracking (Swift)

Track security threats in your analytics system:

Swift
import ByteHideMonitor
import FirebaseAnalytics

BHMMonitor.configure { config in
    config.registerCustomAction("track_analytics") { context in
        var params: [String: Any] = [
            "threat_type": context.threatType ?? "unknown",
            "description": context.threatDescription ?? "",
            "timestamp": Date().timeIntervalSince1970
        ]

        if let result = context.detectionResult {
            params["confidence"] = result.confidence
        }

        // Add evidence if available
        if let evidence = context.detectionResult?.evidence {
            for (key, value) in evidence {
                params["evidence_\(key)"] = "\(value)"
            }
        }

        Analytics.logEvent("security_threat", parameters: params)
    }

    config.enableProtection(
        .tamperingDetection,
        customAction: "track_analytics",
        intervalMs: 3000
    )
}

Conditional Response Based on Threat Type (Swift)

Execute different logic for different threat types:

Swift
import ByteHideMonitor

BHMMonitor.configure { config in
    config.registerCustomAction("conditional_response") { context in
        let confidence = context.detectionResult?.confidence ?? 0

        switch context.threatType {
        case "DEBUGGER_ATTACHED":
            // Debugger detected - immediate exit
            print("Debugger detected: \(context.threatDescription ?? "")")
            exit(1)

        case "JAILBREAK_DETECTED":
            // Jailbreak detected - send alert
            print("Jailbreak detected")
            sendSecurityAlert(context)

        case "MEMORY_DUMP_DETECTED":
            // Memory issue - clear sensitive data first
            print("Memory dump detected - erasing data")
            clearKeychainItems()
            exit(1)

        default:
            // Low confidence threat - just log it
            if confidence < 0.70 {
                print("Low confidence threat logged: \(context.threatDescription ?? "")")
            }
        }
    }

    config.enableProtection(
        .memoryDumpDetection,
        customAction: "conditional_response",
        intervalMs: 2000
    )
}

Multiple Custom Actions (Swift)

Register different handlers for different modules with different behaviors:

Swift
BHMMonitor.configure { config in
    // Action 1: Simple logging
    config.registerCustomAction("log_all_threats") { context in
        let confidence = context.detectionResult?.confidence ?? 0
        print("Threat logged: \(context.threatType ?? "unknown") (\(Int(confidence * 100))%)")
    }

    // Action 2: Alert on high confidence threats
    config.registerCustomAction("alert_high_confidence") { context in
        if context.detectionResult?.confidence ?? 0 >= 0.85 {
            sendSecurityAlert(context)
            exit(1)
        }
    }

    // Action 3: Conditional erase
    config.registerCustomAction("conditional_erase") { context in
        if context.detectionResult?.confidence ?? 0 >= 0.95 {
            clearKeychainItems()
            exit(1)
        }
    }

    // Apply actions to different modules
    config.enableProtection(.memoryDumpDetection, customAction: "log_all_threats", intervalMs: 2000)
    config.enableProtection(.networkTampering, customAction: "alert_high_confidence", intervalMs: 2000)
    config.enableProtection(.processInjection, customAction: "conditional_erase", intervalMs: 2000)
}

Error Handling

Implement safe error handling in your custom actions to prevent handler failures from crashing the application:

Swift
config.registerCustomAction("safe_handler") { context in
    do {
        // Your custom logic here
        try sendSecurityAlert(context)
        try trackAnalytics(context)
    } catch {
        // Fallback behavior - log and exit safely
        print("Handler error: \(error.localizedDescription)")

        // Attempt graceful fallback
        clearKeychainItems()
        exit(1)
    }
}

Best Practices

  • Keep Handlers Fast: Minimize processing in custom actions to avoid blocking threat detection
  • Avoid Sensitive Operations: Don't call risky APIs in threat handlers that might be intercepted
  • Log Everything: Record all threat occurrences for later analysis
  • Test Thoroughly: Test custom actions with realistic threat scenarios
  • Combine Actions: Use multiple custom actions for comprehensive threat response
  • Monitor Performance: Track performance impact of custom action execution
  • Implement Fallbacks: Provide default behavior if custom handlers fail
  • Use Confidence Levels: Implement different behaviors based on threat confidence scores
  • Dispatch to Main Thread: Use DispatchQueue.main.async for any UI operations in handlers
  • Timeout Protection: Keep handler execution time short to prevent timing issues

DetectionResult Properties

When accessing threat properties in custom handlers, use these available properties:

BHMThreatContext:

  • context.moduleType (BHMProtectionModuleType): Which module detected the threat
  • context.threatType (String): Type of threat detected
  • context.threatDescription (String): Detailed description
  • context.detectionResult (BHMDetectionResult): Full detection result
  • context.metadata (Dictionary): Additional context

BHMDetectionResult:

  • result.isThreat (Bool): Confirmed threat status
  • result.category (String): Threat classification
  • result.threatDescription (String): Human-readable description
  • result.confidence (Double): Confidence score (0.0-1.0)
  • result.evidence (Dictionary): Additional evidence data
  • result.timestamp (Date): Detection timestamp

Log Action

Record threats to internal logger

Close Action

Terminate application immediately

Erase Action

Wipe sensitive data before termination

Previous
Erase