Overview
Quark Engine is an Android security analysis framework designed to detect and score malicious behavior in APK files. Instead of relying solely on signatures, Quark analyzes actual function calls and API usage patterns within Android applications, providing behavior-based malware scoring and detailed forensic analysis. It’s ideal for security researchers, mobile app developers, and incident response teams.
Key Features
- Behavior-Based Detection: Analyzes API calls and code patterns rather than signatures
- Malware Scoring: Quantifies risk with confidence scores (0-100%)
- APK Unpacking: Automatically extracts and analyzes APK structure
- Bytecode Analysis: Deep inspection of DEX bytecode
- Report Generation: Detailed HTML and text reports
- Signature Matching: Custom rule definitions for behavior detection
- Chain Analysis: Traces multi-step malicious workflows
- Comparison Mode: Compare multiple samples for similarity
- Integration Ready: Python API for automation and CI/CD
Installation
Prerequisites
# Required: Python 3.8+
python --version
# Required: Java Development Kit (for DEX analysis)
java -version
Installation Methods
# Method 1: pip (simplest)
pip install quark-engine
# Method 2: From source
git clone https://github.com/quark-engine/quark-engine
cd quark-engine
pip install -e .
# Method 3: Docker
docker pull ghcr.io/quark-engine/quark-engine
docker run -it quark-engine /bin/bash
# Verify installation
quark --version
Update Rulesets
# Download latest detection rules
quark --update-rule
# Verify rules installed
quark -l | head -20
Basic Usage
Analyze Single APK
# Simple analysis
quark -a sample.apk
# With detailed output
quark -a sample.apk -d
# Show all behavior rules matched
quark -a sample.apk -d -o html > report.html
Output Modes
# Command-line output (default)
quark -a sample.apk
# HTML report
quark -a sample.apk -o html > analysis.html
# JSON output
quark -a sample.apk -o json > analysis.json
# Text file output
quark -a sample.apk -o txt > analysis.txt
Command-Line Options
| Option | Description | Example |
|---|
-a FILE | Analyze APK | quark -a malware.apk |
-d | Show detailed output | quark -a app.apk -d |
-o FORMAT | Output format (html/json/txt) | quark -a app.apk -o json |
-l | List available rules | quark -l |
-s RULE | Score specific rule | quark -a app.apk -s rules/suspicious |
--update-rule | Update detection rules | quark --update-rule |
-c APP1 APP2 | Compare two APKs | quark -c app1.apk app2.apk |
--summary | Summary view | quark -a app.apk --summary |
-i | Interactive mode | quark -i |
--version | Show version | quark --version |
Core Concepts
Behavior-Based Scoring
Quark doesn’t look for specific malware signatures. Instead, it scores based on dangerous API usage patterns:
Score Calculation:
├── Permission Analysis
│ ├── Dangerous permissions detected
│ ├── Permission usage in code
│ └── Permission risk level
├── Behavior Chain Detection
│ ├── Multi-step attack patterns
│ ├── API call sequences
│ └── Intent manipulation
└── Confidence Scoring
├── Pattern frequency
├── Certainty percentage
└── Risk classification
Risk Categories
| Category | Description | Risk Level |
|---|
| Critical | Stolen credentials, banking trojans | 80-100% |
| High | Unauthorized tracking, SMS interception | 60-80% |
| Medium | Data exfiltration, excessive permissions | 40-60% |
| Low | Analytics, optional tracking | 20-40% |
| Info | Normal app functionality | 0-20% |
Analysis Examples
Example 1: Basic Malware Analysis
# Download sample (for testing - use authorized samples only)
# wget https://example.com/sample.apk
# Analyze
quark -a sample.apk -d
# Expected output shows:
# - Suspicious behaviors detected
# - Confidence scores
# - Risk categories
# - API call chains
Example 2: Detailed Report Generation
# Generate comprehensive HTML report
quark -a suspicious_app.apk -o html > malware_report.html
# Generate JSON for parsing
quark -a suspicious_app.apk -o json > analysis.json
# View with browser
firefox malware_report.html
Example 3: Batch Analysis
# Analyze multiple APKs
for apk in *.apk; do
echo "Analyzing $apk..."
quark -a "$apk" -o html > "${apk%.apk}_report.html"
done
# Summary of all
echo "Analysis complete. Reports generated:"
ls *.html
Example 4: Specific Rule Scoring
# Score against credential theft rules
quark -a app.apk -s rules/credential_theft
# Score against tracking behaviors
quark -a app.apk -s rules/tracking
# Score against banking trojans
quark -a app.apk -s rules/banking_malware
Example 5: Application Comparison
# Compare two versions (original vs suspicious)
quark -c original.apk suspicious_variant.apk
# Output shows:
# - Behavior similarities
# - New malicious additions
# - Removed features
# - Risk difference
Working with Rules
List Available Rules
# Show all available detection rules
quark -l
# Filter by category
quark -l | grep -i "trojan"
quark -l | grep -i "tracking"
quark -l | grep -i "credential"
# Count total rules
quark -l | wc -l
Rule Structure
# Example rule file format (JSON)
{
"name": "Suspicious SMS Send",
"category": "trojan",
"severity": "high",
"behaviors": [
{
"api": "sendTextMessage",
"class": "android.telephony.SmsManager",
"method": "sendTextMessage",
"args": ["phone_number", "message"],
"risk": "critical"
}
]
}
Custom Rule Creation
# Create custom detection rule
rule = {
"name": "Custom Malware Pattern",
"category": "trojan",
"severity": "critical",
"behaviors": [
{
"api": "Runtime.exec",
"class": "java.lang.Runtime",
"method": "exec"
},
{
"api": "startActivity",
"class": "android.app.Activity",
"method": "startActivity"
}
],
"chain": [
"Runtime.exec",
"startActivity"
]
}
# Save to custom_rules.json
import json
with open('custom_rules.json', 'w') as f:
json.dump([rule], f, indent=2)
Python API Usage
Basic Scripting
#!/usr/bin/env python3
from quark.core.quark_engine import QuarkEngine
# Initialize Quark
quark = QuarkEngine()
# Load APK
quark.load("sample.apk")
# Run analysis
quark.analyze()
# Get results
for behavior in quark.behaviors:
print(f"Behavior: {behavior.name}")
print(f"Confidence: {behavior.confidence}%")
print(f"Permission: {behavior.permission}")
print("---")
Advanced Analysis
#!/usr/bin/env python3
from quark.core.quark_engine import QuarkEngine
from quark.utils.data import parse_xml_manifest
def analyze_and_report(apk_path):
"""Comprehensive APK analysis"""
quark = QuarkEngine()
quark.load(apk_path)
# Analyze bytecode
quark.analyze()
# Extract manifest
manifest = parse_xml_manifest(apk_path)
permissions = manifest.get('uses-permission', [])
# Score each behavior
results = {
'file': apk_path,
'total_behaviors': len(quark.behaviors),
'high_risk': [],
'medium_risk': [],
'permissions': permissions
}
for behavior in quark.behaviors:
if behavior.confidence >= 80:
results['high_risk'].append({
'name': behavior.name,
'confidence': behavior.confidence
})
elif behavior.confidence >= 40:
results['medium_risk'].append({
'name': behavior.name,
'confidence': behavior.confidence
})
return results
# Usage
results = analyze_and_report('app.apk')
print(f"Total behaviors: {results['total_behaviors']}")
print(f"High risk: {len(results['high_risk'])}")
print(f"Medium risk: {len(results['medium_risk'])}")
Batch Processing with Reporting
#!/usr/bin/env python3
import os
import json
from pathlib import Path
from quark.core.quark_engine import QuarkEngine
class APKAnalyzer:
def __init__(self, apk_dir):
self.apk_dir = apk_dir
self.results = []
def analyze_directory(self):
"""Analyze all APKs in directory"""
apks = Path(self.apk_dir).glob('*.apk')
for apk_path in apks:
print(f"Analyzing {apk_path.name}...")
quark = QuarkEngine()
quark.load(str(apk_path))
quark.analyze()
# Collect results
risk_score = sum(b.confidence for b in quark.behaviors) / len(quark.behaviors) if quark.behaviors else 0
self.results.append({
'file': apk_path.name,
'risk_score': risk_score,
'behavior_count': len(quark.behaviors),
'high_risk_count': len([b for b in quark.behaviors if b.confidence >= 80])
})
def generate_report(self, output_file='analysis_report.json'):
"""Save results to JSON"""
with open(output_file, 'w') as f:
json.dump(self.results, f, indent=2)
print(f"Report saved to: {output_file}")
def print_summary(self):
"""Print summary statistics"""
high_risk_apps = [r for r in self.results if r['risk_score'] >= 70]
print(f"\nAnalysis Summary:")
print(f"Total APKs: {len(self.results)}")
print(f"High-risk APKs: {len(high_risk_apps)}")
for app in high_risk_apps:
print(f" - {app['file']}: {app['risk_score']:.1f}% risk")
# Usage
analyzer = APKAnalyzer('./apks')
analyzer.analyze_directory()
analyzer.generate_report()
analyzer.print_summary()
Common Detection Patterns
Credential Stealing
# Analyze for credential theft
quark -a banking_app.apk -d | grep -i "password\|credential\|account"
# Specific check
quark -a app.apk -s rules/credential_theft
SMS/Call Interception
# Check for SMS interception patterns
quark -a app.apk -d | grep -i "sms\|intercept\|receive"
# Check for call forwarding
quark -a app.apk -d | grep -i "call\|forward\|intercept"
Data Exfiltration
# Analyze data transmission
quark -a app.apk -d | grep -i "upload\|send\|exfil\|http"
# Check for file access
quark -a app.apk -d | grep -i "file\|storage\|external"
Remote Code Execution
# Check for RCE patterns
quark -a app.apk -d | grep -i "Runtime.exec\|ProcessBuilder\|reflection"
# Look for dynamic loading
quark -a app.apk -d | grep -i "DexClassLoader\|URLClassLoader"
Troubleshooting
”APK Not Found"
# Verify APK exists
file sample.apk
# Check read permissions
ls -la sample.apk
# Absolute path (sometimes required)
quark -a /full/path/to/sample.apk
# Verify APK integrity
unzip -t sample.apk
# Check if valid ZIP
file sample.apk
# Re-package if corrupted
cd apk_extracted
zip -r ../sample_fixed.apk .
"Rule File Not Found”
# Check if rules updated
quark --update-rule
# Verify rule location
quark -l | head -5
# Reinstall rules
pip install --upgrade quark-engine
Low/No Detections
# Verify analysis completed
quark -a sample.apk -d | tail -10
# Check with verbose output
quark -a sample.apk -d --verbose
# Try comparison mode
quark -c sample.apk known_malware.apk
Large APK Analysis
# Timeout configuration
timeout 300 quark -a large_app.apk
# Memory optimization
export PYTHONHASHSEED=0
quark -a app.apk
# Parallel analysis (multiple tools)
quark -a app1.apk &
quark -a app2.apk &
quark -a app3.apk &
wait
Caching Analysis Results
# Save analysis output
quark -a sample.apk -o json > cache/sample_analysis.json
# Reuse cached results
if [ -f "cache/sample_analysis.json" ]; then
cat cache/sample_analysis.json
else
quark -a sample.apk -o json > cache/sample_analysis.json
fi
Integration Examples
GitHub Actions CI/CD
name: APK Security Scan
on: [push, pull_request]
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Python
uses: actions/setup-python@v2
with:
python-version: '3.10'
- name: Install Quark Engine
run: pip install quark-engine
- name: Update Rules
run: quark --update-rule
- name: Scan APK
run: |
quark -a app.apk -o json > quark_report.json
- name: Check Results
run: |
python3 << 'EOF'
import json
with open('quark_report.json') as f:
report = json.load(f)
risk_score = report.get('risk_score', 0)
if risk_score > 70:
print(f"⚠️ HIGH RISK: {risk_score}%")
exit(1)
else:
print(f"✓ Risk acceptable: {risk_score}%")
EOF
Web Service Integration
#!/usr/bin/env python3
from flask import Flask, request, jsonify
from quark.core.quark_engine import QuarkEngine
import os
app = Flask(__name__)
@app.route('/analyze', methods=['POST'])
def analyze_apk():
"""API endpoint for APK analysis"""
if 'file' not in request.files:
return jsonify({'error': 'No file provided'}), 400
file = request.files['file']
if not file.filename.endswith('.apk'):
return jsonify({'error': 'Invalid file type'}), 400
# Save temporary file
temp_path = f'/tmp/{file.filename}'
file.save(temp_path)
try:
# Analyze with Quark
quark = QuarkEngine()
quark.load(temp_path)
quark.analyze()
# Prepare response
behaviors = [{
'name': b.name,
'confidence': b.confidence,
'permission': b.permission
} for b in quark.behaviors]
risk_score = sum(b.confidence for b in quark.behaviors) / len(quark.behaviors) if quark.behaviors else 0
return jsonify({
'file': file.filename,
'risk_score': risk_score,
'behaviors': behaviors
})
finally:
# Cleanup
os.remove(temp_path)
if __name__ == '__main__':
app.run(debug=False, port=5000)
Best Practices
- Keep Rules Updated: Regularly run
quark --update-rule
- Multiple Tools: Use alongside other analyzers (Frida, Burp Mobile)
- Static + Dynamic: Combine static analysis with runtime behavior monitoring
- Sample Verification: Confirm sample provenance and authorization
- Report Generation: Always create documented reports for findings
- Version Tracking: Monitor Quark updates for improved detection
Comparison with Alternatives
| Tool | Type | Strengths | Weakness |
|---|
| Quark Engine | Behavioral | Fast, accurate, rule-based | Limited to static analysis |
| MobSF | Comprehensive | All-in-one, web UI | Resource intensive |
| Frida | Dynamic | Runtime behavior | Requires running device |
| Jadx | Decompilation | Source code recovery | No behavioral analysis |
| FlexDroid | APK Analysis | Fast scanning | Limited accuracy |
Resources
Ethical Use
- Authorization: Only analyze APKs you own or have permission to test
- Privacy: Respect user data and privacy regulations
- Responsible Disclosure: Report vulnerabilities properly to developers
- Legal Compliance: Follow local laws regarding reverse engineering
- Educational Use: Document learnings and share responsibly