コンテンツにスキップ

MobSF (Mobile Security Framework) Cheat Sheet

Overview

Mobile Security Framework (MobSF) is an automated, all-in-one mobile application (Android/iOS/Windows) pen-testing, malware analysis and security assessment framework capable of performing static and dynamic analysis. MobSF provides comprehensive security testing capabilities including static analysis, dynamic analysis, malware analysis, and API security testing.

⚠️ Warning: Only use MobSF on applications you own or have explicit permission to test. Unauthorized analysis may violate terms of service or local laws.

Installation

# Pull MobSF Docker image
docker pull opensecurity/mobsf

# Run MobSF container
docker run -it --rm -p 8000:8000 opensecurity/mobsf:latest

# Run with persistent storage
docker run -it --rm -p 8000:8000 -v /host/path:/home/mobsf/.MobSF opensecurity/mobsf:latest

# Run in background
docker run -d -p 8000:8000 --name mobsf opensecurity/mobsf:latest

Manual Installation

Linux/macOS

# Clone repository
git clone https://github.com/MobSF/Mobile-Security-Framework-MobSF.git
cd Mobile-Security-Framework-MobSF

# Install dependencies
pip3 install -r requirements.txt

# Setup database
python3 manage.py makemigrations
python3 manage.py migrate

# Create superuser (optional)
python3 manage.py createsuperuser

# Run MobSF
python3 manage.py runserver 0.0.0.0:8000

Windows

# Clone repository
git clone https://github.com/MobSF/Mobile-Security-Framework-MobSF.git
cd Mobile-Security-Framework-MobSF

# Install dependencies
pip install -r requirements.txt

# Setup database
python manage.py makemigrations
python manage.py migrate

# Run MobSF
python manage.py runserver 0.0.0.0:8000

Prerequisites Installation

Java Development Kit

# Ubuntu/Debian
sudo apt update
sudo apt install openjdk-11-jdk

# macOS
brew install openjdk@11

# Windows
# Download and install from Oracle or OpenJDK website

Android SDK (for dynamic analysis)

# Download Android SDK
wget https://dl.google.com/android/repository/commandlinetools-linux-8512546_latest.zip
unzip commandlinetools-linux-8512546_latest.zip

# Set environment variables
export ANDROID_HOME=$HOME/Android/Sdk
export PATH=$PATH:$ANDROID_HOME/cmdline-tools/latest/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools

# Install SDK components
sdkmanager "platform-tools" "platforms;android-30" "build-tools;30.0.3"

Basic Usage

Web Interface Access

# Access MobSF web interface
http://localhost:8000

# Default credentials (if authentication enabled)
# Username: admin
# Password: (set during installation)

File Upload and Analysis

# Upload APK file via web interface
# Navigate to http://localhost:8000
# Click "Upload" and select APK/IPA file
# Analysis starts automatically

# Supported file formats:
# Android: APK, XAPK, AAB
# iOS: IPA, ZIP
# Windows: APPX

Command Line Interface

# Start MobSF server
python3 manage.py runserver 0.0.0.0:8000

# Run with specific settings
python3 manage.py runserver --settings=mobsf.settings.production

# Run with debug mode
python3 manage.py runserver --debug

# Database operations
python3 manage.py migrate
python3 manage.py collectstatic

API Usage

REST API Endpoints

# Upload file for analysis
curl -X POST -F "file=@app.apk" http://localhost:8000/api/v1/upload

# Get scan results
curl -X POST -d "hash=<file_hash>" http://localhost:8000/api/v1/scan

# Download report
curl -X POST -d "hash=<file_hash>&scan_type=apk" http://localhost:8000/api/v1/download_pdf

# Delete scan
curl -X POST -d "hash=<file_hash>" http://localhost:8000/api/v1/delete_scan

Python API Client

#!/usr/bin/env python3
import requests
import json

class MobSFAPI:
    def __init__(self, server_url="http://localhost:8000"):
        self.server = server_url
        self.api_key = None

    def upload_file(self, file_path):
        """Upload file for analysis"""
        url = f"\\\\{self.server\\\\}/api/v1/upload"
        files = \\\\{'file': open(file_path, 'rb')\\\\}
        response = requests.post(url, files=files)
        return response.json()

    def scan_file(self, file_hash, scan_type="apk"):
        """Start scan analysis"""
        url = f"\\\\{self.server\\\\}/api/v1/scan"
        data = \\\\{'hash': file_hash, 'scan_type': scan_type\\\\}
        response = requests.post(url, data=data)
        return response.json()

    def get_report(self, file_hash, scan_type="apk"):
        """Get analysis report"""
        url = f"\\\\{self.server\\\\}/api/v1/report_json"
        data = \\\\{'hash': file_hash, 'scan_type': scan_type\\\\}
        response = requests.post(url, data=data)
        return response.json()

    def download_pdf(self, file_hash, scan_type="apk"):
        """Download PDF report"""
        url = f"\\\\{self.server\\\\}/api/v1/download_pdf"
        data = \\\\{'hash': file_hash, 'scan_type': scan_type\\\\}
        response = requests.post(url, data=data)
        return response.content

