[MENU] | |||||||||
[THOUGHTS] | [TECH RESOURCES] | [TRASH TALK] | |||||||
[DANK MEMES] | [FEATURED ARTISTS] | [W] |
Hello guys!
I would like to share with you my last script to get dangerous permissions that you would like to analyze in second.
- #!/usr/bin/env python
- import logging
- import mimetypes
- import argparse
- import os
- import json
-
- from contextlib import suppress
- from typing import Tuple, List, Optional, Union, Dict
-
- from androguard.misc import AnalyzeAPK
- from androguard.core.bytecodes.apk import BrokenAPKError
-
- logger = logging.getLogger(__file__)
-
- DANGEROUS_TYPES = frozenset(
- {
- "android.permission.READ_CALENDAR",
- "android.permission.WRITE_CALENDAR",
- "android.permission.CAMERA",
- "android.permission.READ_CONTACTS",
- "android.permission.WRITE_CONTACTS",
- "android.permission.GET_ACCOUNTS",
- "android.permission.ACCESS_FINE_LOCATION",
- "android.permission.ACCESS_COARSE_LOCATION",
- "android.permission.RECORD_AUDIO",
- "android.permission.READ_PHONE_STATE",
- "android.permission.READ_PHONE_NUMBERS",
- "android.permission.CALL_PHONE",
- "android.permission.ANSWER_PHONE_CALLS",
- "android.permission.READ_CALL_LOG",
- "android.permission.WRITE_CALL_LOG",
- "android.permission.ADD_VOICEMAIL",
- "android.permission.USE_SIP",
- "android.permission.PROCESS_OUTGOING_CALLS",
- "android.permission.BODY_SENSORS",
- "android.permission.SEND_SMS",
- "android.permission.RECEIVE_SMS",
- "android.permission.READ_SMS",
- "android.permission.RECEIVE_WAP_PUSH",
- "android.permission.RECEIVE_MMS",
- "android.permission.READ_EXTERNAL_STORAGE",
- "android.permission.WRITE_EXTERNAL_STORAGE",
- "android.permission.MOUNT_UNMOUNT_FILESYSTEMS",
- "android.permission.READ_HISTORY_BOOKMARKS",
- "android.permission.WRITE_HISTORY_BOOKMARKS",
- "android.permission.INSTALL_PACKAGES",
- "android.permission.RECEIVE_BOOT_COMPLETED",
- "android.permission.READ_LOGS",
- "android.permission.CHANGE_WIFI_STATE",
- "android.permission.DISABLE_KEYGUARD",
- "android.permission.GET_TASKS",
- "android.permission.BLUETOOTH",
- "android.permission.CHANGE_NETWORK_STATE",
- "android.permission.ACCESS_WIFI_STATE",
- }
- )
- APK_MIMETYPE = "application/vnd.android.package-archive"
-
-
- def valid_mimetype(filename: str) -> bool:
- m_type = mimetypes.guess_type(filename)
- logger.debug(f"{filename} mimetype is {m_type[0]}")
- return APK_MIMETYPE == m_type[0]
-
-
- def extract_filenames(directory: str) -> Optional[List[str]]:
- logger.info("Getting files from the given directory.")
- with suppress(FileNotFoundError):
- files = os.listdir(directory)
- logger.debug(f"The given directory has this files {', '.join(files)}")
- return files
- logger.error("Error at getting files from the given directory.")
- return None
-
-
- def get_permissions(apk_file: AnalyzeAPK) -> List[str]:
- return apk_file.get_permissions()
-
-
- def analyze_file(filepath: str) -> List[str]:
- print(filepath)
- logger.info("Analyzing this file -> " + filepath)
- with suppress(BrokenAPKError):
- a, _, _ = AnalyzeAPK(filepath)
- perms = get_permissions(a)
- dangerous_perms = list(DANGEROUS_TYPES.intersection(perms))
- return dangerous_perms
- logger.error("Error at creating APK Object")
- return ["CORRUPTED"]
-
-
- def parser() -> Tuple[str, str]:
- arg_parser = argparse.ArgumentParser() # our wise arg_parser
- arg_parser.add_argument(
- "file_or_directory", help="Chosen apk file", nargs=1, type=str
- )
- arg_parser.add_argument(
- "--verbose", help="Verbose Output", dest="verbose", action="store_true"
- )
- arg_parser.add_argument("--out", help="Save output to a file", type=str)
- parsed = arg_parser.parse_args()
- if parsed.verbose:
- logging.basicConfig(level=logging.INFO)
-
- return parsed.file_or_directory[0], parsed.out
-
-
- def analyze_directory(directory: str) -> Dict[str, List[str]]:
- filenames = extract_filenames(directory)
- assert isinstance(filenames, list), "aloooo admini yok mu buranin"
- return dict(
- (filename, analyze_file(f"{directory}/{filename}"))
- for filename in (
- filename
- for filename in filenames
- if valid_mimetype(f"{directory}/{filename}")
- )
- )
-
-
- def analyze(filename: str) -> Optional[Union[Dict[str, List[str]], List[str]]]:
- if os.path.isdir(filename):
- return analyze_directory(filename)
- if os.path.isfile(filename):
- return analyze_file(filename)
- return None
-
-
- def save(data: str, output_fname: str):
- output_file = open(output_fname, "w")
- output_file.write(data)
- output_file.close()
- logger.info("Output file created at --> " + output_fname)
-
-
- def main():
- filename, output_name = parser()
- rep = json.dumps(analyze(filename), indent=4)
- if output_name:
- return save(rep, os.path.realpath(output_name))
- print(rep)
-
-
- if __name__ == "__main__":
- main()
- usage: main.py [-h] [--verbose] [--out OUT] file_or_directory
-
- positional arguments:
- file_or_directory Chosen apk file or directory of APKs
-
- optional arguments:
- -h, --help show this help message and exit
- --verbose Verbose Output
- --out OUT Save output to a file