Introducing a new way to review your PRs.

Read the announcement

mobsf / mobile-security-framework-mobsf

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.

View on GitHub

13 documents · Updated Nov 16, 2026

docs / django-core-routing-config

Django Core Routing and Configuration

Overview

MobSF's Django shell starts from two entry points. manage.py sets DJANGO_SETTINGS_MODULE=mobsf.MobSF.settings and delegates to Django's command runner; when the command is runserver, it also marks MOBSF_RUNSERVER=1 and registers an exit cleanup that calls the cleanup_android management command before the long-lived development reloader parent exits. The package entry point, mobsf/__main__.py, is the production-style launcher: it ensures migrations and role creation have run, then serves mobsf.MobSF.wsgi:application with gunicorn on Unix or waitress on Windows. mobsf/…/wsgi.py wraps Django's WSGI application in WhiteNoise, serving BASE_DIR/static under static/ and enabling autorefresh only when MOBSF_RUNSERVER=1.

Runtime configuration is assembled in mobsf/…/settings.py. It creates or locates MOBSF_HOME through mobsf/…/init.py, loads ~/…/config.py when USE_HOME is true, generates or reads the secret from MOBSF_SECRET_KEY / MOBSF_HOME/secret, and chooses PostgreSQL only when the required POSTGRES_* environment is present, otherwise SQLite at MOBSF_HOME/db.sqlite3. first_run() in mobsf/…/init.py also runs migrations/role creation for package installs and starts a background JADX download if MOBSF_HOME/tools/jadx/jadx-<version> is absent. Boolean environment flags are intentionally strict: mobsf/…/env.py treats only 1 (or Python True from an older config file) as enabled, and settings.py re-applies those flags after loading user config.

Requests are rooted at ROOT_URLCONF = mobsf.MobSF.urls and pass through the middleware stack declared in mobsf/…/settings.py: mobsf.MobSF.middleware.CompressionMiddleware, Django security/session/CSRF/auth/message/clickjacking middleware, and mobsf.MobSF.views.api.api_middleware.RestApiAuthMiddleware before sessions. CompressionMiddleware in mobsf/…/middleware.py gzips only non-streaming text-like responses, skips binary downloads and streaming logs, and intentionally avoids compressing the api_docs route because it renders a long-lived API secret.

mobsf/…/urls.py is the central request map. It always exposes login/logout/password routes from mobsf/…/authentication.py, user-management routes from mobsf/…/authorization.py, SAML routes from mobsf/…/saml2.py, and the entire /api/v1/... surface. Web UI routes are appended only when settings.API_ONLY is false; these include the home page, uploads, downloads, recent scans, scan status, static analyzer dispatch routes, suppression routes, Android/iOS dynamic analyzer routes, report routes, and helper AJAX endpoints. Importing urls.py has startup side effects: it prints the MobSF version/API key via mobsf/…/utils.py, installs subprocess tamper-detection hooks with init_exec_hooks(), and snapshots executable hashes with store_exec_hashes_at_first_run() from mobsf/…/security.py.

Authentication and authorization are centralized but deliberately bypassable for API/internal callers. mobsf/…/authentication.py defines a local login_required decorator that skips Django login enforcement when settings.DISABLE_AUTHENTICATION is true or when a decorated view is called with api=True; otherwise it delegates to Django's login_required. login_view() is POST-rate-limited using settings.RATELIMIT, sanitizes the next parameter through mobsf/MobSF/security.py:sanitize_redirect(), and disables password login when SAML is configured unless SP_ALLOW_PASSWORD is enabled. mobsf/…/authorization.py defines scan/suppress/delete permissions, maps them to the StaticAnalyzer app permission codenames, creates the maintainer/viewer groups, and provides a permission_required() wrapper with the same DISABLE_AUTHENTICATION / api=True bypass. Staff-only web user creation/deletion validates usernames using USERNAME_REGEX from mobsf/…/utils.py and assigns new users to the configured maintainer or viewer group.

SAML login lives in mobsf/…/saml2.py. /sso/ builds OneLogin settings from IDP_METADATA_URL or explicit IdP settings and sends the user to the IdP with a sanitized relative return URL. /sso/acs/ is CSRF-exempt because the IdP POST cannot carry Django's token; after OneLogin signature processing it rejects replayed assertion IDs in the process-local ASSERTION_IDS set, requires email and role attributes, maps any role containing the maintainer group string to MAINTAINER_GROUP and all other roles to VIEWER_GROUP, updates or creates a Django User, and redirects only to a sanitized relative RelayState.

The REST API authorization gate is mobsf/…/api_middleware.py. Any request whose path starts with /api/ must supply the API key in X-Mobsf-Api-Key or Authorization; the expected value comes from mobsf/MobSF/init.py:api_key(), which reads MOBSF_API_KEY_FILE, MOBSF_API_KEY, or hashes the secret file. OPTIONS requests get a CORS JSON response, and unauthorized API calls receive JSON before URL dispatch reaches any view. Because API endpoints call many web helpers with api=True, the middleware is the main API authentication boundary.