# Usage example
mobsf = MobSFAPI()
upload_result = mobsf.upload_file("app.apk")
file_hash = upload_result['hash']
scan_result = mobsf.scan_file(file_hash)
report = mobsf.get_report(file_hash)

Static Analysis Features

Android APK Analysis

# Automatic analysis includes:
# - Manifest analysis
# - Permission analysis
# - Certificate analysis
# - Code analysis (Java/Kotlin)
# - Resource analysis
# - Binary analysis
# - Security issues detection

# Key areas analyzed:
# - Hardcoded secrets
# - Insecure data storage
# - Cryptographic issues
# - Network security
# - Code obfuscation
# - Anti-debugging measures

iOS IPA Analysis

# Automatic analysis includes:
# - Info.plist analysis
# - Entitlements analysis
# - Binary analysis
# - Code analysis (Objective-C/Swift)
# - Resource analysis
# - Security configuration

# Key areas analyzed:
# - App Transport Security
# - Keychain usage
# - URL schemes
# - File system permissions
# - Binary protections
# - Code signing

Custom Rules and Signatures

# Add custom security rules
# Edit mobsf/StaticAnalyzer/views/android/rules/

# Example custom rule
\\\\{
    "rules": [
        \\\\{
            "id": "custom_hardcoded_key",
            "message": "Hardcoded API key detected",
            "type": "Regex",
            "pattern": "api_key\\s*=\\s*['\"][a-zA-Z0-9]\\\\{32\\\\}['\"]",
            "severity": "HIGH",
            "languages": ["java", "kotlin"],
            "cwe": "CWE-798"
        \\\\}
    ]
\\\\}

Dynamic Analysis

Android Dynamic Analysis Setup

# Setup Android emulator or device
# Enable USB debugging
adb devices

# Install MobSF agent
# Download from MobSF interface
adb install MobSFy.apk

# Configure proxy settings
adb shell settings put global http_proxy localhost:1337

# Start dynamic analysis from web interface
# Navigate to Dynamic Analysis tab
# Select target application
# Click "Start Dynamic Analysis"

iOS Dynamic Analysis Setup

# Requires jailbroken iOS device
# Install MobSF agent via Cydia or manual installation

# SSH to device
ssh root@<device-ip>

# Install required tools
apt update
apt install python3 python3-pip

# Install MobSF iOS agent
pip3 install frida-tools
# Follow MobSF documentation for agent installation

Dynamic Analysis Features

# Runtime analysis capabilities:
# - API monitoring
# - File system monitoring
# - Network traffic analysis
# - Memory dumps
# - Method tracing
# - SSL pinning bypass
# - Root/jailbreak detection bypass
# - Screenshot capture
# - Activity monitoring

Advanced Configuration

Custom Settings

# Edit mobsf/settings.py or create local_settings.py

# Database configuration
DATABASES = \\\\{
    'default': \\\\{
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mobsf_db',
        'USER': 'mobsf_user',
        'PASSWORD': 'password',
        'HOST': 'localhost',
        'PORT': '5432',
    \\\\}
\\\\}

# Security settings
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'your-domain.com']
SECRET_KEY = 'your-secret-key-here'

# Analysis settings
MOBSF_MAX_FILE_SIZE = 100 * 1024 * 1024  # 100MB
MOBSF_TIMEOUT = 300  # 5 minutes

# Proxy settings for dynamic analysis
PROXY_IP = '127.0.0.1'
PROXY_PORT = 1337

Docker Compose Setup

# docker-compose.yml
version: '3.8'

services:
  mobsf:
    image: opensecurity/mobsf:latest
    ports:
      - "8000:8000"
    volumes:
      - mobsf_data:/home/mobsf/.MobSF
    environment:
      - MOBSF_ANALYZER_TIMEOUT=300
    restart: unless-stopped

  postgres:
    image: postgres:13
    environment:
      - POSTGRES_DB=mobsf
      - POSTGRES_USER=mobsf
      - POSTGRES_PASSWORD=password
    volumes:
      - postgres_data:/var/lib/postgresql/data
    restart: unless-stopped

volumes:
  mobsf_data:
  postgres_data:

SSL/TLS Configuration

# Generate SSL certificate
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes

