freeRASP for React Native

repository·master·Indexed 41 days ago

https://github.com/talsec/free-rasp-reactnative

A security plugin providing Runtime App Self Protection (RASP) for React Native apps on Android and iOS. It detects and prevents threats such as rooting/jailbreaking, hooking frameworks (Frida, LSPosed), UI automation attacks (Appium), and bootloader compromises. Version 5.2.1 includes features for screen capture blocking, malware detection on Android, and a `useFreeRasp` hook for easy integration.

Tokens
5.4K
Snippets
20
Records
24
Agent score
51%

What's inside freeRASP

  1. Overview of freeRASP for React Native

    master

    freeRASP for React Native is a mobile in-app protection and security monitoring plugin designed for Runtime App Self Protection (RASP) and application shielding. It provides detection and prevention mechanisms for several security threats, including:

    • Root/Jailbreak detection: Identifies compromised environments (e.g., Magisk, KernelSU, checkra1n, Dopamine).
    • Bootloader status: Detects unlocked or compromised bootloaders.
    • Hooking frameworks: Detects tools like Frida, LSPosed, or Shadow.
    • UI Automation: Detects driven-input attacks from tools like Appium.
    • Installation integrity: Detects untrusted installation methods.
    • Data protection: Protects against App Data Migration attacks.

    It is a unified solution that works across mobile platforms without dependency on external web services, ensuring low latency and avoiding additional points of failure.

  2. Use freeMalwareDetection for Android security

    master

    For Android developers looking to enhance security beyond standard RASP features, freeMalwareDetection can be used to scan for malicious or suspicious applications. It identifies apps with suspicious package names, hashes, or dangerous permissions using various blacklists and security policies.

    Note: This is a separate feature/repository. After integrating freeRASP, you should visit the freeMalwareDetection repository for specific implementation details.

  3. Integrate freeRASP into a React Native project

    master

    To integrate freeRASP into your React Native application, you must follow the official step-by-step instructions provided in the Integration Guide. Because the setup involves both open-source and binary components, following the specific platform-based instructions is critical for a successful implementation.

    Detailed instructions can be found at the Official Integration Guide.

  4. Configure autolinking for freerasp-react-native

    master

    When developing or using the library in a monorepo or a specific project structure, you can use react-native.config.js to manually specify the root path for freerasp-react-native to ensure autolinking works correctly. This is particularly useful if the package is located in a parent directory relative to the example project.

    const path = require('path');
    const pak = require('../package.json');
    
    module.exports = {
      dependencies: {
        [pak.name]: {
          root: path.join(__dirname, '..'),
        },
      },
    };
  5. Configure TalsecAndroidConfig

    master

    Android-specific configuration for freeRASP. It defines the app's identity and security parameters for the Android environment.

    Key properties:

    • packageName: The unique package name of your Android application.
    • certificateHashes: A list of valid certificate hashes for your app.
    • supportedAlternativeStores: Optional list of alternative stores that are considered trusted.
    • suspiciousAppDetectionConfig: Configuration for detecting malicious or suspicious apps on the device.
    type TalsecAndroidConfig = {
      packageName: string;
      certificateHashes: string[];
      supportedAlternativeStores?: string[];
      suspiciousAppDetectionConfig?: SuspiciousAppDetectionConfig;
    };
  6. Configure SuspiciousAppDetectionConfig

    master

    Defines how freeRASP scans for and identifies suspicious applications on the device.

    Key properties:

    • packageNames: Specific package names to flag.
    • hashes: Specific app hashes to flag.
    • requestedPermissions: Arrays of permissions that, if requested by an app, mark it as suspicious.
    • grantedPermissions: Arrays of permissions that, if granted to an app, mark it as suspicious.
    • scanScope: Defines the depth and type of scan to perform.
    • reasonMode: Determines the strictness of detection ('ALL' or 'HIGHEST_CONFIDENCE').
    type SuspiciousAppDetectionConfig = {
      packageNames?: string[];
      hashes?: string[];
      requestedPermissions?: string[][];
      grantedPermissions?: string[][];
      scanScope: ScanScope;
      reasonMode: ReasonMode;
    };
  7. Configure TalsecIosConfig

    master

    iOS-specific configuration for freeRASP. It defines the app's identity for the iOS environment.

    Key properties:

    • appBundleId: The unique bundle identifier for your iOS application.
    • appTeamId: Your Apple Developer Team ID.
    type TalsecIosConfig = {
      appBundleId: string;
      appTeamId: string;
    };
  8. Configure Metro for peerDependency resolution in the example project

    master

    The metro.config.js in the example/ directory is configured to prevent multiple versions of peer dependencies from being loaded. It achieves this by blacklisting the peer dependency versions located in the project root's node_modules and aliasing them to the versions installed within the example/node_modules folder. This ensures that only one instance of each peer dependency is used during the Metro bundling process.

    const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');
    const path = require('path');
    const blacklist = require('metro-config/src/defaults/exclusionList');
    const escape = require('escape-string-regexp');
    const pak = require('../package.json');
    
    const root = path.resolve(__dirname, '..');
    
    const modules = Object.keys({
      ...pak.peerDependencies,
    });
    
    const config = {
      watchFolders: [root],
    
      resolver: {
        blacklistRE: blacklist(
          modules.map(
            (m) =>
              new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`)
          )
        ),
    
        extraNodeModules: modules.reduce((acc, name) => {
          acc[name] = path.join(__dirname, 'node_modules', name);
          return acc;
        }, {}),
      },
    };
    
    module.exports = mergeConfig(getDefaultConfig(__dirname), config);
  9. Configure freeRASP React Native plugin settings

    master

    The PluginConfigType interface allows you to configure platform-specific build properties for the freeRASP React Native plugin. You can provide configuration for both ios and android within the main configuration object.

    const config: PluginConfigType = {
      ios: {
        useSpm: true
      },
      android: {
        minSdkVersion: 24,
        R8Version: '8.0.0'
      }
    };
  10. Configure TalsecConfig

    master

    The TalsecConfig object is the primary configuration interface for initializing freeRASP. It allows you to define platform-specific settings, security behaviors, and contact information for threat reporting.

    Key properties:

    • watcherMail: (Required) The email address used for reporting/monitoring.
    • isProd: Boolean indicating if the app is in production mode.
    • killOnBypass: If true, the app will terminate when a security bypass is detected.
    • androidConfig: Platform-specific settings for Android.
    • iosConfig: Platform-specific settings for iOS.
    type TalsecConfig = {
      androidConfig?: TalsecAndroidConfig;
      iosConfig?: TalsecIosConfig;
      watcherMail: string;
      isProd?: boolean;
      killOnBypass?: boolean;
    };
  11. Integrate freeRASP using the useFreeRasp hook

    master

    The useFreeRasp hook is the primary way to integrate freeRASP into a React Native component. It handles the initialization of the RASP engine, sets up threat listeners, and manages the execution state listener.

    When the hook is mounted, it:

    1. Sets up threat event listeners based on the provided actions.
    2. Optionally sets up a RASP execution state listener.
    3. Starts the freeRASP engine using the provided config.

    If talsecStart fails to return the expected 'freeRASP started' string, it triggers onInvalidCallback(). On unmount, the hook automatically removes the threat and execution state listeners to prevent memory leaks.

    import { useFreeRasp } from 'freerasp-react-native';
    
    // Inside your component
    useFreeRasp(
      {
        // TalsecConfig object
        applicationId: 'YOUR_APP_ID',
        callback: (error) => console.log(error),
        // ... other config properties
      },
      {
        // ThreatEventActions
        onRootDetected: () => console.log('Root detected!'),
        onDebuggerDetected: () => console.log('Debugger detected!'),
        // ... other threat actions
      },
      {
        // Optional: RaspExecutionStateEventActions
        onStateChanged: (state) => console.log('State changed:', state),
      }
    );
  12. Define ThreatEventActions callbacks

    master

    The ThreatEventActions type defines the callback functions that are triggered when specific security threats or environmental risks are detected. You should implement these to decide how your app responds to threats (e.g., logging, alerting the user, or terminating the session).

    Common threat categories include:

    • malware: Triggered when suspicious apps are detected. Receives an array of SuspiciousAppInfo.
    • debug: Triggered when a debugger is attached.
    • simulator: Triggered when running on an emulator/simulator.
    • appIntegrity: Triggered when app integrity is compromised.
    • adbEnabled: Triggered when ADB is enabled on Android.
    • screenshot / screenRecording: Triggered when screen capture is detected.
    • root / bootloader: Triggered by device compromise indicators.
    • locationSpoofing / timeSpoofing: Triggered by environmental manipulation.
    type ThreatEventActions = {
      privilegedAccess?: () => any;
      debug?: () => any;
      simulator?: () => any;
      appIntegrity?: () => any;
      unofficialStore?: () => any;
      hooks?: () => any;
      deviceBinding?: () => any;
      deviceID?: () => any;
      passcode?: () => any;
      secureHardwareNotAvailable?: () => any;
      obfuscationIssues?: () => any;
      devMode?: () => any;
      systemVPN?: () => any;
      malware?: (suspiciousApps: SuspiciousAppInfo[]) => any;
      adbEnabled?: () => any;
      screenshot?: () => any;
      screenRecording?: () => any;
      multiInstance?: () => any;
      timeSpoofing?: () => any;
      locationSpoofing?: () => any;
      unsecureWifi?: () => any;
      automation?: () => any;
      bootloader?: () => any;
    };