Mobile Security: Automation of APK Analysis with MobSF

From Elvis Wiki

Summary

This article explores the automation of the Mobile Security Framework MobSF using its API, highlighting key features of the automation of static analysis for mobile applications. It discusses the API endpoints available in MobSF and shows how they can be integrated into scripts. Practical use cases are being presented, to demostrate how MobSF automation enhances mobile seucurity during the development lifecycle of a mobile application.

Mobile Security Framework

Mobile Security Framework (MobSF) is a mobile application pentesting tool, capable of performing static as well as dynamic analyses. It is well known for its ability to analyze APK files for Android applications and IPA files for IOS applications. It provides detailed security assessments and vulnerability reports. MobSF supports a lot of different functionalities, including code analysis, binary analysis and runtime behavior analysis, therefore making it an important tool for mobile application security testing.

Automation of static analysis

Static analysis in MobSF can be automated by implementing one of the numerous different API endpoints, which offer a wide range of functionalities.

Upload a File

  • Function: API to upload a file. Supported file types are apk, zip, ipa and appx.
  • URL: /api/v1/upload
  • Sample Call:
curl -F 'file=@/Users/YourUser/Desktop/base.apk' http://localhost:8000/api/v1/upload -H "Authorization:YourAPIKey"

Scan a File

  • Function: API to scan a file that is already uploaded. Supports scanning apk, xapk, apks, jar, aar, zip, ipa, so, dylib, a, and appx extensions.
  • URL: /api/v1/scan
  • Sample Call:
curl -F 'file=@/Users/YourUser/Desktop/base.apk' http://localhost:8000/api/v1/scan -H "Authorization:YourAPIKey"

Display Recent Scans

  • Function: API to display recent scans.
  • URL: /api/v1/scans
  • Sample Call:
curl --url "http://localhost:8000/api/v1/scans" -H "Authorization:YourAPIKey"

Delete a Scan

  • Function: API to scan a file that is already uploaded. Supports scanning apk, xapk, apks, jar, aar, zip, ipa, so, dylib, a, and appx extensions.
  • URL: /api/v1/scan
  • Sample Call:
curl -X POST --url http://localhost:8000/api/v1/delete_scan --data "hash=HashOfAPK" -H "Authorization:YourAPIKey"

App Scorecard

  • Function: Get MobSF Application Security Scorecard.
  • URL: /api/v1/scorecard
  • Sample Call:
curl -X POST --url http://localhost:8000/api/v1/scorecard --data "hash=HashOfAPK" -H "Authorization:YourAPIKey"

Download PDF Report

  • Function: API to generate PDF report.
  • URL: /api/v1/download_pdf
  • Sample Call:
curl -X POST --url http://localhost:8000/api/v1/download_pdf --data "hash=HashOfAPK" -H "Authorization:YourAPIKey"

Generate JSON Report

  • Function: API to generate JSON report.
  • URL: /api/v1/report_json
  • Sample Call:
curl -X POST --url http://localhost:8000/api/v1/report_json --data "hash=HashOfAPK" -H "Authorization:YourAPIKey"

View Source Files

  • Function: API to view source files.
  • URL: /api/v1/view_source
  • Sample Call:
curl -X POST --url http://localhost:8000/api/v1/view_source --data "hash=HashOfAPK&type=apk&file=b/a/a/a/a/a.java" -H "Authorization:YourAPIKey"

Compare Apps

  • Function: API to compare scan results.
  • URL: /api/v1/compare
  • Sample Call:
curl -X POST --url http://localhost:8000/api/v1/compare --data "hash=HashOfAPK&hash2=HashOfOtherAPK" -H "Authorization:YourAPIKey"

Suppress by Rule

  • Function: Suppress findings by rule id.
  • URL: /api/v1/suppress_by_rule
  • Sample Call:
curl -X POST --url http://localhost:8000/api/v1/suppress_by_rule --data "hash=HashOfAPK&type=manifest&rule=RuleYouWantToSuppress" -H "Authorization:YourAPIKey"

Suppress by Files

  • Function: Suppress findings by files.
  • URL: /api/v1/suppress_by_files
  • Sample Call:
curl -X POST --url http://localhost:8000/api/v1/suppress_by_files --data "hash=HashOfAPK&type=code&rule=RuleYouWantToSuppress" -H "Authorization:YourAPIKey"