# Configure HTTPS in settings
USE_TLS = True
TLS_CERT = '/path/to/cert.pem'
TLS_KEY = '/path/to/key.pem'

# Run with HTTPS
python3 manage.py runsslserver 0.0.0.0:8000 --certificate /path/to/cert.pem --key /path/to/key.pem

Automation Scripts

Batch Analysis Script

#!/usr/bin/env python3
import os
import requests
import time
import json
from pathlib import Path

class MobSFBatchAnalyzer:
    def __init__(self, server_url="http://localhost:8000"):
        self.server = server_url
        self.session = requests.Session()

    def analyze_directory(self, directory_path, output_dir="reports"):
        """Analyze all APK/IPA files in directory"""
        Path(output_dir).mkdir(exist_ok=True)

        for file_path in Path(directory_path).glob("*.apk"):
            print(f"[+] Analyzing \\\\{file_path.name\\\\}")

            try:
                # Upload file
                upload_result = self.upload_file(str(file_path))
                file_hash = upload_result['hash']

                # Wait for analysis completion
                self.wait_for_analysis(file_hash)

                # Download report
                report = self.get_report(file_hash)
                report_path = Path(output_dir) / f"\\\\{file_path.stem\\\\}_report.json"

                with open(report_path, 'w') as f:
                    json.dump(report, f, indent=2)

                print(f"[+] Report saved: \\\\{report_path\\\\}")

            except Exception as e:
                print(f"[-] Error analyzing \\\\{file_path.name\\\\}: \\\\{e\\\\}")

    def upload_file(self, file_path):
        """Upload file for analysis"""
        url = f"\\\\{self.server\\\\}/api/v1/upload"
        files = \\\\{'file': open(file_path, 'rb')\\\\}
        response = self.session.post(url, files=files)
        return response.json()

    def wait_for_analysis(self, file_hash, timeout=300):
        """Wait for analysis to complete"""
        start_time = time.time()
        while time.time() - start_time < timeout:
            status = self.get_scan_status(file_hash)
            if status.get('status') == 'completed':
                return True
            time.sleep(10)
        raise TimeoutError("Analysis timeout")

    def get_scan_status(self, file_hash):
        """Get scan status"""
        url = f"\\\\{self.server\\\\}/api/v1/scan_status"
        data = \\\\{'hash': file_hash\\\\}
        response = self.session.post(url, data=data)
        return response.json()

    def get_report(self, file_hash):
        """Get analysis report"""
        url = f"\\\\{self.server\\\\}/api/v1/report_json"
        data = \\\\{'hash': file_hash, 'scan_type': 'apk'\\\\}
        response = self.session.post(url, data=data)
        return response.json()

# Usage
if __name__ == "__main__":
    analyzer = MobSFBatchAnalyzer()
    analyzer.analyze_directory("/path/to/apk/files", "analysis_reports")

CI/CD Integration Script

#!/usr/bin/env python3
import sys
import requests
import json
import time

def mobsf_security_gate(apk_path, threshold_score=7.0):
    """
    Security gate for CI/CD pipeline
    Returns True if app passes security threshold
    """
    mobsf_url = "http://localhost:8000"

    # Upload APK
    upload_url = f"\\\\{mobsf_url\\\\}/api/v1/upload"
    files = \\\\{'file': open(apk_path, 'rb')\\\\}
    upload_response = requests.post(upload_url, files=files)

    if upload_response.status_code != 200:
        print("[-] Upload failed")
        return False

    file_hash = upload_response.json()['hash']

    # Wait for analysis
    time.sleep(60)  # Wait for analysis to complete

    # Get report
    report_url = f"\\\\{mobsf_url\\\\}/api/v1/report_json"
    report_data = \\\\{'hash': file_hash, 'scan_type': 'apk'\\\\}
    report_response = requests.post(report_url, data=report_data)

    if report_response.status_code != 200:
        print("[-] Report generation failed")
        return False

    report = report_response.json()

    # Calculate security score
    high_issues = len([issue for issue in report.get('findings', []) if issue.get('severity') == 'high'])
    medium_issues = len([issue for issue in report.get('findings', []) if issue.get('severity') == 'medium'])

    # Simple scoring: 10 - (high_issues * 2) - (medium_issues * 1)
    security_score = 10 - (high_issues * 2) - (medium_issues * 1)

    print(f"[+] Security Score: \\\\{security_score\\\\}/10")
    print(f"[+] High Issues: \\\\{high_issues\\\\}")
    print(f"[+] Medium Issues: \\\\{medium_issues\\\\}")

    if security_score >= threshold_score:
        print("[+] Security gate PASSED")
        return True
    else:
        print("[-] Security gate FAILED")
        return False

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python3 security_gate.py <apk_path>")
        sys.exit(1)

    apk_path = sys.argv[1]
    if mobsf_security_gate(apk_path):
        sys.exit(0)  # Success
    else:
        sys.exit(1)  # Failure

