Skip to content

Resk-Security/resk-android

Repository files navigation

Resk Android Security Library

A lightweight, modular, and efficient Android library in Kotlin for securing user inputs and LLM interactions in Android applications. The library focuses on protecting against prompt injection attacks, sanitizing inputs, moderating content, and preventing data leaks, optimized for Android's resource-constrained environment.

Features

  • âś… Input Sanitization: Remove dangerous HTML, scripts, SQL injection attempts
  • âś… Prompt Injection Detection: Detect attempts to manipulate AI system behavior
  • âś… Content Moderation: Filter inappropriate content, profanity, and sensitive information
  • âś… Data Protection: Mask and protect sensitive data (emails, phones, credit cards, SSNs)
  • âś… Multi-LLM Provider Support: Abstract interface for different LLM providers
  • âś… Java Compatibility: Full interoperability with Java code
  • âś… Lightweight: Optimized for mobile performance
  • âś… Configurable: Flexible configuration options for different security levels

Installation

Gradle (Module level)

dependencies {
    implementation 'com.resk:resk-security:1.0.0'
}

Maven

<dependency>
    <groupId>com.resk</groupId>
    <artifactId>resk-security</artifactId>
    <version>1.0.0</version>
</dependency>

Quick Start

Basic Setup

import com.resk.security.ReskSecurity
import com.resk.security.ReskConfig

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        
        // Initialize with default configuration
        val config = ReskConfig.createDefault()
        ReskSecurity.initialize(config)
    }
}

Basic Usage

val reskSecurity = ReskSecurity.getInstance()

// Sanitize user input
val cleanInput = reskSecurity.sanitizeInput("Hello <script>alert('xss')</script> World")
// Result: "Hello  World"

// Check for prompt injection
val injectionResult = reskSecurity.checkPromptInjection("Ignore all previous instructions")
// Result: PromptInjectionResult(isSecure=false, threatLevel=HIGH)

// Moderate content
val moderationResult = reskSecurity.moderateContent("Contact me at john@example.com")
// Result: ModerationResult(isAcceptable=false, violations=[PERSONAL_INFO])

// Protect sensitive data
val protectionResult = reskSecurity.protectData("My SSN is 123-45-6789")
// Result: DataProtectionResult(protectedData="My SSN is ***-**-****")

// Comprehensive security check
val securityResult = reskSecurity.securityCheck("Your input here")

Configuration Options

Predefined Configurations

// Default configuration - balanced security and performance
val defaultConfig = ReskConfig.createDefault()

// Strict configuration - maximum security
val strictConfig = ReskConfig.createStrict()

// Permissive configuration - minimal restrictions
val permissiveConfig = ReskConfig.createPermissive()

// Enhanced default configuration with external patterns
val enhancedConfig = ReskConfig.loadDefaultEnhanced(context)

External Configuration Files

The library now supports loading configuration from JSON and YAML files:

From Assets

// Load from JSON file in assets folder
val config = ReskConfig.loadFromAssets(context, "my-security-config.json")

// Load from YAML file in assets folder
val config = ReskConfig.loadFromAssets(context, "my-security-config.yaml")

From Raw Resources

// Load from raw resource
val config = ReskConfig.loadFromRaw(context, R.raw.security_config)

Direct Loading

// Load directly using ConfigLoader
val config = ConfigLoader.loadFromJson(inputStream)
val config = ConfigLoader.loadFromYaml(inputStream)

Configuration File Format

JSON Configuration