List Suppressions

  • Function: View suppressions associated with a scan.
  • URL: /api/v1/list_suppressions
  • Sample Call:
curl -X POST --url http://localhost:8000/api/v1/list_suppressions --data "hash=HashOfAPK" -H "Authorization:YourAPIKey"

Delete Suppressions

  • Function: Delete suppressions.
  • URL: /api/v1/delete_suppression
  • Sample Call:
curl -X POST --url http://localhost:8000/api/v1/list_suppressions --data "hash=HashOfAPK&kind=file&type=code&rule=RuleYouSuppressed" -H "Authorization:YourAPIKey"

Use Cases

CI/CD Integration

  • Description: Automatically analyize mobile applications during the build process, in order to catch security issues before application deployment.
  • Implementation: Include MobSF API calls into the CI/CD pipeline to carry out scans automatically. Retrieve and parse the reults to determine if the build passes all required security criteria.
  • Benefits: Every build is checked for scurity flaws, therefore reducing the risk of deploying vulnerable applications.

Scheduled Scans

  • Description: Perform regular security scans on mobile applications to ensure they remain secure over time after deployment.
  • Implementation: Set up cron jobs or scheduled tasks that use the MobSF API to scan at regular intervals. Collect and review the reports to see if new vulnerabilities apper.
  • Benefits: Maintains security assessment over time, helping to detect and mitigate vulnerabilities introduced with updates or changes in the threat landscape.

Bulk analysis

  • Description: Automate the analysis of multiple applications.
  • Implementation: Develop scripts that use the MobSF API to queue and process multiple applications at once, collecting and comparing the results.
  • Benefits: Manages the security assessment of portfolios of applications, making sure all of them are constantly evaluated and remain secure.


Example Code

This is a simple example of automation of static Analysis in MobSF. It uploads a file, scans this file, and locally creates a pdf report of the static analysis of the APK.

Important: Make sure to input your API Key and the URL to your MobSF instance before using the script.
import sys
import os
import json
import requests 
from requests_toolbelt.multipart.encoder import MultipartEncoder
# -----------------
SERVER = "Put the URL to your MobSF instance here, like http://127.0.0.1:8000"
APIKEY = 'Put your API Key here'
# -----------------
def upload(file_path):
   """Upload File"""
   print("Uploading file:", file_path)
   multipart_data = MultipartEncoder(fields={'file': (os.path.basename(file_path), open(file_path, 'rb'), 'application/octet-stream')})
   headers = {
       'Content-Type': multipart_data.content_type,
       'Authorization': APIKEY
   }
   print("Headers for upload:", headers)  # Debugging line to check headers
   response = requests.post(SERVER + '/api/v1/upload', data=multipart_data, headers=headers)
   print("Upload response:", response.text)
   return response.json()
# -----------------
def scan(upload_response):
   """Scan the file"""
   print("Scanning file")
   post_dict = {'hash': upload_response['hash']}
   headers = {'Authorization': APIKEY}
   response = requests.post(SERVER + '/api/v1/scan', data=post_dict, headers=headers)
   print("Scan response:", response.text)
   return upload_response['hash']
# -----------------
def pdf(file_hash):
   """Generate PDF Report"""
   print("Generate PDF report")
   headers = {'Authorization': APIKEY}
   data = {"hash": file_hash}
   response = requests.post(SERVER + '/api/v1/download_pdf', data=data, headers=headers, stream=True)
   with open("report.pdf", 'wb') as flip:
       for chunk in response.iter_content(chunk_size=1024):
           if chunk:
               flip.write(chunk)
   print("Report saved as report.pdf")
# -----------------
if __name__ == "__main__":
   if len(sys.argv) != 2:
       print("Usage: python script_name.py <apk_file>")
       sys.exit(1)
   apk_file_path = sys.argv[1]
# -----------------
   if not os.path.isfile(apk_file_path) or not apk_file_path.endswith(".apk"):
       print("Invalid APK file:", apk_file_path)
       sys.exit(1)
   upload_response = upload(apk_file_path)
# -----------------
   if 'hash' not in upload_response:
       print("Failed to upload the APK file. Response:", upload_response)
       sys.exit(1)
# -----------------
   file_hash = scan(upload_response)
   pdf(file_hash)


The script can be executed as follows:

python "ScriptName" "PathToAPK"

References