Saltar a contenido

MobSF (Seguridad Móvil Framework) hoja de trucos

Overview

Seguridad Móvil Framework (MobSF) is an automated, all-in-one mobile application (Android/iOS/Windows) pen-testing, Análisis de Malware and security assessment framework capable of performing static and dynamic analysis. MobSF provides comprehensive security testing capabilities including static analysis, dynamic analysis, Análisis de Malware, and Seguridad de API testing.

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

instalación

# 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 instalación

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 (opciónal)
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 instalación

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/comandolinetools-linux-8512546_latest.zip
unzip comandolinetools-linux-8512546_latest.zip

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

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

Basic uso

Web Interface Access

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

# Default credenciales (if autenticación enabled)
# nombre de usuario: admin
# contraseña: (set during instalación)

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

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

comando 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 uso

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 repuerto
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
impuerto requests
impuerto json

class MobSFAPI:
    def __init__(self, server_url="http://localhost:8000"):
        self.server = server_url
        self.api_clave = 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_repuerto(self, file_hash, scan_type="apk"):
        """Get analysis repuerto"""
        url = f"\\\\{self.server\\\\}/api/v1/repuerto_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 repuerto"""
        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

# uso ejemplo
mobsf = MobSFAPI()
upload_result = mobsf.upload_file("app.apk")
file_hash = upload_result['hash']
scan_result = mobsf.scan_file(file_hash)
repuerto = mobsf.get_repuerto(file_hash)

Static Analysis Features

Android APK Analysis

# Automatic analysis includes:
# - Manifest analysis
# - Permission analysis
# - certificado analysis
# - Code analysis (Java/Kotlin)
# - Resource analysis
# - Análisis Binario
# - Security issues detection

# clave 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
# - Análisis Binario
# - Code analysis (Objective-C/Swift)
# - Resource analysis
# - Security configuración

# clave areas analyzed:
# - App Transpuerto Security
# - clavechain uso
# - URL schemes
# - File system permissions
# - Binary protections
# - Code signing

Custom Rules and firmas

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

# ejemplo custom rule
\\\\{
    "rules": [
        \\\\{
            "id": "custom_hardcoded_clave",
            "message": "Hardcoded API clave detected",
            "type": "Regex",
            "pattern": "api_clave\\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 objetivo application
# Click "Start Dynamic Analysis"

iOS Dynamic Analysis Setup

# Requires jailbroken iOS device
# Install MobSF agent via Cydia or manual instalación

# 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 documentación for agent instalación

Dynamic Analysis Features

# Runtime analysis capabilities:
# - API monitoring
# - File system monitoring
# - Network Análisis de Tráfico
# - Memory dumps
# - Method tracing
# - SSL pinning bypass
# - Root/jailbreak detection bypass
# - Screenshot capture
# - Activity monitoring

Advanced configuración

Custom Settings

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

# Database configuración
DATABASES = \\\\{
    'default': \\\\{
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mobsf_db',
        'USER': 'mobsf_user',
        'contraseña': 'contraseña',
        'host': 'localhost',
        'puerto': '5432',
    \\\\}
\\\\}

# Security settings
ALLOWED_hostS = ['localhost', '127.0.0.1', 'your-domain.com']
SECRET_clave = 'your-secret-clave-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_puerto = 1337

Docker Compose Setup

# docker-compose.yml
version: '3.8'

servicios:
  mobsf:
    image: opensecurity/mobsf:latest
    puertos:
      - "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_contraseña=contraseña
    volumes:
      - postgres_data:/var/lib/postgresql/data
    restart: unless-stopped

volumes:
  mobsf_data:
  postgres_data:

SSL/TLS configuración

# Generate SSL certificado
openssl req -x509 -newclave rsa:4096 -claveout clave.pem -out cert.pem -days 365 -nodes

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

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

Automation Scripts

Batch Analysis Script

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

class MobSFBatchAnalyzer:
    def __init__(self, server_url="http://localhost:8000"):
        self.server = server_url
        self.sesión = requests.sesión()

    def analyze_directory(self, directory_path, output_dir="repuertos"):
        """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 repuerto
                repuerto = self.get_repuerto(file_hash)
                repuerto_path = Path(output_dir) / f"\\\\{file_path.stem\\\\}_repuerto.json"

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

                print(f"[+] Repuerto saved: \\\\{repuerto_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.sesión.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.sesión.post(url, data=data)
        return response.json()

    def get_repuerto(self, file_hash):
        """Get analysis repuerto"""
        url = f"\\\\{self.server\\\\}/api/v1/repuerto_json"
        data = \\\\{'hash': file_hash, 'scan_type': 'apk'\\\\}
        response = self.sesión.post(url, data=data)
        return response.json()

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

CI/CD Integration Script

#!/usr/bin/env python3
impuerto sys
impuerto requests
impuerto json
impuerto 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 repuerto
    repuerto_url = f"\\\\{mobsf_url\\\\}/api/v1/repuerto_json"
    repuerto_data = \\\\{'hash': file_hash, 'scan_type': 'apk'\\\\}
    repuerto_response = requests.post(repuerto_url, data=repuerto_data)

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

    repuerto = repuerto_response.json()

    # Calculate security score
    high_issues = len([issue for issue in repuerto.get('findings', []) if issue.get('severity') == 'high'])
    medium_issues = len([issue for issue in repuerto.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("uso: 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 ejemplos

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: Seguridad Móvil 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 "
        impuerto requests
        impuerto 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 repuerto
        time.sleep(60)
        repuerto_data = \\\\{'hash': file_hash, 'scan_type': 'apk'\\\\}
        repuerto = requests.post('http: //localhost:8000/api/v1/repuerto_json', data=repuerto_data)

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

    - name: Upload Security Repuerto
      uses: actions/upload-artifact@v2
      with:
        name: security-repuerto
        path: security_repuerto.json

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

solución de problemas

Common instalación 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

# puerto 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
expuerto 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 instalación fails
adb uninstall com.mobsf.mobsfy
adb install -r MobSFy.apk

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

Performance Optimization

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

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

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

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

Resources


This hoja de trucos provides a comprehensive reference for using MobSF for mobile application security testing. Always ensure you have proper autorización before testing any mobile applications.