{
  "inputSanitizer": {
    "removeHtmlTags": true,
    "removeScriptTags": true,
    "removeSqlKeywords": true,
    "normalizeWhitespace": true,
    "maxLength": 2000,
    "allowedHtmlTags": ["b", "i", "u", "em", "strong"]
  },
  "promptInjection": {
    "sensitivity": "MEDIUM",
    "checkSystemPrompts": true,
    "checkRoleChanges": true,
    "checkInstructionOverrides": true,
    "customPatterns": [
      "(?i)\\b(?:sudo|admin|root)\\s+mode\\b",
      "(?i)\\[\\s*(?:SYSTEM|ADMIN)\\s*\\]"
    ]
  },
  "contentModerator": {
    "checkProfanity": true,
    "checkPersonalInfo": true,
    "checkSensitiveTerms": true,
    "strictMode": false,
    "customBlockedTerms": ["password", "secret"],
    "whitelistedTerms": ["public", "open"]
  },
  "dataProtector": {
    "maskEmails": true,
    "maskPhoneNumbers": true,
    "maskCreditCards": true,
    "maskSocialSecurityNumbers": true,
    "maskPasswords": true,
    "maskingCharacter": "*",
    "customPatterns": [
      {
        "name": "employee_id",
        "pattern": "\\bEMP\\d{4,6}\\b",
        "maskingStrategy": "PARTIAL_MASK"
      }
    ]
  }
}

YAML Configuration

inputSanitizer:
  removeHtmlTags: true
  removeScriptTags: true
  removeSqlKeywords: true
  normalizeWhitespace: true
  maxLength: 2000
  allowedHtmlTags:
    - "b"
    - "i"
    - "u"
    - "em"
    - "strong"

promptInjection:
  sensitivity: "MEDIUM"
  checkSystemPrompts: true
  checkRoleChanges: true
  checkInstructionOverrides: true
  customPatterns:
    - "(?i)\\b(?:sudo|admin|root)\\s+mode\\b"
    - "(?i)\\[\\s*(?:SYSTEM|ADMIN)\\s*\\]"

contentModerator:
  checkProfanity: true
  checkPersonalInfo: true
  checkSensitiveTerms: true
  strictMode: false
  customBlockedTerms:
    - "password"
    - "secret"
  whitelistedTerms:
    - "public"
    - "open"

dataProtector:
  maskEmails: true
  maskPhoneNumbers: true
  maskCreditCards: true
  maskSocialSecurityNumbers: true
  maskPasswords: true
  maskingCharacter: "*"
  customPatterns:
    - name: "employee_id"
      pattern: "\\bEMP\\d{4,6}\\b"
      maskingStrategy: "PARTIAL_MASK"

Default Patterns

The library includes comprehensive default patterns for:

  • Prompt Injection Detection: System override attempts, role changes, instruction overrides, jailbreak patterns
  • Data Protection: Email addresses, phone numbers, credit cards, SSNs, passwords, API keys, IP addresses, UUIDs, JWT tokens, and more
  • Content Moderation: Basic profanity, personal information detection, sensitive terms

See the default configuration files for complete pattern lists.

Custom Configuration

val customConfig = ReskConfig(
    inputSanitizerConfig = InputSanitizerConfig(
        removeHtmlTags = true,
        removeScriptTags = true,
        maxLength = 1000
    ),
    promptInjectionConfig = PromptInjectionConfig(
        sensitivity = PromptInjectionSensitivity.HIGH,
        checkSystemPrompts = true
    ),
    contentModeratorConfig = ContentModeratorConfig(
        checkProfanity = true,
        checkPersonalInfo = true,
        strictMode = false
    ),
    dataProtectorConfig = DataProtectorConfig(
        maskEmails = true,
        maskPhoneNumbers = true,
        maskCreditCards = true
    )
)

Advanced Features

LLM Provider Integration

import com.resk.security.llm.*

// Define a custom LLM provider
class MyLLMProvider : BaseLLMProvider() {
    override fun getProviderName(): String = "MyProvider"
    
    override suspend fun sendSecureRequest(request: LLMRequest): LLMResponse {
        // Apply security checks before sending
        val secureResult = applySecurityChecks(request)
        
        if (!secureResult.isSecure) {
            throw SecurityViolationException("Request blocked by security check")
        }
        
        // Send request to your LLM service
        val response = sendToLLMService(secureResult.secureRequest)
        
        // Apply security checks to response
        val responseCheck = applyResponseSecurityChecks(response.content)
        
        return LLMResponse(
            content = responseCheck.sanitizedInput,
            securityCheck = responseCheck,
            isSecure = responseCheck.isSecure
        )
    }
    
