Name | trigdroid JSON |
Version |
2.0.0
JSON |
| download |
home_page | None |
Summary | Android Sandbox Payload Trigger Framework for Security Research |
upload_time | 2025-08-21 07:32:21 |
maintainer | None |
docs_url | None |
author | None |
requires_python | >=3.9 |
license | MIT License
Copyright (c) 2025 FKIE-CAD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. |
keywords |
android
frida
malware-analysis
mobile-security
penetration-testing
reverse-engineering
security
|
VCS |
 |
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
# TrigDroid π€
**Android Sandbox Payload Trigger Framework for Security Research**
[](https://www.python.org/downloads/)
[](LICENSE)
[]()
[]()
TrigDroid is a modern Android security testing framework designed to trigger payloads in potentially malicious Android applications through sophisticated environmental manipulation. Built for security researchers, malware analysts, and penetration testers, it provides both a powerful command-line interface and a flexible Python API. It is part of the Android Sandbox Sandroid.
## π― Key Features
- **π Payload Trigger Detection**: Sophisticated environmental manipulation to trigger hidden malicious behaviors
- **π± Multi-Device Support**: Works with physical devices and emulators
- **π§ Dual Interface**: Both CLI and Python API for maximum flexibility
- **β‘ Frida Integration**: Advanced runtime instrumentation with TypeScript hooks
- **π Network Manipulation**: WiFi, mobile data, and Bluetooth state changes
- **π Sensor Simulation**: Accelerometer, gyroscope, light, pressure, and more
- **π Battery Simulation**: Dynamic battery level and charging state changes
- **π Comprehensive Reporting**: Detailed test results with timing and metrics
- **ποΈ Modern Architecture**: Built with SOLID principles and type safety
## π Quick Start
### Installation
```bash
# Install TrigDroid with full features
pip install trigdroid[full]
# Install minimal version
pip install trigdroid
# Install with specific features
pip install trigdroid[frida] # Just Frida support
pip install trigdroid[dev] # Development tools
```
### Prerequisites
- **Python 3.9+**
- **Android Debug Bridge (ADB)**
- **Android device or emulator** with USB debugging enabled
- **Node.js** (optional, for TypeScript Frida hooks)
### Basic Usage
```bash
# Test an Android app with basic payload triggers
trigdroid -p com.example.app
# Advanced testing with sensor manipulation
trigdroid -p com.suspicious.app --acceleration 8 --battery 3 --wifi
# List available Android devices
trigdroid devices
# Get detailed app information
trigdroid info com.example.app
```
## π Command Line Interface
### Core Commands
```bash
# Basic app analysis
trigdroid -p <package_name>
# Advanced options
trigdroid -p com.example.app \
--acceleration 5 \ # Sensor elaborateness (0-10)
--battery 3 \ # Battery rotation level (0-4)
--wifi \ # Enable WiFi state changes
--data \ # Enable mobile data changes
--frida \ # Enable Frida hooks
--timeout 600 # Test timeout in seconds
```
### Device Management
```bash
# List all connected devices
trigdroid devices
# Get detailed device information
trigdroid devices --verbose
# Test specific device
trigdroid -p com.example.app -d emulator-5554
```
### Configuration Files
```bash
# Create configuration template
trigdroid --create-config default
# Use configuration file
trigdroid test-config config.yaml
```
### Example Configuration (config.yaml)
```yaml
package: "com.example.app"
acceleration: 5
sensors:
- accelerometer
- gyroscope
- light
network_states:
- wifi
- data
battery_rotation: 3
frida_hooks: true
timeout: 300
verbose: true
```
## π Python API
### Simple Usage
```python
from trigdroid import quick_test
# Quick test with default settings
result = quick_test("com.example.app")
print(f"Test successful: {result.success}")
```
### Advanced Usage
```python
from trigdroid import TrigDroidAPI, TestConfiguration
# Create detailed configuration
config = TestConfiguration(
package="com.suspicious.app",
acceleration=8, # High sensor activity
sensors=["accelerometer", "gyroscope", "light"],
network_states=["wifi", "data"], # Network state changes
battery_rotation=3, # Battery level simulation
frida_hooks=True, # Enable runtime instrumentation
timeout=600, # 10 minute timeout
verbose=True
)
# Run comprehensive test
with TrigDroidAPI() as trigdroid:
trigdroid.configure(config)
result = trigdroid.run_tests()
# Analyze results
if result.success:
print(f"β
Test completed in {result.duration_seconds:.1f}s")
print(f"π Tests run: {result.total_tests}")
print(f"β
Passed: {result.passed_tests}")
print(f"β Failed: {result.failed_tests}")
else:
print(f"β Test failed: {result.error}")
# Check for suspicious behavior
if result.app_crashed:
print("β οΈ App crashed during testing")
if result.frida_errors:
print(f"π Frida instrumentation issues: {result.frida_errors}")
# Access detailed metrics
print(f"π± Sensor tests: {len(result.sensor_tests_executed)}")
print(f"π Network changes: {len(result.network_state_changes)}")
print(f"π Background time: {result.app_background_time:.1f}s")
```
### Device Management API
```python
from trigdroid import DeviceManager, scan_devices
# Scan for available devices
devices = scan_devices()
for device in devices:
print(f"Device: {device['id']} ({device['status']})")
# Advanced device management
manager = DeviceManager()
device = manager.connect_to_device("emulator-5554")
if device:
print(f"Connected to: {device.device_id}")
info = device.get_device_info()
print(f"Model: {info.get('model', 'Unknown')}")
print(f"Android: {info.get('version', 'Unknown')}")
```
### Environment Validation
```python
from trigdroid.api.quick_start import validate_environment, setup_environment
# Check if environment is ready
status = validate_environment()
if all(status.values()):
print("π Environment is ready!")
else:
print("β Issues found:")
for check, result in status.items():
if not result:
print(f" β’ {check}")
# Automatically setup environment
if setup_environment():
print("β
Environment setup complete")
```
## π§ Advanced Features
### Sensor Manipulation
TrigDroid can simulate various Android sensors to trigger environment-dependent payloads:
- **Accelerometer**: Motion detection triggers
- **Gyroscope**: Rotation-based activations
- **Light Sensor**: Ambient light conditions
- **Pressure**: Atmospheric pressure changes
- **Magnetometer**: Magnetic field variations
- **Proximity**: Near/far object detection
```bash
# Fine-tuned sensor testing
trigdroid -p com.example.app \
--acceleration 7 \
--gyroscope 5 \
--light 3 \
--pressure 4
```
### Network State Manipulation
Simulate different connectivity scenarios:
```bash
# Test with network state changes
trigdroid -p com.example.app --wifi --data --bluetooth
```
### Frida Runtime Instrumentation
TrigDroid includes sophisticated Frida hooks written in TypeScript:
- **Method interception**: Hook critical Android APIs
- **Parameter modification**: Alter method arguments and return values
- **Behavior monitoring**: Track app interactions with system APIs
- **Anti-analysis detection**: Identify evasion techniques
### Battery and System Simulation
```bash
# Simulate battery level changes and system states
trigdroid -p com.example.app \
--battery 4 \ # Maximum battery simulation
--background-time 30 \ # 30 seconds in background
--min-runtime 5 # Minimum 5 minutes runtime
```
## π Understanding Results
### Test Result Structure
```python
# Example result analysis
result = api.run_tests()
# Basic status
print(f"Success: {result.success}")
print(f"Phase: {result.phase}") # setup, execution, teardown
print(f"Duration: {result.duration_seconds}s")
# Test statistics
print(f"Total tests: {result.total_tests}")
print(f"Success rate: {result.success_rate:.1f}%")
# App behavior analysis
print(f"App started: {result.app_started}")
print(f"App crashed: {result.app_crashed}")
print(f"Background time: {result.app_background_time}s")
# Instrumentation results
print(f"Frida hooks loaded: {result.frida_hooks_loaded}")
print(f"Frida hooks active: {result.frida_hooks_active}")
# Sensor test results
for sensor, changed in result.sensor_values_changed.items():
print(f"Sensor {sensor}: {changed} value changes")
# Export results
result_dict = result.to_dict()
summary = result.summary() # Human-readable summary
```
### Interpreting Security Findings
**π Suspicious Indicators:**
- App crashes during sensor manipulation
- Unexpected network activity during state changes
- Frida hook detection or evasion attempts
- Unusual battery usage patterns
- Background behavior changes
**β
Normal Behavior:**
- Consistent app performance across all tests
- No crashes or errors
- Predictable sensor responses
- Standard network usage patterns
## π οΈ Development and Integration
### Third-Party Project Integration
```python
# In your security analysis tool
from trigdroid import TrigDroidAPI, TestConfiguration
def analyze_apk(package_name: str) -> dict:
"""Analyze an APK for malicious behavior."""
config = TestConfiguration(
package=package_name,
acceleration=8, # High intensity testing
timeout=600,
frida_hooks=True
)
with TrigDroidAPI() as trigdroid:
result = trigdroid.run_tests()
return {
"malicious": not result.success,
"confidence": result.success_rate,
"indicators": {
"crashed": result.app_crashed,
"evasion_detected": len(result.frida_errors) > 0,
"suspicious_network": len(result.network_state_changes) > 5
},
"report": result.summary()
}
# Usage
analysis = analyze_apk("com.suspicious.app")
if analysis["malicious"]:
print(f"β οΈ Malicious behavior detected (confidence: {analysis['confidence']:.1f}%)")
```
### CI/CD Integration
```yaml
# .github/workflows/security-scan.yml
name: Android Security Scan
on: [push, pull_request]
jobs:
security-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
- name: Install TrigDroid
run: pip install trigdroid[frida]
- name: Setup Android Emulator
uses: reactivecircus/android-emulator-runner@v2
with:
api-level: 29
script: |
adb devices
trigdroid devices
- name: Security Analysis
run: |
trigdroid -p com.example.testapp \
--acceleration 5 \
--timeout 300 \
--frida
```
## π Security Considerations
**β οΈ Important**: TrigDroid is designed for **defensive security research** and **malware analysis** only.
### Ethical Usage Guidelines
- β
**Authorized Testing**: Only test applications you own or have explicit permission to analyze
- β
**Research Purposes**: Use for academic research, security analysis, and malware detection
- β
**Controlled Environment**: Run tests in isolated environments or sandboxes
- β **No Malicious Use**: Do not use to enhance or create malicious capabilities
- β **No Unauthorized Testing**: Do not test third-party applications without permission
### Privacy and Legal Compliance
- Ensure compliance with local laws and regulations
- Respect application privacy policies and terms of service
- Use appropriate data handling and retention practices
- Consider ethical implications of security research
## π Troubleshooting
### Common Issues
**Device Not Found**
```bash
# Check ADB connection
adb devices
# Restart ADB server
adb kill-server && adb start-server
# Enable USB debugging on device
# Developer options β USB debugging
```
**Frida Hooks Fail to Load**
```bash
# Check Frida installation
python -c "import frida; print(frida.__version__)"
# Reinstall Frida
pip install --upgrade frida frida-tools
# Check device architecture
adb shell getprop ro.product.cpu.abi
```
**TypeScript Compilation Errors**
```bash
# Check Node.js installation
node --version && npm --version
# Rebuild TypeScript hooks
cd frida-hooks
rm -rf node_modules dist
npm install && npm run build
```
**Permission Errors**
```bash
# Grant app permissions manually
adb shell pm grant com.example.app android.permission.READ_PHONE_STATE
# Use TrigDroid's permission management
trigdroid -p com.example.app --grant-permission android.permission.CAMERA
```
### Getting Help
- **Documentation**: Full documentation at [docs.trigdroid.org](https://docs.trigdroid.org)
- **Issues**: Report bugs at [GitHub Issues](https://github.com/trigdroid/trigdroid/issues)
- **Discussions**: Join the community at [GitHub Discussions](https://github.com/trigdroid/trigdroid/discussions)
## π€ Contributing
We welcome contributions from the security research community!
```bash
# Development setup
git clone https://github.com/trigdroid/trigdroid.git
cd trigdroid
pip install -e ".[dev]"
# Run tests
pytest tests/
# Code quality checks
black src/ tests/
mypy src/
ruff check src/ tests/
```
See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed contribution guidelines.
## π License
TrigDroid is released under the [MIT License](LICENSE). See LICENSE file for details.
## π οΈ Development Guide
### Modern Architecture Overview
TrigDroid has been completely refactored following **SOLID principles** with a clean dual-layer architecture:
```
βββ src/ # π New Refactored Code (SOLID Architecture)
β βββ trigdroid/ # Modern Public API Layer (lowercase)
β β βββ api/ # External interface with context managers
β β β βββ main.py # TrigDroidAPI class
β β β βββ config.py # Type-safe TestConfiguration
β β β βββ results.py # Comprehensive TestResult classes
β β β βββ devices.py # Device management wrapper
β β β βββ runners.py # Test runner wrapper
β β β βββ quick_start.py # Convenience functions
β β βββ cli/ # Rich CLI interface using Click
β β β βββ main.py # Modern CLI with subcommands
β β βββ core/ # Core utilities and enums
β β β βββ enums.py # Type-safe enumerations
β β β βββ cleanup.py # Resource management
β β βββ exceptions.py # Exception hierarchy
β βββ TrigDroid_Infrastructure/ # ποΈ Infrastructure Layer (SOLID)
β βββ interfaces/ # Protocol-based abstractions
β β βββ __init__.py # ILogger, ITestRunner, IAndroidDevice, etc.
β βββ infrastructure/ # Dependency injection + implementations
β β βββ dependency_injection.py # DI container
β β βββ configuration.py # Config providers
β β βββ logging.py # Logger implementations
β β βββ android.py # Device management
β βββ application/ # Application orchestration
β β βββ orchestrator.py # Main workflow coordinator
β βββ test_runners/ # Test execution implementations
βββ src/ # ποΈ Legacy Code (Original Implementation)
β βββ TrigDroid/ # Legacy TrigDroid (preserved for compatibility)
β βββ logger/ # Original logging utilities
β βββ interaction/ # Legacy UI components
β βββ utils/ # Legacy utility functions
β βββ frida/ # Legacy JavaScript hooks
β βββ ... # Other legacy components
βββ frida-hooks/ # π§ TypeScript Frida Hooks (New)
β βββ main.ts # Hook entry point
β βββ hooks/ # Individual hook modules
β β βββ android-sensors.ts
β β βββ android-build.ts
β βββ types.ts # TypeScript type definitions
β βββ utils.ts # Common hook utilities
β βββ package.json # Node.js build configuration
β βββ tsconfig.json # TypeScript compiler settings
βββ scripts/ # π Build and installation scripts
β βββ build.py # Cross-platform build script
β βββ install.sh # Automated installation
βββ pyproject.toml # Modern Python packaging (PEP 621)
βββ Makefile # Development workflow commands
```
### SOLID Principles Implementation
#### **1. Single Responsibility Principle**
Each class has one reason to change:
- `AndroidDevice`: Only handles device operations
- `StandardLogger`: Only handles logging
- `SensorTestRunner`: Only executes sensor tests
#### **2. Open/Closed Principle**
Extend functionality without modifying existing code:
```python
# Add new test runner without changing existing ones
class CustomTestRunner(TestRunnerBase):
def can_run(self, test_type: str) -> bool:
return test_type == "custom"
def _execute_internal(self, context: ITestContext) -> TestResult:
# Custom test logic
return TestResult.SUCCESS
# Register in DI container
container.register_transient(ITestRunner, CustomTestRunner, "custom")
```
#### **3. Liskov Substitution Principle**
All implementations follow their interfaces:
```python
# Any ILogger implementation works seamlessly
logger: ILogger = StandardLogger() # or FilteredLogger()
logger.info("Test message") # Works the same way
```
#### **4. Interface Segregation Principle**
Small, focused interfaces instead of large monolithic ones:
```python
class ILogger(Protocol):
def debug(self, message: str) -> None: ...
def info(self, message: str) -> None: ...
class IConfigurationProvider(Protocol):
def get_value(self, key: str) -> ConfigValue: ...
def set_value(self, key: str, value: ConfigValue) -> None: ...
```
#### **5. Dependency Inversion Principle**
Depend on abstractions, inject dependencies:
```python
class SensorTestRunner(TestRunnerBase):
def __init__(self, logger: ILogger, device: IAndroidDevice):
super().__init__(logger)
self._device = device # Injected dependency
```
### Development Environment Setup
#### **Quick Development Setup**
```bash
# 1. Clone and setup development environment
git clone https://github.com/trigdroid/trigdroid.git
cd trigdroid
# 2. Use our automated installer
./scripts/install.sh --mode dev
# 3. Alternative: Manual setup
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -e ".[full,dev,test,docs]"
# 4. Build TypeScript hooks
cd frida-hooks
npm install && npm run build
cd ..
# 5. Verify installation
trigdroid --version
pytest tests/ -v
```
#### **Development Workflow Commands**
```bash
# Development commands (see Makefile)
make setup-dev-env # Initial environment setup
make dev-install # Install in development mode
make build # Build all components (Python + TypeScript)
# Code quality
make format # Auto-format with black + isort
make lint # Type checking with mypy + ruff
make check # Run all quality checks
make pre-commit # Format + lint + fast tests
# Testing
make test # All tests
make test-unit # Unit tests only
make test-integration # Integration tests
make test-fast # Skip slow tests
make coverage # Generate coverage report
# Build and distribution
make package # Build wheel/sdist
make hooks # Build TypeScript hooks only
make clean # Clean build artifacts
```
### Adding New Features
#### **1. Create New Test Runner**
```python
# src2/TrigDroid_Infrastructure/test_runners/custom_test_runner.py
from ..interfaces import ITestRunner, ITestContext, TestResult, TestRunnerBase
class CustomTestRunner(TestRunnerBase):
"""Example custom test runner."""
def can_run(self, test_type: str) -> bool:
return test_type == "custom"
def _execute_internal(self, context: ITestContext) -> TestResult:
# Implement your test logic
self._logger.info("Running custom test")
# Access dependencies through context
device = context.device
config = context.config
package = context.package_name
# Your test implementation
success = self._run_custom_test(device, package)
return TestResult.SUCCESS if success else TestResult.FAILURE
def _run_custom_test(self, device, package) -> bool:
# Custom test implementation
return True
# Register in dependency_injection.py
container.register_transient(ITestRunner, CustomTestRunner, "custom")
```
#### **2. Add New Configuration Provider**
```python
# src2/TrigDroid_Infrastructure/infrastructure/configuration.py
class DatabaseConfigProvider(ConfigurationProviderBase):
"""Load configuration from database."""
def _load_configuration(self) -> Dict[str, ConfigValue]:
# Load from database
return {"custom_setting": "value"}
# Register in configure_container()
container.register_transient(IConfigurationProvider, DatabaseConfigProvider, "database")
```
#### **3. Create TypeScript Frida Hook**
```typescript
// frida-hooks/hooks/custom-hook.ts
import { HookManager } from '../utils';
export class CustomHook extends HookManager {
public hookCustomAPI(): void {
const SomeClass = Java.use("com.example.SomeClass");
SomeClass.someMethod.implementation = function(...args) {
console.log("[TrigDroid] Custom hook triggered");
this.logToChangelog("SomeClass.someMethod", "original", "hooked");
// Call original method
return this.someMethod.apply(this, args);
};
}
}
// Add to main.ts
import { CustomHook } from './hooks/custom-hook';
function main() {
const customHook = new CustomHook();
customHook.hookCustomAPI();
}
```
### TypeScript Hook Development
#### **Building Hooks**
```bash
# Build hooks automatically during pip install
pip install -e .
# Manual hook building
cd frida-hooks
npm install # Install dependencies
npm run build # Compile TypeScript to JavaScript
npm run watch # Watch mode for development
# Using make
make hooks # Build hooks only
```
#### **Hook Development Patterns**
```typescript
// frida-hooks/hooks/android-example.ts
import { AndroidSensorType } from '../types';
import { HookUtils } from '../utils';
export class AndroidExampleHook {
private hookUtils: HookUtils;
constructor() {
this.hookUtils = new HookUtils();
}
public hookSensorManager(): void {
try {
const SensorManager = Java.use("android.hardware.SensorManager");
SensorManager.getDefaultSensor.implementation = function(type) {
const originalSensor = this.getDefaultSensor(type);
// Log the hook for debugging
this.hookUtils.logHookExecution("SensorManager.getDefaultSensor", {
sensorType: type,
timestamp: Date.now()
});
// Record change in changelog
this.hookUtils.writeToChangelog(
"SensorManager.getDefaultSensor",
"original_behavior",
"hooked_behavior",
`Sensor type ${type} intercepted`
);
return originalSensor;
};
} catch (error) {
console.error(`[TrigDroid] Hook failed: ${error}`);
}
}
}
```
### Dependency Injection Usage
#### **Registering Services**
```python
# In configure_container()
from .my_service import MyService
# Singleton (same instance every time)
container.register_singleton(IMyService, MyService)
# Transient (new instance every time)
container.register_transient(IMyService, MyService)
# Factory function
container.register_singleton(IMyService, lambda: MyService(config="custom"))
# Specific instance
container.register_instance(IMyService, my_service_instance)
```
#### **Resolving Dependencies**
```python
# Method 1: Through container
container = configure_container()
logger = container.resolve(ILogger)
# Method 2: Service Locator (global access)
ServiceLocator.set_container(container)
logger = ServiceLocator.get_service(ILogger)
# Method 3: Constructor injection
@inject(logger=ILogger, device=IAndroidDevice)
class MyTestRunner:
def __init__(self, logger: ILogger, device: IAndroidDevice):
self._logger = logger
self._device = device
```
### Code Quality Standards
#### **Type Safety**
```python
# Use type hints everywhere
def process_config(config: TestConfiguration) -> TestResult:
return TestResult.SUCCESS
# Use protocols for interfaces
class IMyService(Protocol):
def do_something(self, value: str) -> bool: ...
# Use enums for constants
class TestPhase(Enum):
SETUP = "setup"
EXECUTION = "execution"
TEARDOWN = "teardown"
```
#### **Error Handling**
```python
# Proper exception hierarchy
class TrigDroidException(Exception):
"""Base exception for TrigDroid."""
pass
class DeviceConnectionError(TrigDroidException):
"""Device connection failed."""
pass
# Use try/catch with specific exceptions
try:
device.connect()
except DeviceConnectionError as e:
logger.error(f"Failed to connect: {e}")
return TestResult.FAILURE
```
#### **Logging Best Practices**
```python
# Use structured logging
logger.info("Test started", extra={
"package": package_name,
"phase": "setup",
"timestamp": time.time()
})
# Use appropriate log levels
logger.debug("Detailed debugging info") # Development only
logger.info("Important user information") # Normal operation
logger.warning("Something might be wrong") # Potential issues
logger.error("Something failed") # Errors that don't stop execution
logger.critical("System cannot continue") # Fatal errors
```
### Testing Framework
#### **Unit Tests**
```python
# tests/unit/test_sensor_runner.py
import pytest
from unittest.mock import Mock
from TrigDroid_Infrastructure.test_runners import SensorTestRunner
from TrigDroid_Infrastructure.interfaces import ILogger, ITestContext, TestResult
def test_sensor_runner_success():
# Arrange
mock_logger = Mock(spec=ILogger)
mock_context = Mock(spec=ITestContext)
runner = SensorTestRunner(mock_logger)
# Act
result = runner.execute(mock_context)
# Assert
assert result == TestResult.SUCCESS
mock_logger.info.assert_called()
```
#### **Integration Tests**
```python
# tests/integration/test_full_workflow.py
@pytest.mark.integration
@pytest.mark.requires_device
def test_full_testing_workflow(test_device):
"""Test complete workflow with real device."""
config = TestConfiguration(
package="com.example.testapp",
acceleration=3,
timeout=60
)
with TrigDroidAPI() as api:
api.configure(config)
api.set_device(test_device.device_id)
result = api.run_tests()
assert result.success
assert result.total_tests > 0
```
### Performance Optimization
#### **Fast Development Cycle**
```bash
# Skip TypeScript build during development
SKIP_HOOKS=1 pip install -e .
# Run only fast tests
make test-fast
# Use parallel testing
pytest -n auto tests/
# Quick format and lint check
make pre-commit
```
#### **Build Optimization**
```bash
# Build only what changed
make hooks-if-changed
# Use cached dependencies
pip install --cache-dir ~/.cache/pip -e .
# Parallel hook compilation
cd frida-hooks && npm run build:parallel
```
### Contributing Guidelines
#### **Code Standards**
- **Readable**: Code should read like well-written prose
- **Self-documenting**: Use clear variable and function names
- **Consistent**: Follow established patterns
- **Simple**: Prefer simple solutions over clever ones
- **DRY**: Extract common functionality
- **YAGNI**: Don't over-engineer
#### **Pull Request Process**
```bash
# 1. Development workflow
git checkout -b feature/new-feature
make dev-install
make pre-commit # Format + lint + fast tests
# 2. Before committing
make test # Full test suite
make build # Ensure everything builds
make check # Final quality check
# 3. Create pull request
git push origin feature/new-feature
# Open PR with detailed description
```
#### **Code Review Checklist**
- [ ] Follows SOLID principles
- [ ] Has proper type annotations
- [ ] Includes unit tests (>90% coverage)
- [ ] Updated documentation if needed
- [ ] No hardcoded values or magic numbers
- [ ] Proper error handling
- [ ] TypeScript hooks built successfully
- [ ] All quality checks pass
### Debugging and Troubleshooting
#### **Development Issues**
```bash
# TypeScript compilation fails
cd frida-hooks
rm -rf node_modules dist
npm install && npm run build
# Python import errors
pip uninstall trigdroid
pip install -e ".[full]"
# Dependency injection issues
# Check container registration in configure_container()
container.has_service(IMyService) # Should return True
# Test runner not found
# Verify registration with correct name
container.resolve(ITestRunner, "my_runner")
```
#### **Runtime Debugging**
```python
# Enable debug logging
import logging
logging.basicConfig(level=logging.DEBUG)
# Use dependency injection debug mode
container = configure_container()
if container.has_service(IMyService):
service = container.resolve(IMyService)
# Check service registration
print(f"Registered services: {list(container._services.keys())}")
```
This development guide provides comprehensive information for contributing to and extending TrigDroid's modern architecture.
## π Acknowledgments
- Built on the foundation of the [Evadroid](https://github.com/evadroid/evadroid) project
- Powered by [Frida](https://frida.re/) dynamic instrumentation toolkit
- Uses [Click](https://click.palletsprojects.com/) for command-line interface
- Enhanced with [Rich](https://rich.readthedocs.io/) for beautiful terminal output
---
**Made with β€οΈ for the security research community**
*TrigDroid helps security researchers and malware analysts understand and detect sophisticated Android threats through intelligent payload triggering and environmental manipulation.*
Raw data
{
"_id": null,
"home_page": null,
"name": "trigdroid",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.9",
"maintainer_email": "TrigDroid Team <contact@trigdroid.org>",
"keywords": "android, frida, malware-analysis, mobile-security, penetration-testing, reverse-engineering, security",
"author": null,
"author_email": "Daniel Baier <daniel.baier@fkie.fraunhofer.de>, Simon H\u00fcsch <simon.huesch@smail.inf.h-brs.de>",
"download_url": "https://files.pythonhosted.org/packages/55/00/a8c0001df1155494d5919a2836503e81e545bc8cba3c5e9962dc867965eb/trigdroid-2.0.0.tar.gz",
"platform": null,
"description": "# TrigDroid \ud83e\udd16\n\n**Android Sandbox Payload Trigger Framework for Security Research**\n\n[](https://www.python.org/downloads/)\n[](LICENSE)\n[]()\n[]()\n\nTrigDroid is a modern Android security testing framework designed to trigger payloads in potentially malicious Android applications through sophisticated environmental manipulation. Built for security researchers, malware analysts, and penetration testers, it provides both a powerful command-line interface and a flexible Python API. It is part of the Android Sandbox Sandroid.\n\n## \ud83c\udfaf Key Features\n\n- **\ud83d\udd0d Payload Trigger Detection**: Sophisticated environmental manipulation to trigger hidden malicious behaviors\n- **\ud83d\udcf1 Multi-Device Support**: Works with physical devices and emulators\n- **\ud83d\udd27 Dual Interface**: Both CLI and Python API for maximum flexibility \n- **\u26a1 Frida Integration**: Advanced runtime instrumentation with TypeScript hooks\n- **\ud83c\udf10 Network Manipulation**: WiFi, mobile data, and Bluetooth state changes\n- **\ud83d\udcca Sensor Simulation**: Accelerometer, gyroscope, light, pressure, and more\n- **\ud83d\udd0b Battery Simulation**: Dynamic battery level and charging state changes\n- **\ud83d\udcc8 Comprehensive Reporting**: Detailed test results with timing and metrics\n- **\ud83c\udfd7\ufe0f Modern Architecture**: Built with SOLID principles and type safety\n\n## \ud83d\ude80 Quick Start\n\n### Installation\n\n```bash\n# Install TrigDroid with full features\npip install trigdroid[full]\n\n# Install minimal version\npip install trigdroid\n\n# Install with specific features\npip install trigdroid[frida] # Just Frida support\npip install trigdroid[dev] # Development tools\n```\n\n### Prerequisites\n\n- **Python 3.9+**\n- **Android Debug Bridge (ADB)**\n- **Android device or emulator** with USB debugging enabled\n- **Node.js** (optional, for TypeScript Frida hooks)\n\n### Basic Usage\n\n```bash\n# Test an Android app with basic payload triggers\ntrigdroid -p com.example.app\n\n# Advanced testing with sensor manipulation\ntrigdroid -p com.suspicious.app --acceleration 8 --battery 3 --wifi\n\n# List available Android devices\ntrigdroid devices\n\n# Get detailed app information\ntrigdroid info com.example.app\n```\n\n## \ud83d\udccb Command Line Interface\n\n### Core Commands\n\n```bash\n# Basic app analysis\ntrigdroid -p <package_name>\n\n# Advanced options\ntrigdroid -p com.example.app \\\n --acceleration 5 \\ # Sensor elaborateness (0-10)\n --battery 3 \\ # Battery rotation level (0-4)\n --wifi \\ # Enable WiFi state changes\n --data \\ # Enable mobile data changes\n --frida \\ # Enable Frida hooks\n --timeout 600 # Test timeout in seconds\n```\n\n### Device Management\n\n```bash\n# List all connected devices\ntrigdroid devices\n\n# Get detailed device information\ntrigdroid devices --verbose\n\n# Test specific device\ntrigdroid -p com.example.app -d emulator-5554\n```\n\n### Configuration Files\n\n```bash\n# Create configuration template\ntrigdroid --create-config default\n\n# Use configuration file\ntrigdroid test-config config.yaml\n```\n\n### Example Configuration (config.yaml)\n\n```yaml\npackage: \"com.example.app\"\nacceleration: 5\nsensors:\n - accelerometer\n - gyroscope\n - light\nnetwork_states:\n - wifi\n - data\nbattery_rotation: 3\nfrida_hooks: true\ntimeout: 300\nverbose: true\n```\n\n## \ud83d\udc0d Python API\n\n### Simple Usage\n\n```python\nfrom trigdroid import quick_test\n\n# Quick test with default settings\nresult = quick_test(\"com.example.app\")\nprint(f\"Test successful: {result.success}\")\n```\n\n### Advanced Usage\n\n```python\nfrom trigdroid import TrigDroidAPI, TestConfiguration\n\n# Create detailed configuration\nconfig = TestConfiguration(\n package=\"com.suspicious.app\",\n acceleration=8, # High sensor activity\n sensors=[\"accelerometer\", \"gyroscope\", \"light\"],\n network_states=[\"wifi\", \"data\"], # Network state changes\n battery_rotation=3, # Battery level simulation\n frida_hooks=True, # Enable runtime instrumentation\n timeout=600, # 10 minute timeout\n verbose=True\n)\n\n# Run comprehensive test\nwith TrigDroidAPI() as trigdroid:\n trigdroid.configure(config)\n result = trigdroid.run_tests()\n \n # Analyze results\n if result.success:\n print(f\"\u2705 Test completed in {result.duration_seconds:.1f}s\")\n print(f\"\ud83d\udcca Tests run: {result.total_tests}\")\n print(f\"\u2705 Passed: {result.passed_tests}\")\n print(f\"\u274c Failed: {result.failed_tests}\")\n else:\n print(f\"\u274c Test failed: {result.error}\")\n \n # Check for suspicious behavior\n if result.app_crashed:\n print(\"\u26a0\ufe0f App crashed during testing\")\n if result.frida_errors:\n print(f\"\ud83d\udd0d Frida instrumentation issues: {result.frida_errors}\")\n \n # Access detailed metrics\n print(f\"\ud83d\udcf1 Sensor tests: {len(result.sensor_tests_executed)}\")\n print(f\"\ud83c\udf10 Network changes: {len(result.network_state_changes)}\")\n print(f\"\ud83d\udd0b Background time: {result.app_background_time:.1f}s\")\n```\n\n### Device Management API\n\n```python\nfrom trigdroid import DeviceManager, scan_devices\n\n# Scan for available devices\ndevices = scan_devices()\nfor device in devices:\n print(f\"Device: {device['id']} ({device['status']})\")\n\n# Advanced device management\nmanager = DeviceManager()\ndevice = manager.connect_to_device(\"emulator-5554\")\n\nif device:\n print(f\"Connected to: {device.device_id}\")\n info = device.get_device_info()\n print(f\"Model: {info.get('model', 'Unknown')}\")\n print(f\"Android: {info.get('version', 'Unknown')}\")\n```\n\n### Environment Validation\n\n```python\nfrom trigdroid.api.quick_start import validate_environment, setup_environment\n\n# Check if environment is ready\nstatus = validate_environment()\nif all(status.values()):\n print(\"\ud83c\udf89 Environment is ready!\")\nelse:\n print(\"\u274c Issues found:\")\n for check, result in status.items():\n if not result:\n print(f\" \u2022 {check}\")\n\n# Automatically setup environment\nif setup_environment():\n print(\"\u2705 Environment setup complete\")\n```\n\n## \ud83d\udd27 Advanced Features\n\n### Sensor Manipulation\n\nTrigDroid can simulate various Android sensors to trigger environment-dependent payloads:\n\n- **Accelerometer**: Motion detection triggers\n- **Gyroscope**: Rotation-based activations \n- **Light Sensor**: Ambient light conditions\n- **Pressure**: Atmospheric pressure changes\n- **Magnetometer**: Magnetic field variations\n- **Proximity**: Near/far object detection\n\n```bash\n# Fine-tuned sensor testing\ntrigdroid -p com.example.app \\\n --acceleration 7 \\\n --gyroscope 5 \\\n --light 3 \\\n --pressure 4\n```\n\n### Network State Manipulation\n\nSimulate different connectivity scenarios:\n\n```bash\n# Test with network state changes\ntrigdroid -p com.example.app --wifi --data --bluetooth\n```\n\n### Frida Runtime Instrumentation\n\nTrigDroid includes sophisticated Frida hooks written in TypeScript:\n\n- **Method interception**: Hook critical Android APIs\n- **Parameter modification**: Alter method arguments and return values\n- **Behavior monitoring**: Track app interactions with system APIs\n- **Anti-analysis detection**: Identify evasion techniques\n\n### Battery and System Simulation\n\n```bash\n# Simulate battery level changes and system states\ntrigdroid -p com.example.app \\\n --battery 4 \\ # Maximum battery simulation\n --background-time 30 \\ # 30 seconds in background\n --min-runtime 5 # Minimum 5 minutes runtime\n```\n\n## \ud83d\udcca Understanding Results\n\n### Test Result Structure\n\n```python\n# Example result analysis\nresult = api.run_tests()\n\n# Basic status\nprint(f\"Success: {result.success}\")\nprint(f\"Phase: {result.phase}\") # setup, execution, teardown\nprint(f\"Duration: {result.duration_seconds}s\")\n\n# Test statistics\nprint(f\"Total tests: {result.total_tests}\")\nprint(f\"Success rate: {result.success_rate:.1f}%\")\n\n# App behavior analysis\nprint(f\"App started: {result.app_started}\")\nprint(f\"App crashed: {result.app_crashed}\")\nprint(f\"Background time: {result.app_background_time}s\")\n\n# Instrumentation results\nprint(f\"Frida hooks loaded: {result.frida_hooks_loaded}\")\nprint(f\"Frida hooks active: {result.frida_hooks_active}\")\n\n# Sensor test results\nfor sensor, changed in result.sensor_values_changed.items():\n print(f\"Sensor {sensor}: {changed} value changes\")\n\n# Export results\nresult_dict = result.to_dict()\nsummary = result.summary() # Human-readable summary\n```\n\n### Interpreting Security Findings\n\n**\ud83d\udd0d Suspicious Indicators:**\n- App crashes during sensor manipulation\n- Unexpected network activity during state changes\n- Frida hook detection or evasion attempts\n- Unusual battery usage patterns\n- Background behavior changes\n\n**\u2705 Normal Behavior:**\n- Consistent app performance across all tests\n- No crashes or errors\n- Predictable sensor responses\n- Standard network usage patterns\n\n## \ud83d\udee0\ufe0f Development and Integration\n\n### Third-Party Project Integration\n\n```python\n# In your security analysis tool\nfrom trigdroid import TrigDroidAPI, TestConfiguration\n\ndef analyze_apk(package_name: str) -> dict:\n \"\"\"Analyze an APK for malicious behavior.\"\"\"\n config = TestConfiguration(\n package=package_name,\n acceleration=8, # High intensity testing\n timeout=600,\n frida_hooks=True\n )\n \n with TrigDroidAPI() as trigdroid:\n result = trigdroid.run_tests()\n \n return {\n \"malicious\": not result.success,\n \"confidence\": result.success_rate,\n \"indicators\": {\n \"crashed\": result.app_crashed,\n \"evasion_detected\": len(result.frida_errors) > 0,\n \"suspicious_network\": len(result.network_state_changes) > 5\n },\n \"report\": result.summary()\n }\n\n# Usage\nanalysis = analyze_apk(\"com.suspicious.app\")\nif analysis[\"malicious\"]:\n print(f\"\u26a0\ufe0f Malicious behavior detected (confidence: {analysis['confidence']:.1f}%)\")\n```\n\n### CI/CD Integration\n\n```yaml\n# .github/workflows/security-scan.yml\nname: Android Security Scan\n\non: [push, pull_request]\n\njobs:\n security-scan:\n runs-on: ubuntu-latest\n \n steps:\n - uses: actions/checkout@v3\n \n - name: Setup Python\n uses: actions/setup-python@v4\n with:\n python-version: '3.9'\n \n - name: Install TrigDroid\n run: pip install trigdroid[frida]\n \n - name: Setup Android Emulator\n uses: reactivecircus/android-emulator-runner@v2\n with:\n api-level: 29\n script: |\n adb devices\n trigdroid devices\n \n - name: Security Analysis\n run: |\n trigdroid -p com.example.testapp \\\n --acceleration 5 \\\n --timeout 300 \\\n --frida\n```\n\n## \ud83d\udd12 Security Considerations\n\n**\u26a0\ufe0f Important**: TrigDroid is designed for **defensive security research** and **malware analysis** only.\n\n### Ethical Usage Guidelines\n\n- \u2705 **Authorized Testing**: Only test applications you own or have explicit permission to analyze\n- \u2705 **Research Purposes**: Use for academic research, security analysis, and malware detection\n- \u2705 **Controlled Environment**: Run tests in isolated environments or sandboxes\n- \u274c **No Malicious Use**: Do not use to enhance or create malicious capabilities\n- \u274c **No Unauthorized Testing**: Do not test third-party applications without permission\n\n### Privacy and Legal Compliance\n\n- Ensure compliance with local laws and regulations\n- Respect application privacy policies and terms of service\n- Use appropriate data handling and retention practices\n- Consider ethical implications of security research\n\n## \ud83d\udc1b Troubleshooting\n\n### Common Issues\n\n**Device Not Found**\n```bash\n# Check ADB connection\nadb devices\n\n# Restart ADB server\nadb kill-server && adb start-server\n\n# Enable USB debugging on device\n# Developer options \u2192 USB debugging\n```\n\n**Frida Hooks Fail to Load**\n```bash\n# Check Frida installation\npython -c \"import frida; print(frida.__version__)\"\n\n# Reinstall Frida\npip install --upgrade frida frida-tools\n\n# Check device architecture\nadb shell getprop ro.product.cpu.abi\n```\n\n**TypeScript Compilation Errors**\n```bash\n# Check Node.js installation\nnode --version && npm --version\n\n# Rebuild TypeScript hooks\ncd frida-hooks\nrm -rf node_modules dist\nnpm install && npm run build\n```\n\n**Permission Errors**\n```bash\n# Grant app permissions manually\nadb shell pm grant com.example.app android.permission.READ_PHONE_STATE\n\n# Use TrigDroid's permission management\ntrigdroid -p com.example.app --grant-permission android.permission.CAMERA\n```\n\n### Getting Help\n\n- **Documentation**: Full documentation at [docs.trigdroid.org](https://docs.trigdroid.org)\n- **Issues**: Report bugs at [GitHub Issues](https://github.com/trigdroid/trigdroid/issues)\n- **Discussions**: Join the community at [GitHub Discussions](https://github.com/trigdroid/trigdroid/discussions)\n\n## \ud83e\udd1d Contributing\n\nWe welcome contributions from the security research community!\n\n```bash\n# Development setup\ngit clone https://github.com/trigdroid/trigdroid.git\ncd trigdroid\npip install -e \".[dev]\"\n\n# Run tests\npytest tests/\n\n# Code quality checks\nblack src/ tests/\nmypy src/\nruff check src/ tests/\n```\n\nSee [CONTRIBUTING.md](CONTRIBUTING.md) for detailed contribution guidelines.\n\n## \ud83d\udcc4 License\n\nTrigDroid is released under the [MIT License](LICENSE). See LICENSE file for details.\n\n## \ud83d\udee0\ufe0f Development Guide\n\n### Modern Architecture Overview\n\nTrigDroid has been completely refactored following **SOLID principles** with a clean dual-layer architecture:\n\n```\n\u251c\u2500\u2500 src/ # \ud83c\udd95 New Refactored Code (SOLID Architecture)\n\u2502 \u251c\u2500\u2500 trigdroid/ # Modern Public API Layer (lowercase)\n\u2502 \u2502 \u251c\u2500\u2500 api/ # External interface with context managers\n\u2502 \u2502 \u2502 \u251c\u2500\u2500 main.py # TrigDroidAPI class\n\u2502 \u2502 \u2502 \u251c\u2500\u2500 config.py # Type-safe TestConfiguration\n\u2502 \u2502 \u2502 \u251c\u2500\u2500 results.py # Comprehensive TestResult classes\n\u2502 \u2502 \u2502 \u251c\u2500\u2500 devices.py # Device management wrapper\n\u2502 \u2502 \u2502 \u251c\u2500\u2500 runners.py # Test runner wrapper\n\u2502 \u2502 \u2502 \u2514\u2500\u2500 quick_start.py # Convenience functions\n\u2502 \u2502 \u251c\u2500\u2500 cli/ # Rich CLI interface using Click\n\u2502 \u2502 \u2502 \u2514\u2500\u2500 main.py # Modern CLI with subcommands\n\u2502 \u2502 \u251c\u2500\u2500 core/ # Core utilities and enums\n\u2502 \u2502 \u2502 \u251c\u2500\u2500 enums.py # Type-safe enumerations\n\u2502 \u2502 \u2502 \u2514\u2500\u2500 cleanup.py # Resource management\n\u2502 \u2502 \u2514\u2500\u2500 exceptions.py # Exception hierarchy\n\u2502 \u2514\u2500\u2500 TrigDroid_Infrastructure/ # \ud83c\udfd7\ufe0f Infrastructure Layer (SOLID)\n\u2502 \u251c\u2500\u2500 interfaces/ # Protocol-based abstractions\n\u2502 \u2502 \u2514\u2500\u2500 __init__.py # ILogger, ITestRunner, IAndroidDevice, etc.\n\u2502 \u251c\u2500\u2500 infrastructure/ # Dependency injection + implementations\n\u2502 \u2502 \u251c\u2500\u2500 dependency_injection.py # DI container\n\u2502 \u2502 \u251c\u2500\u2500 configuration.py # Config providers\n\u2502 \u2502 \u251c\u2500\u2500 logging.py # Logger implementations\n\u2502 \u2502 \u2514\u2500\u2500 android.py # Device management\n\u2502 \u251c\u2500\u2500 application/ # Application orchestration\n\u2502 \u2502 \u2514\u2500\u2500 orchestrator.py # Main workflow coordinator\n\u2502 \u2514\u2500\u2500 test_runners/ # Test execution implementations\n\u251c\u2500\u2500 src/ # \ud83c\udfdb\ufe0f Legacy Code (Original Implementation)\n\u2502 \u2514\u2500\u2500 TrigDroid/ # Legacy TrigDroid (preserved for compatibility)\n\u2502 \u251c\u2500\u2500 logger/ # Original logging utilities\n\u2502 \u251c\u2500\u2500 interaction/ # Legacy UI components \n\u2502 \u251c\u2500\u2500 utils/ # Legacy utility functions\n\u2502 \u251c\u2500\u2500 frida/ # Legacy JavaScript hooks\n\u2502 \u2514\u2500\u2500 ... # Other legacy components\n\u251c\u2500\u2500 frida-hooks/ # \ud83d\udd27 TypeScript Frida Hooks (New)\n\u2502 \u251c\u2500\u2500 main.ts # Hook entry point\n\u2502 \u251c\u2500\u2500 hooks/ # Individual hook modules\n\u2502 \u2502 \u251c\u2500\u2500 android-sensors.ts\n\u2502 \u2502 \u2514\u2500\u2500 android-build.ts\n\u2502 \u251c\u2500\u2500 types.ts # TypeScript type definitions\n\u2502 \u251c\u2500\u2500 utils.ts # Common hook utilities\n\u2502 \u251c\u2500\u2500 package.json # Node.js build configuration\n\u2502 \u2514\u2500\u2500 tsconfig.json # TypeScript compiler settings\n\u251c\u2500\u2500 scripts/ # \ud83d\ude80 Build and installation scripts\n\u2502 \u251c\u2500\u2500 build.py # Cross-platform build script\n\u2502 \u2514\u2500\u2500 install.sh # Automated installation\n\u251c\u2500\u2500 pyproject.toml # Modern Python packaging (PEP 621)\n\u2514\u2500\u2500 Makefile # Development workflow commands\n```\n\n### SOLID Principles Implementation\n\n#### **1. Single Responsibility Principle**\nEach class has one reason to change:\n- `AndroidDevice`: Only handles device operations\n- `StandardLogger`: Only handles logging\n- `SensorTestRunner`: Only executes sensor tests\n\n#### **2. Open/Closed Principle**\nExtend functionality without modifying existing code:\n```python\n# Add new test runner without changing existing ones\nclass CustomTestRunner(TestRunnerBase):\n def can_run(self, test_type: str) -> bool:\n return test_type == \"custom\"\n \n def _execute_internal(self, context: ITestContext) -> TestResult:\n # Custom test logic\n return TestResult.SUCCESS\n\n# Register in DI container\ncontainer.register_transient(ITestRunner, CustomTestRunner, \"custom\")\n```\n\n#### **3. Liskov Substitution Principle**\nAll implementations follow their interfaces:\n```python\n# Any ILogger implementation works seamlessly\nlogger: ILogger = StandardLogger() # or FilteredLogger()\nlogger.info(\"Test message\") # Works the same way\n```\n\n#### **4. Interface Segregation Principle**\nSmall, focused interfaces instead of large monolithic ones:\n```python\nclass ILogger(Protocol):\n def debug(self, message: str) -> None: ...\n def info(self, message: str) -> None: ...\n \nclass IConfigurationProvider(Protocol):\n def get_value(self, key: str) -> ConfigValue: ...\n def set_value(self, key: str, value: ConfigValue) -> None: ...\n```\n\n#### **5. Dependency Inversion Principle**\nDepend on abstractions, inject dependencies:\n```python\nclass SensorTestRunner(TestRunnerBase):\n def __init__(self, logger: ILogger, device: IAndroidDevice):\n super().__init__(logger)\n self._device = device # Injected dependency\n```\n\n### Development Environment Setup\n\n#### **Quick Development Setup**\n```bash\n# 1. Clone and setup development environment\ngit clone https://github.com/trigdroid/trigdroid.git\ncd trigdroid\n\n# 2. Use our automated installer\n./scripts/install.sh --mode dev\n\n# 3. Alternative: Manual setup\npython -m venv venv\nsource venv/bin/activate # On Windows: venv\\Scripts\\activate\npip install -e \".[full,dev,test,docs]\"\n\n# 4. Build TypeScript hooks\ncd frida-hooks\nnpm install && npm run build\ncd ..\n\n# 5. Verify installation\ntrigdroid --version\npytest tests/ -v\n```\n\n#### **Development Workflow Commands**\n```bash\n# Development commands (see Makefile)\nmake setup-dev-env # Initial environment setup\nmake dev-install # Install in development mode\nmake build # Build all components (Python + TypeScript)\n\n# Code quality\nmake format # Auto-format with black + isort\nmake lint # Type checking with mypy + ruff\nmake check # Run all quality checks\nmake pre-commit # Format + lint + fast tests\n\n# Testing\nmake test # All tests\nmake test-unit # Unit tests only\nmake test-integration # Integration tests\nmake test-fast # Skip slow tests\nmake coverage # Generate coverage report\n\n# Build and distribution\nmake package # Build wheel/sdist\nmake hooks # Build TypeScript hooks only\nmake clean # Clean build artifacts\n```\n\n### Adding New Features\n\n#### **1. Create New Test Runner**\n```python\n# src2/TrigDroid_Infrastructure/test_runners/custom_test_runner.py \nfrom ..interfaces import ITestRunner, ITestContext, TestResult, TestRunnerBase\n\nclass CustomTestRunner(TestRunnerBase):\n \"\"\"Example custom test runner.\"\"\"\n \n def can_run(self, test_type: str) -> bool:\n return test_type == \"custom\"\n \n def _execute_internal(self, context: ITestContext) -> TestResult:\n # Implement your test logic\n self._logger.info(\"Running custom test\")\n \n # Access dependencies through context\n device = context.device\n config = context.config\n package = context.package_name\n \n # Your test implementation\n success = self._run_custom_test(device, package)\n \n return TestResult.SUCCESS if success else TestResult.FAILURE\n \n def _run_custom_test(self, device, package) -> bool:\n # Custom test implementation\n return True\n\n# Register in dependency_injection.py\ncontainer.register_transient(ITestRunner, CustomTestRunner, \"custom\")\n```\n\n#### **2. Add New Configuration Provider**\n```python\n# src2/TrigDroid_Infrastructure/infrastructure/configuration.py\nclass DatabaseConfigProvider(ConfigurationProviderBase):\n \"\"\"Load configuration from database.\"\"\"\n \n def _load_configuration(self) -> Dict[str, ConfigValue]:\n # Load from database\n return {\"custom_setting\": \"value\"}\n\n# Register in configure_container()\ncontainer.register_transient(IConfigurationProvider, DatabaseConfigProvider, \"database\")\n```\n\n#### **3. Create TypeScript Frida Hook**\n```typescript\n// frida-hooks/hooks/custom-hook.ts\nimport { HookManager } from '../utils';\n\nexport class CustomHook extends HookManager {\n public hookCustomAPI(): void {\n const SomeClass = Java.use(\"com.example.SomeClass\");\n \n SomeClass.someMethod.implementation = function(...args) {\n console.log(\"[TrigDroid] Custom hook triggered\");\n this.logToChangelog(\"SomeClass.someMethod\", \"original\", \"hooked\");\n \n // Call original method\n return this.someMethod.apply(this, args);\n };\n }\n}\n\n// Add to main.ts\nimport { CustomHook } from './hooks/custom-hook';\n\nfunction main() {\n const customHook = new CustomHook();\n customHook.hookCustomAPI();\n}\n```\n\n### TypeScript Hook Development\n\n#### **Building Hooks**\n```bash\n# Build hooks automatically during pip install\npip install -e .\n\n# Manual hook building\ncd frida-hooks\nnpm install # Install dependencies\nnpm run build # Compile TypeScript to JavaScript\nnpm run watch # Watch mode for development\n\n# Using make\nmake hooks # Build hooks only\n```\n\n#### **Hook Development Patterns**\n```typescript\n// frida-hooks/hooks/android-example.ts\nimport { AndroidSensorType } from '../types';\nimport { HookUtils } from '../utils';\n\nexport class AndroidExampleHook {\n private hookUtils: HookUtils;\n \n constructor() {\n this.hookUtils = new HookUtils();\n }\n \n public hookSensorManager(): void {\n try {\n const SensorManager = Java.use(\"android.hardware.SensorManager\");\n \n SensorManager.getDefaultSensor.implementation = function(type) {\n const originalSensor = this.getDefaultSensor(type);\n \n // Log the hook for debugging\n this.hookUtils.logHookExecution(\"SensorManager.getDefaultSensor\", {\n sensorType: type,\n timestamp: Date.now()\n });\n \n // Record change in changelog\n this.hookUtils.writeToChangelog(\n \"SensorManager.getDefaultSensor\",\n \"original_behavior\",\n \"hooked_behavior\",\n `Sensor type ${type} intercepted`\n );\n \n return originalSensor;\n };\n \n } catch (error) {\n console.error(`[TrigDroid] Hook failed: ${error}`);\n }\n }\n}\n```\n\n### Dependency Injection Usage\n\n#### **Registering Services**\n```python\n# In configure_container()\nfrom .my_service import MyService\n\n# Singleton (same instance every time)\ncontainer.register_singleton(IMyService, MyService)\n\n# Transient (new instance every time) \ncontainer.register_transient(IMyService, MyService)\n\n# Factory function\ncontainer.register_singleton(IMyService, lambda: MyService(config=\"custom\"))\n\n# Specific instance\ncontainer.register_instance(IMyService, my_service_instance)\n```\n\n#### **Resolving Dependencies**\n```python\n# Method 1: Through container\ncontainer = configure_container()\nlogger = container.resolve(ILogger)\n\n# Method 2: Service Locator (global access)\nServiceLocator.set_container(container)\nlogger = ServiceLocator.get_service(ILogger)\n\n# Method 3: Constructor injection\n@inject(logger=ILogger, device=IAndroidDevice)\nclass MyTestRunner:\n def __init__(self, logger: ILogger, device: IAndroidDevice):\n self._logger = logger\n self._device = device\n```\n\n### Code Quality Standards\n\n#### **Type Safety**\n```python\n# Use type hints everywhere\ndef process_config(config: TestConfiguration) -> TestResult:\n return TestResult.SUCCESS\n\n# Use protocols for interfaces\nclass IMyService(Protocol):\n def do_something(self, value: str) -> bool: ...\n\n# Use enums for constants\nclass TestPhase(Enum):\n SETUP = \"setup\"\n EXECUTION = \"execution\"\n TEARDOWN = \"teardown\"\n```\n\n#### **Error Handling**\n```python\n# Proper exception hierarchy\nclass TrigDroidException(Exception):\n \"\"\"Base exception for TrigDroid.\"\"\"\n pass\n\nclass DeviceConnectionError(TrigDroidException):\n \"\"\"Device connection failed.\"\"\"\n pass\n\n# Use try/catch with specific exceptions\ntry:\n device.connect()\nexcept DeviceConnectionError as e:\n logger.error(f\"Failed to connect: {e}\")\n return TestResult.FAILURE\n```\n\n#### **Logging Best Practices**\n```python\n# Use structured logging\nlogger.info(\"Test started\", extra={\n \"package\": package_name,\n \"phase\": \"setup\",\n \"timestamp\": time.time()\n})\n\n# Use appropriate log levels\nlogger.debug(\"Detailed debugging info\") # Development only\nlogger.info(\"Important user information\") # Normal operation\nlogger.warning(\"Something might be wrong\") # Potential issues\nlogger.error(\"Something failed\") # Errors that don't stop execution\nlogger.critical(\"System cannot continue\") # Fatal errors\n```\n\n### Testing Framework\n\n#### **Unit Tests**\n```python\n# tests/unit/test_sensor_runner.py\nimport pytest\nfrom unittest.mock import Mock\nfrom TrigDroid_Infrastructure.test_runners import SensorTestRunner\nfrom TrigDroid_Infrastructure.interfaces import ILogger, ITestContext, TestResult\n\ndef test_sensor_runner_success():\n # Arrange\n mock_logger = Mock(spec=ILogger)\n mock_context = Mock(spec=ITestContext)\n runner = SensorTestRunner(mock_logger)\n \n # Act\n result = runner.execute(mock_context)\n \n # Assert\n assert result == TestResult.SUCCESS\n mock_logger.info.assert_called()\n```\n\n#### **Integration Tests**\n```python\n# tests/integration/test_full_workflow.py\n@pytest.mark.integration\n@pytest.mark.requires_device\ndef test_full_testing_workflow(test_device):\n \"\"\"Test complete workflow with real device.\"\"\"\n config = TestConfiguration(\n package=\"com.example.testapp\",\n acceleration=3,\n timeout=60\n )\n \n with TrigDroidAPI() as api:\n api.configure(config)\n api.set_device(test_device.device_id)\n result = api.run_tests()\n \n assert result.success\n assert result.total_tests > 0\n```\n\n### Performance Optimization\n\n#### **Fast Development Cycle**\n```bash\n# Skip TypeScript build during development\nSKIP_HOOKS=1 pip install -e .\n\n# Run only fast tests\nmake test-fast\n\n# Use parallel testing\npytest -n auto tests/\n\n# Quick format and lint check\nmake pre-commit\n```\n\n#### **Build Optimization**\n```bash\n# Build only what changed\nmake hooks-if-changed\n\n# Use cached dependencies\npip install --cache-dir ~/.cache/pip -e .\n\n# Parallel hook compilation\ncd frida-hooks && npm run build:parallel\n```\n\n### Contributing Guidelines\n\n#### **Code Standards**\n- **Readable**: Code should read like well-written prose\n- **Self-documenting**: Use clear variable and function names\n- **Consistent**: Follow established patterns\n- **Simple**: Prefer simple solutions over clever ones\n- **DRY**: Extract common functionality\n- **YAGNI**: Don't over-engineer\n\n#### **Pull Request Process**\n```bash\n# 1. Development workflow\ngit checkout -b feature/new-feature\nmake dev-install\nmake pre-commit # Format + lint + fast tests\n\n# 2. Before committing\nmake test # Full test suite\nmake build # Ensure everything builds\nmake check # Final quality check\n\n# 3. Create pull request\ngit push origin feature/new-feature\n# Open PR with detailed description\n```\n\n#### **Code Review Checklist**\n- [ ] Follows SOLID principles\n- [ ] Has proper type annotations\n- [ ] Includes unit tests (>90% coverage)\n- [ ] Updated documentation if needed\n- [ ] No hardcoded values or magic numbers\n- [ ] Proper error handling\n- [ ] TypeScript hooks built successfully\n- [ ] All quality checks pass\n\n### Debugging and Troubleshooting\n\n#### **Development Issues**\n```bash\n# TypeScript compilation fails\ncd frida-hooks\nrm -rf node_modules dist\nnpm install && npm run build\n\n# Python import errors\npip uninstall trigdroid\npip install -e \".[full]\"\n\n# Dependency injection issues\n# Check container registration in configure_container()\ncontainer.has_service(IMyService) # Should return True\n\n# Test runner not found\n# Verify registration with correct name\ncontainer.resolve(ITestRunner, \"my_runner\")\n```\n\n#### **Runtime Debugging**\n```python\n# Enable debug logging\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\n\n# Use dependency injection debug mode\ncontainer = configure_container()\nif container.has_service(IMyService):\n service = container.resolve(IMyService)\n \n# Check service registration\nprint(f\"Registered services: {list(container._services.keys())}\")\n```\n\nThis development guide provides comprehensive information for contributing to and extending TrigDroid's modern architecture.\n\n## \ud83d\ude4f Acknowledgments\n\n- Built on the foundation of the [Evadroid](https://github.com/evadroid/evadroid) project\n- Powered by [Frida](https://frida.re/) dynamic instrumentation toolkit\n- Uses [Click](https://click.palletsprojects.com/) for command-line interface\n- Enhanced with [Rich](https://rich.readthedocs.io/) for beautiful terminal output\n\n---\n\n**Made with \u2764\ufe0f for the security research community**\n\n*TrigDroid helps security researchers and malware analysts understand and detect sophisticated Android threats through intelligent payload triggering and environmental manipulation.*",
"bugtrack_url": null,
"license": "MIT License\n \n Copyright (c) 2025 FKIE-CAD\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.",
"summary": "Android Sandbox Payload Trigger Framework for Security Research",
"version": "2.0.0",
"project_urls": {
"Bug Tracker": "https://github.com/fkie-cad/Sandroid_TrigDroid/issues",
"Changelog": "https://github.com/fkie-cad/Sandroid_TrigDroid/blob/main/CHANGELOG.md",
"Documentation": "https://fkie-cad/Sandroid_TrigDroid",
"Homepage": "https://github.com/fkie-cad/Sandroid_TrigDroid",
"Repository": "https://github.com/fkie-cad/Sandroid_TrigDroid.git"
},
"split_keywords": [
"android",
" frida",
" malware-analysis",
" mobile-security",
" penetration-testing",
" reverse-engineering",
" security"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "51f5ddb2e429933f8326a3d5c557535515033ad4439a471459b7900409979b38",
"md5": "8756f9575b2a7fd777e0005a16767ae0",
"sha256": "495abcfb10aef78511793ff6a28790e7df0514ad653c9f650f9748ff979a8a86"
},
"downloads": -1,
"filename": "trigdroid-2.0.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "8756f9575b2a7fd777e0005a16767ae0",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.9",
"size": 13784,
"upload_time": "2025-08-21T07:32:19",
"upload_time_iso_8601": "2025-08-21T07:32:19.900562Z",
"url": "https://files.pythonhosted.org/packages/51/f5/ddb2e429933f8326a3d5c557535515033ad4439a471459b7900409979b38/trigdroid-2.0.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "5500a8c0001df1155494d5919a2836503e81e545bc8cba3c5e9962dc867965eb",
"md5": "ddb8c902c9bc2a2148a30139c13015c0",
"sha256": "835f8f7d2e6d77b94cc005b35bd3fa5736c53f7dac77eaa13da61be85af46670"
},
"downloads": -1,
"filename": "trigdroid-2.0.0.tar.gz",
"has_sig": false,
"md5_digest": "ddb8c902c9bc2a2148a30139c13015c0",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.9",
"size": 58723,
"upload_time": "2025-08-21T07:32:21",
"upload_time_iso_8601": "2025-08-21T07:32:21.363008Z",
"url": "https://files.pythonhosted.org/packages/55/00/a8c0001df1155494d5919a2836503e81e545bc8cba3c5e9962dc867965eb/trigdroid-2.0.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-21 07:32:21",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "fkie-cad",
"github_project": "Sandroid_TrigDroid",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "trigdroid"
}