The home/upload/download layer in mobsf/…/home.py frames how scans enter MobSF. /upload/ is Upload.as_view, wrapped with login and Permissions.SCAN; it validates UploadFileForm, checks MIME and magic bytes through mobsf/MobSF/views/helpers.py:FileType, rejects iOS IPA static analysis on non-Linux/non-macOS platforms, then delegates to mobsf/MobSF/views/scanning.py:Scanning. Scanning stores the uploaded file under settings.UPLD_DIR/<md5>/<md5>.<ext>, creates a RecentScansDB row, and chooses the analyzer slug (static_analyzer, static_analyzer_ios, or static_analyzer_windows) that later routes such as /static_analyzer/<md5>/ use. Downloads are similarly centralized: /download/<path> serves only configured ALLOWED_EXTENSIONS from settings.DWD_DIR after security.is_safe_path() traversal checks, /download_binary/<md5>/ serves the original upload for a recorded scan, and SVGs are sanitized with security.sanitize_svg() before being returned.

Core security helpers in mobsf/…/security.py are shared by this routing layer and downstream analyzers. They provide redirect sanitization, filename/log sanitization, strict path traversal checks across POSIX/Windows/URL-encoded forms, SVG sanitization, Android/iOS path validation, command-injection detection, Windows batch argument guards, SSRF-safe safe_request() / safe_stream_request() that pin DNS answers and fail closed with upstream proxies, and runtime executable tampering detection by wrapping subprocess.Popen. The executable hash baseline covers bundled analyzer tools, downloaded tools, manage.py, common system binaries, and configured user binaries; if a known executable changes while the process is running, subprocess execution raises.

Management commands under mobsf/MobSF/management/commands support this shell. create_roles.py invokes authorization.create_authorization_roles() and is called by both first-run init and mobsf/__main__.py. clear_tasks.py deletes Django Q Task/OrmQ rows and MobSF EnqueuedTask rows. cleanup_android.py reads host-side Android dynamic analysis state from MOBSF_HOME/scan_state/*/proxy-state, finds online ADB devices, clears MobSF-owned proxy/Frida forwarding through the dynamic analyzer Environment, and removes per-scan state; manage.py runs this automatically when development runserver exits.

Coupling

  • If mobsf/…/settings.py changes MIDDLEWARE order, verify mobsf/…/api_middleware.py still runs before expensive API views and that session/auth-dependent web views in mobsf/…/home.py, authentication.py, and authorization.py still see request.user when needed.
  • If API route prefixes in mobsf/…/urls.py move away from /api/, update RestApiAuthMiddleware.process_request() in mobsf/…/api_middleware.py; it authenticates solely by request.path.startswith('/api/').
  • If upload extensions or MIME lists change in mobsf/…/settings.py, also update mobsf/MobSF/views/helpers.py:FileType, mobsf/MobSF/views/home.py:Upload.upload(), and mobsf/MobSF/views/scanning.py:Scanning; acceptance, storage extension, scan type, and analyzer route must stay aligned.
  • If auth bypass behavior changes, check both decorators: mobsf/MobSF/views/authentication.py:login_required and mobsf/MobSF/views/authorization.py:permission_required independently skip enforcement for settings.DISABLE_AUTHENTICATION and api=True.
  • If SAML group names or role attributes change in settings, verify mobsf/MobSF/views/saml2.py:get_user_role() and mobsf/MobSF/views/authorization.py:create_authorization_roles() together; SAML assigns groups by the same configured strings that role creation persists in Django auth.
  • If executable/tool locations change in settings or startup code, update mobsf/MobSF/security.py:get_executable_hashes() so init_exec_hooks() does not miss a binary that MobSF later launches through subprocess.Popen.
  • If Android dynamic state filenames change in mobsf/MobSF/utils.py:SCAN_STATE_FILES, update mobsf/…/cleanup_android.py; shutdown cleanup discovers only */proxy-state and clears only names understood by clear_analysis_state().

Risks

  • mobsf/…/urls.py performs heavy startup side effects at import time: version/update checks, subprocess hook installation, and hashing many tool/system binaries. If URLConf is imported by commands or tests that do not expect process-global subprocess.Popen wrapping, those processes inherit tamper-detection behavior before any request is served.
  • mobsf/…/saml2.py stores replayed assertion IDs in the process-local ASSERTION_IDS set. In multi-process deployments launched by mobsf/__main__.py or another WSGI server, a replay seen by one worker is not known to another; if worker count increases, SAML replay protection needs shared storage.
  • mobsf/…/api_middleware.py authenticates API requests only when the URL starts with /api/. Adding a new API-like route outside that prefix, or calling API-capable views through non-API URLs with api=True, bypasses this middleware and relies on the view-level decorators instead.
  • mobsf/…/settings.py sets ALLOWED_HOSTS = ['127.0.0.1', 'mobsf', '*'] and enables forwarded host/port handling by default. Deployments behind untrusted proxies must ensure the proxy strips hostile X-Forwarded-* headers, or URL generation in mobsf/MobSF/views/saml2.py:prepare_django_request() can reflect attacker-supplied host data unless SP_HOST is pinned.