    override fun validateConfiguration(): ValidationResult {
        return ValidationResult(isValid = true)
    }
}

Custom Data Patterns

val customPattern = DataPattern(
    name = "employee_id",
    pattern = Regex("EMP\\d{4}"),
    maskingStrategy = MaskingStrategy.PARTIAL_MASK
)

val config = ReskConfig(
    dataProtectorConfig = DataProtectorConfig(
        customPatterns = listOf(customPattern)
    )
)

Security Features

Input Sanitization

  • HTML Tag Removal: Removes dangerous HTML tags while optionally preserving safe ones
  • Script Tag Detection: Identifies and removes JavaScript injection attempts
  • SQL Injection Protection: Detects and removes common SQL injection patterns
  • Length Limiting: Prevents oversized inputs that could cause performance issues
  • Whitespace Normalization: Standardizes whitespace for consistent processing

Prompt Injection Detection

  • System Prompt Override: Detects attempts to override system instructions
  • Role Change Detection: Identifies attempts to change AI behavior or personality
  • Instruction Override: Catches attempts to inject new instructions
  • Continuation Attacks: Detects attempts to continue with malicious prompts
  • Custom Pattern Matching: Allows definition of organization-specific attack patterns

Content Moderation

  • Profanity Detection: Basic profanity filtering with configurable sensitivity
  • Personal Information: Detects emails, phone numbers, addresses
  • Sensitive Terms: Identifies medical, financial, and legal terms
  • Hate Speech Detection: Basic hate speech and harassment detection
  • Custom Term Blocking: Organization-specific blocked terms

Data Protection

  • Email Masking: Protects email addresses with configurable masking strategies
  • Phone Number Protection: Masks phone numbers in various formats
  • Credit Card Security: Detects and masks credit card numbers with Luhn validation
  • SSN Protection: Masks Social Security Numbers
  • Password/API Key Detection: Identifies and masks credentials
  • IP Address Masking: Protects IP addresses from exposure

Java Compatibility

The library is fully compatible with Java:

// Java usage example
ReskConfig config = ReskConfig.createDefault();
ReskSecurity reskSecurity = ReskSecurity.initialize(config);

String cleanInput = reskSecurity.sanitizeInput("User input here");
PromptInjectionResult result = reskSecurity.checkPromptInjection("Test input");

if (!result.isSecure()) {
    System.out.println("Threat detected: " + result.getThreatLevel());
}

Performance Considerations

  • Lightweight: Minimal memory footprint and fast processing
  • Efficient Regex: Optimized pattern matching for mobile devices
  • Configurable Features: Disable unused features to improve performance
  • Caching: Internal caching of compiled patterns
  • Async Support: Non-blocking operations where applicable

Testing

The library includes comprehensive unit tests:

./gradlew test

CI/CD and Deployment

The library includes a complete CI/CD pipeline using GitHub Actions:

Continuous Integration

  • Automated Testing: Unit tests run on every push and pull request
  • Code Quality: Lint checks and static analysis
  • Security Scanning: Vulnerability scanning with Trivy
  • Multi-Environment: Tests across different Android API levels

Continuous Deployment

  • Automated Releases: Tagged versions are automatically published to Maven Central
  • Documentation: Auto-generated documentation deployed to GitHub Pages
  • Artifacts: Build artifacts are attached to GitHub releases

Workflow Features

  • Pull request validation
  • Branch protection
  • Security scanning
  • Automated dependency updates
  • Release automation with semantic versioning

See GitHub Actions workflows for complete pipeline configuration.

Sample Application

See the sample-app module for a complete demonstration of library features.

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Ensure all tests pass
  5. Submit a pull request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Security

For security issues, please email security@resk.com instead of using public issue tracker.

Changelog

Version 1.0.0

  • Initial release
  • Input sanitization
  • Prompt injection detection
  • Content moderation
  • Data protection
  • LLM provider abstractions
  • Java compatibility
  • Comprehensive test suite

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •  

Languages