Flutter App Security

A comprehensive Flutter security module providing multiple layers of protection against common mobile app attacks.

pub package License: MIT

"Security isn't about being unbreakable — it's about making attacks expensive, difficult, and detectable."

Platform Support

Platform Supported Notes
Android Full support
iOS Full support
macOS Screen protection, code signature verification
Windows Screen protection via SetWindowDisplayAffinity
Web Limited checks (secure context, DevTools detection)
Linux ⚠️ Compiles but no native features yet

Features

Feature Android iOS macOS Windows Web
Root/Jailbreak Detection - - -
Emulator Detection - - -
Debug Mode Detection
App Tampering Detection - -
Hooking Framework Detection - - -
SSL Pinning -
Screenshot Prevention -
Screen Recording Detection - - -
Secure Context Check - - - -
DevTools Detection - - - -

Installation

Add to your pubspec.yaml:

dependencies:
  flutter_app_security: ^1.0.0

Quick Start

import 'package:flutter_app_security/flutter_app_security.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Initialize with production config
  await AppSecurity.instance.initialize(
    SecurityConfig.production(
      onThreatDetected: (result) {
        print('Threats: ${result.detectedThreats}');
      },
    ),
  );

  // Run security checks
  final result = await AppSecurity.instance.runSecurityChecks();

  if (!result.isSecure) {
    // Handle security threats
    print('Security issues detected!');
  }

  runApp(MyApp());
}

Configuration Options

Development Configuration

Use during development to avoid false positives:

await AppSecurity.instance.initialize(
  SecurityConfig.development(),
);

Production Configuration

Maximum security for production builds:

await AppSecurity.instance.initialize(
  SecurityConfig.production(
    certificatePins: [
      'sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=',
    ],
    allowedSignatures: [
      'YOUR_APP_SIGNATURE_SHA256',
    ],
    onThreatDetected: (result) {
      // Send to analytics, block app, etc.
    },
  ),
);

Custom Configuration

Fine-tune individual security checks:

await AppSecurity.instance.initialize(
  SecurityConfig(
    checkRootJailbreak: true,
    checkEmulator: true,
    checkDebugMode: false,  // Allow debug builds
    checkTampering: true,
    enableSslPinning: true,
    preventScreenshot: true,
    preventScreenRecording: true,
    threatAction: SecurityAction.warn,
    certificatePins: ['...'],
  ),
);

Usage Examples

Run Security Checks

final result = await AppSecurity.instance.runSecurityChecks();

if (!result.isSecure) {
  for (final threat in result.detectedThreats) {
    print('Threat: ${threat.name}');
    print('Details: ${result.threatDetails[threat]}');
  }
}

Enable Screen Protection

// Prevent screenshots and screen recording
await AppSecurity.instance.enableScreenSecurity();

// Disable when no longer needed
await AppSecurity.instance.disableScreenSecurity();

Periodic Security Checks

// Check every 5 minutes
AppSecurity.instance.startPeriodicChecks(
  interval: Duration(minutes: 5),
);

// Stop checks
AppSecurity.instance.stopPeriodicChecks();

Wrap Your App with Security

runApp(
  SecureApp(
    child: MyApp(),
    blockedWidget: SecurityBlockedScreen(
      threats: [],
      onRetry: () => AppSecurity.instance.runSecurityChecks(),
    ),
  ),
);

Protect Sensitive Content (Widget)

SecureContent(
  preventScreenshot: true,
  preventRecording: true,
  onRecordingWidget: RecordingDetectedWidget(),
  child: SensitiveDataWidget(),
)

Get Security Info

final info = await AppSecurity.instance.getSecurityInfo();
print('Platform: ${info['device']['platform']}');
print('Is Physical Device: ${info['device']['isPhysicalDevice']}');
print('Is Secure: ${info['isSecure']}');

Security Threat Types

enum SecurityThreat {
  rootedDevice,      // Android device is rooted
  jailbrokenDevice,  // iOS device is jailbroken
  emulator,          // Running on emulator/simulator
  debugMode,         // App is in debug mode
  tamperedApp,       // App has been modified
  hookingFramework,  // Frida, Xposed, etc. detected
  unsafeNetwork,     // Network security issue
  screenCapture,     // Screen capture detected
}

