Static analysis common pipeline
Overview
The shared static-analysis layer is the infrastructure that Android, iOS, Windows, and standalone library analyzers build on before they persist or render platform-specific reports. The database contract lives in mobsf/…/models.py: RecentScansDB tracks scan metadata and logs by MD5, StaticAnalyzerAndroid, StaticAnalyzerIOS, and StaticAnalyzerWindows store the full static report payloads in text fields, SuppressFindings stores package-scoped suppression rules, and EnqueuedTask records Django-Q scan queue state. Input validation for source viewing and API report lookups is in mobsf/…/forms.py, where file viewer requests reject path traversal and allow only source/config extensions plus app.config and app.manifest.
Upload and extraction helpers are centered in mobsf/…/shared_func.py. hash_gen() computes SHA-1/SHA-256 while appending scan status; unzip() extracts APK/IPA/source archives with encrypted-file skipping, reserved APK filename conflict handling, Zip Slip checks, per-file and total uncompressed-size budgets from settings, and a hardened os_unzip() fallback. The fallback copies the archive through neutralize_zip_special_modes(), extracts into an isolated staging directory, and imports only verified regular files via _import_staged_files() so symlinks, pipes, devices, and paths outside the extraction root do not enter the scan tree. The same file also provides .a archive handling (ar_extract(), ar_os(), and lipo_thin()), URL/email extraction, Android source-root detection for Flutter scans, Java/Kotlin source-root discovery, string/entropy collection, library rescan routing through scan_library(), and app comparison entry validation through compare_apps().
Asynchronous scan orchestration is in mobsf/…/async_task.py. async_analysis() prevents duplicate scans by checking RecentScansDB completion state and recent EnqueuedTask rows within settings.ASYNC_ANALYSIS_TIMEOUT, prunes old queue rows above settings.QUEUE_MAX_SIZE, enqueues the platform analyzer through django_q.tasks.async_task(), and records a new EnqueuedTask. mark_task_started(), mark_task_completed(), and list_tasks() keep UI/API task state synchronized with scan logs, while the post_execute receiver detect_timeout() marks tasks failed when Django-Q returns a timeout string.
The common SAST wrapper is mobsf/…/sast_engine.py. SastEngine and ChoiceEngine wrap libsast.Scanner, PatternMatcher, and ChoiceMatcher, select a multiprocessing backend based on settings.MULTIPROCESSING, settings.ASYNC_ANALYSIS, and Windows compatibility, run scans through run_with_timeout(settings.SAST_TIMEOUT), and normalize finding file paths/line ranges into the report shape consumed by DB save logic, source viewers, suppression, dashboards, and PDFs.
JavaScript, TypeScript, hybrid, and Hermes analysis is implemented under mobsf/StaticAnalyzer/views/common/js_analysis/. analyzer.py is the entry point used by Android and iOS helpers; it chooses roots (assets and res/raw for APKs, app root for IPAs/source ZIPs), detects frameworks from package.json and path patterns, parses Cordova/Capacitor/Expo config files through configs.py, detects packaged source maps and Expo dev-client bundles, extracts URLs/emails/secrets, optionally beautifies minified JS, decompiles Hermes bytecode with hermes.py, and runs collected files through JS SAST rules in views/…/js_rules.yaml. sast.py bounds URL scanning, chunks huge files, batches SAST input by bytes, caps reported line lists, and maps temporary chunk paths back to real relative paths. viewer.py provides safe minified-code formatting and paged source windows so large bundles can be displayed without loading unbounded content into the DOM.
Binary-analysis primitives are under mobsf/StaticAnalyzer/views/common/binary/. lib_analysis.py walks extracted scan trees for .so, .dylib, .o, and iOS framework executables, then delegates to ELFChecksec in elf.py or MachOChecksec in macho.py. Those classes use lief.parse() with settings.BINARY_ANALYSIS_TIMEOUT and report NX/PIE/canary/RELRO/RPATH/RUNPATH/fortify/symbol status for ELF and NX/PIE/canary/ARC/RPATH/code-signature/encryption/symbol status for Mach-O. strings.py prefers the OS strings utility and falls back to mobsf/…/strings.py; extracted strings and symbols are later used for URL, secret, tracker, and binary rule analysis. Standalone static-library .a scans are orchestrated in views/…/a.py, which extracts archive members, runs common library analysis, performs iOS binary rule matching, extracts string metadata, checks domains, trackers, Firebase, VirusTotal, and saves an iOS-shaped context.
Shared enrichment utilities feed multiple report types. mobsf/…/secret_detection.py combines known-format token regexes with entropy detection from entropy.py, while suppressing common Flutter, Dart, Swift, and public-library false positives. sbom.py extracts offline dependency inventories from Android and iOS trees by safely reading bounded lock/config files such as Gradle version catalogs, pom.properties, pubspec.lock, package-lock.json, Podfile.lock, SwiftPM Package.resolved, Cartfile.resolved, and framework Info.plist files. firebase.py converts discovered Firebase URLs/credentials into findings by probing .firebaseio.com database hosts with SSRF host validation and checking Remote Config. technology.py derives report-header language/framework/build/protection/instrumentation badges from collected paths, APKiD output, native library names, JS framework results, and iOS framework paths.
Reporting and review helpers are shared as well. suppression.py exposes authenticated suppression endpoints, resolves a checksum to Android package name or iOS bundle ID, stores rule/file suppressions in SuppressFindings, and applies them to code, JS, and manifest findings while recomputing severity summaries. appsec.py builds Android/iOS scorecards from persisted DB contexts, merging code, JS, permissions, certificates, network/ATS, binary, domain, Firebase, tracker, and secret signals into severity buckets and a score. pdf.py loads the relevant platform DB row, reconstructs the report context via platform DB interaction helpers, adds AppSec and average CVSS data, optionally enriches with VirusTotal, and renders templates through xhtml2pdf with a resource policy restricted to MobSF static files and the download directory. comparer.py currently compares only completed Android scans, reconstructing both DB contexts and diffing permissions, Android APIs, URLs, browsable activities, and APKiD detections.
The mobsf/StaticAnalyzer/tools/ tree contains bundled analyzers and parsers consumed by platform analyzers rather than normal web code: APK tooling jars, iOS binary tools, a Python strings fallback, and a vendored Androguard 4 implementation under tools/androguard4/ for APK, AXML, ARSC, certificate, and resource parsing.
Coupling
- If fields are added to or renamed in mobsf/…/models.py, update the corresponding platform DB interaction helpers and report builders that deserialize text fields with
python_dict()/python_list(); common consumers in views/…/pdf.py, views/…/appsec.py, views/…/suppression.py, and views/comparer.py expect keys such asCODE_ANALYSIS,JS_ANALYSIS,SBOM,SECRETS, package/bundle identifiers, and file lists to keep their current shapes. - If the SAST finding schema changes in mobsf/…/sast_engine.py or views/…/configs.py, verify suppression, AppSec, PDF, and source-viewer paths. views/…/suppression.py expects findings keyed by rule ID with
filesmaps andmetadata.severity; views/…/appsec.py readsmetadata.description,metadata.ref, and file keys; views/…/sast.py caps comma-separated line strings for the viewer. - If archive extraction behavior changes in mobsf/…/shared_func.py, verify Android/iOS source extraction and standalone library analysis. Later stages assume extracted entries are regular files under
settings.UPLD_DIR/<checksum>and that reserved APK names, symlinks, pipes, device files, Zip Slip/AR slip entries, and oversized archive contents have already been filtered. - If JS/hybrid limits or extensions change in mobsf/…/constants.py, check forms.py and viewer.py as well. The source-view form allows JS/TS/hybrid extensions, analyzer.py decides what to scan, and viewer.py decides how large files are paged; drift can make a file scanned but not viewable, or viewable but never scanned.
- If new frameworks or dependency formats are detected in views/…/frameworks.py or views/…/sbom.py, update views/…/technology.py and report templates that display framework/SBOM groups so dependency evidence appears consistently in headers, dashboards, PDF/JSON reports, and platform-specific report pages.
- If task timeout or queue settings change, verify both
async_analysis()anddetect_timeout()in views/…/async_task.py. Duplicate-scan suppression, queue pruning, task status display, and timeout marking are based onsettings.ASYNC_ANALYSIS_TIMEOUT,settings.QUEUE_MAX_SIZE, scan logs, and Django-Q result strings rather than a single authoritative worker state.
Risks
- mobsf/…/models.py defines
EnqueuedTask.__str__()asreturn f'{self.name} ({self.status})', but the model has nonamefield. Any admin/debug code that stringifies anEnqueuedTaskcan raiseAttributeErrorinstead of displaying task state. - mobsf/…/suppression.py computes manifest suppression summaries with
elif ['severity'] == INFO:instead of checkingi['severity']. Manifest info findings will not increment the intended info count, so suppressed/remaining manifest severity summaries can be inaccurate. - mobsf/…/shared_func.py has two extraction paths (
unzip()andos_unzip()) plus AR fallback paths. If a future change bypasses the shared size-budget, safe-path, and special-file checks in only one fallback path, malicious archives can be processed differently depending on whether Pythonzipfilesucceeds, OSunzipis available, orarfallback is used. - mobsf/…/hermes.py writes decompiled <bundle>.dec.js files next to the original bundle during analysis and then includes them in JS SAST. If cleanup or candidate filtering regresses, generated files can be re-scanned or exposed as original source; files.py and analyzer.py currently skip .dec.js candidates and delete failed decompilation outputs to avoid that loop.