Integration Examples

Jenkins Pipeline Integration

pipeline \\\\{
    agent any

    stages \\\\{
        stage('Build') \\\\{
            steps \\\\{
                // Build your Android app
                sh './gradlew assembleDebug'
            \\\\}
        \\\\}

        stage('Security Analysis') \\\\{
            steps \\\\{
                script \\\\{
                    // Start MobSF container
                    sh 'docker run -d -p 8000:8000 --name mobsf opensecurity/mobsf:latest'

                    // Wait for MobSF to start
                    sleep(30)

                    // Run security analysis
                    def result = sh(
                        script: 'python3 security_gate.py app/build/outputs/apk/debug/app-debug.apk',
                        returnStatus: true
                    )

                    if (result != 0) \\\\{
                        error("Security analysis failed")
                    \\\\}
                \\\\}
            \\\\}

            post \\\\{
                always \\\\{
                    // Cleanup
                    sh 'docker stop mobsf && docker rm mobsf'
                \\\\}
            \\\\}
        \\\\}
    \\\\}
\\\\}

GitHub Actions Integration

name: Mobile Security Analysis

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  security-analysis:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v2

    - name: Set up JDK 11
      uses: actions/setup-java@v2
      with:
        java-version: '11'
        distribution: 'adopt'

    - name: Build APK
      run: ./gradlew assembleDebug

    - name: Start MobSF
      run:|
        docker run -d -p 8000:8000 --name mobsf opensecurity/mobsf:latest
        sleep 30

    - name: Run Security Analysis
      run:|
        python3 -c "
        import requests
        import time

        # Upload APK
        files = \\\\{'file': open('app/build/outputs/apk/debug/app-debug.apk', 'rb')\\\\}
        response = requests.post('http://localhost:8000/api/v1/upload', files=files)
        file_hash = response.json()['hash']

        # Wait and get report
        time.sleep(60)
        report_data = \\\\{'hash': file_hash, 'scan_type': 'apk'\\\\}
        report = requests.post('http://localhost:8000/api/v1/report_json', data=report_data)

        # Save report
        with open('security_report.json', 'w') as f:
            f.write(report.text)
        "

    - name: Upload Security Report
      uses: actions/upload-artifact@v2
      with:
        name: security-report
        path: security_report.json

    - name: Cleanup
      run: docker stop mobsf && docker rm mobsf

Troubleshooting

Common Installation Issues

# Python dependency issues
pip3 install --upgrade pip
pip3 install -r requirements.txt --force-reinstall

# Database migration issues
python3 manage.py migrate --run-syncdb
python3 manage.py migrate --fake-initial

# Permission issues (Linux/macOS)
sudo chown -R $USER:$USER .
chmod +x manage.py

Docker Issues

# Container won't start
docker logs mobsf

# Port already in use
docker ps -a
docker stop $(docker ps -q)
netstat -tulpn|grep 8000

# Volume mount issues
docker run -it --rm -v $(pwd)/data:/home/mobsf/.MobSF opensecurity/mobsf:latest

# Memory issues
docker run -it --rm -m 4g opensecurity/mobsf:latest

Analysis Issues

# APK analysis fails
# Check file size (default limit: 100MB)
ls -lh app.apk

# Check file format
file app.apk

# Enable debug mode
export MOBSF_DEBUG=1
python3 manage.py runserver

# Clear cache
rm -rf ~/.MobSF/downloads/*
rm -rf ~/.MobSF/uploads/*

Dynamic Analysis Issues

# Android emulator not detected
adb devices
adb kill-server
adb start-server

# Proxy issues
adb shell settings put global http_proxy localhost:1337
adb shell settings put secure http_proxy localhost:1337

# Agent installation fails
adb uninstall com.mobsf.mobsfy
adb install -r MobSFy.apk

# Certificate issues
adb push mobsf_ca.crt /sdcard/
# Install certificate manually in Android settings

Performance Optimization

# Increase memory allocation
export JAVA_OPTS="-Xmx4g -Xms2g"

# Optimize database
python3 manage.py dbshell
VACUUM;
REINDEX;

# Clean old analyses
python3 manage.py shell
from StaticAnalyzer.models import *
# Delete old records

# Use SSD storage for better I/O performance
# Configure database on SSD
# Use RAM disk for temporary files

Resources


This cheat sheet provides a comprehensive reference for using MobSF for mobile application security testing. Always ensure you have proper authorization before testing any mobile applications.