SSL Pinning

Generate certificate pins:

// From PEM certificate
final pin = CertificatePinGenerator.fromPem(pemString);

// From DER bytes
final pin = CertificatePinGenerator.fromBytes(derBytes);

// From file (mobile/desktop only)
final pin = await CertificatePinGenerator.fromFile('/path/to/cert.der');

Use with your HTTP client:

// Returns HttpClient on mobile/desktop, null on web
final client = SslPinning.instance.getSecureHttpClient();

Platform Setup

Android

No additional setup required. The plugin automatically handles:

  • FLAG_SECURE for screenshot prevention
  • Root detection via file checks and build properties
  • Signature verification

iOS

Add to your Info.plist for Cydia URL scheme detection:

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>cydia</string>
</array>

macOS

No additional setup required. The plugin uses:

  • window.sharingType = .none for screen protection
  • codesign verification for tampering detection
  • NSWorkspace for screen recording detection

Windows

No additional setup required. The plugin uses:

  • SetWindowDisplayAffinity for screen capture prevention (Windows 10 2004+)

Web

Security checks are limited on web platform:

  • Debug mode detection via kDebugMode
  • Secure context detection (HTTPS)
  • Basic DevTools open detection
  • All file-based checks return safe defaults
import 'package:flutter_app_security/flutter_app_security_web.dart';

// Web-specific utilities
bool isSecure = FlutterAppSecurityWeb.isSecureContext();
bool isDev = FlutterAppSecurityWeb.isDevEnvironment();
bool devToolsOpen = FlutterAppSecurityWeb.isDevToolsOpen();
Map<String, dynamic> browserInfo = FlutterAppSecurityWeb.getBrowserInfo();

Cross-Platform Usage

The package gracefully handles platform differences:

// Works on all platforms - returns appropriate results
final result = await AppSecurity.instance.runSecurityChecks();

// Mobile-only checks return CheckResult.pass() on desktop/web
// Screen protection silently no-ops on unsupported platforms

For platform-specific logic:

import 'package:flutter_app_security/flutter_app_security.dart';

if (PlatformHelper.isMobile) {
  // Mobile-specific security
} else if (PlatformHelper.isDesktop) {
  // Desktop-specific security
} else if (PlatformHelper.isWeb) {
  // Web-specific security
}

Best Practices

  1. Use production config in release builds only

    final config = kReleaseMode
        ? SecurityConfig.production()
        : SecurityConfig.development();
    
  2. Don't block users immediately - Show warnings first, collect data

  3. Combine with backend validation - Don't rely solely on client-side checks

  4. Update regularly - New jailbreak/root methods appear frequently

  5. Test on real devices - Emulator detection needs real device testing

  6. Handle platform differences - Some features only work on specific platforms

Limitations

  • Security checks can be bypassed by determined attackers
  • Some checks may have false positives on custom ROMs
  • iOS jailbreak detection is less reliable on newer jailbreaks
  • Screen protection can affect legitimate screen mirroring
  • Web platform has very limited security capabilities
  • Linux platform support is minimal

API Reference

Core Classes

Class Description
AppSecurity Main security service singleton
SecurityConfig Configuration options
SecurityCheckResult Result of security checks
CheckResult Individual check result

Security Modules

Module Description
RootDetection Root/jailbreak detection
EmulatorDetection Emulator/simulator detection
DebugDetection Debug mode detection
TamperingDetection App tampering & hooking detection
SslPinning Certificate pinning
ScreenSecurity Screenshot/recording prevention

Widgets

Widget Description
SecureApp Wrapper that blocks on threats
SecureContent Protects specific content
SecurityBlockedScreen Default blocked UI
RecordingDetectedWidget Screen recording warning

Contributing

Contributions are welcome! Please read our contributing guidelines and submit pull requests.

License

MIT License - see LICENSE file for details.

Credits

Inspired by OWASP Mobile Security Testing Guide and the Flutter security community.

Libraries

flutter_app_security
Flutter App Security
flutter_app_security_web