# Agent Skill Package: analyzing-android-malware-with-apktool You are loading a published Agent Skill. Follow SKILL.md exactly. Supporting files from the original zip are inlined below. When SKILL.md says to read `references/...` or `scripts/...`, use the matching FILE section here — do not say the file is missing. Canonical URL: https://skill.hk/s/analyzing-android-malware-with-apktool.md Human page: https://skill.hk/s/analyzing-android-malware-with-apktool Files (4): - SKILL.md - LICENSE - references/api-reference.md - scripts/agent.py ======================================================================== FILE: SKILL.md ======================================================================== --- name: analyzing-android-malware-with-apktool description: Perform static analysis of Android APK malware using apktool for resource decompilation, jadx for Java source recovery, and androguard for manifest inspection, dangerous permission-combination detection, and identification of obfuscated code, dynamic code loading, and reflection-based API calls. Use to statically triage a suspicious APK without executing it or to build mobile malware detection rules. domain: cybersecurity subdomain: malware-analysis tags: - Android - APK - apktool - jadx - androguard - mobile-malware - static-analysis - reverse-engineering version: '1.0' author: mahipal license: Apache-2.0 nist_csf: - DE.AE-02 - RS.AN-03 - ID.RA-01 - DE.CM-01 mitre_attack: - T1406 - T1407 - T1626.001 - T1655.001 - T1521.001 --- # Analyzing Android Malware with Apktool ## Overview Android malware distributed as APK files can be statically analyzed to extract permissions, activities, services, broadcast receivers, and suspicious API calls without executing the sample. This skill uses androguard for programmatic APK analysis, identifying dangerous permission combinations, obfuscated code patterns, dynamic code loading, reflection-based API calls, and network communication indicators. ## When to Use - When investigating security incidents that require analyzing android malware with apktool - When building detection rules or threat hunting queries for this domain - When SOC analysts need structured procedures for this analysis type - When validating security monitoring coverage for related attack techniques ## Prerequisites - Python 3.9+ with `androguard` - apktool (for resource decompilation) - jadx (for Java source recovery, optional) - Isolated analysis environment (VM or sandbox) - Sample APK files for analysis ## Steps 1. Parse APK with androguard to extract manifest metadata 2. Enumerate requested permissions and flag dangerous combinations 3. List activities, services, receivers, and providers from manifest 4. Scan for suspicious API calls (reflection, crypto, SMS, telephony) 5. Detect dynamic code loading patterns (DexClassLoader, Runtime.exec) 6. Extract hardcoded URLs, IPs, and C2 indicators from strings 7. Generate risk assessment report with MITRE ATT&CK mobile mappings ## Expected Output - JSON report with permission analysis, component listing, suspicious API calls, network indicators, and risk score - Extracted strings and potential IOCs from the APK ======================================================================== FILE: LICENSE ======================================================================== Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to the Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by the Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding any notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. Please do not remove or change the license header comment from a contributed file except when necessary. Copyright 2026 mukul975 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ======================================================================== FILE: references/api-reference.md ======================================================================== # API Reference — Analyzing Android Malware with Apktool ## Libraries Used - **androguard**: Python APK/DEX analysis — `AnalyzeAPK()`, permission enumeration, API call scanning - **re**: Regex extraction of URLs, IPs, base64 patterns from DEX strings - **json**: JSON serialization for analysis reports ## CLI Interface ``` python agent.py sample.apk permissions python agent.py sample.apk manifest python agent.py sample.apk apis python agent.py sample.apk strings python agent.py sample.apk full python agent.py sample.apk # defaults to full analysis ``` ## Core Functions ### `analyze_permissions(apk)` — Permission risk assessment Calls `apk.get_permissions()`. Flags 20 dangerous permissions including SEND_SMS, READ_CONTACTS, BIND_DEVICE_ADMIN, BIND_ACCESSIBILITY_SERVICE. Risk: CRITICAL >= 8 dangerous, HIGH >= 5, MEDIUM >= 2, LOW < 2. ### `analyze_manifest(apk)` — Manifest component extraction Calls `apk.get_activities()`, `get_services()`, `get_receivers()`, `get_providers()`. Returns package name, version, SDK levels, and all component lists. ### `scan_suspicious_apis(dx)` — Suspicious API call detection Searches DEX analysis for 14 patterns including: - `Runtime.exec`, `ProcessBuilder.start` — command execution - `DexClassLoader.loadClass` — dynamic code loading - `Method.invoke`, `Class.forName` — reflection - `Cipher.getInstance` — cryptographic operations - `SmsManager.sendTextMessage` — SMS abuse ### `extract_strings(dx, apk)` — IOC extraction from DEX strings Regex extraction of HTTP/HTTPS URLs, external IP addresses, and base64 strings. Filters out private IP ranges (10.x, 192.168.x, 172.16.x, 127.x). ### `detect_obfuscation(apk, dx)` — Obfuscation indicator detection Checks for single-letter class names (ProGuard), multi-DEX, native libraries. ### `full_analysis(apk_path)` — Comprehensive malware assessment ## Androguard API | Method | Returns | |--------|---------| | `AnalyzeAPK(path)` | `(APK, list[DEX], Analysis)` tuple | | `apk.get_permissions()` | List of Android permissions | | `apk.get_activities()` | Activity component names | | `apk.get_services()` | Service component names | | `apk.get_receivers()` | BroadcastReceiver names | | `apk.get_package()` | Package name string | | `dx.find_methods(classname, methodname)` | Matching method analysis objects | | `dx.get_strings()` | All strings from DEX files | | `dx.get_classes()` | All class analysis objects | ## Risk Scoring | Factor | Max Points | |--------|-----------| | Dangerous permissions (8 pts each) | 40 | | Suspicious API calls (10 pts each) | 30 | | External IPs (5 pts each) | 15 | | Obfuscation detected | 15 | ## Dependencies - `androguard` >= 3.4.0 - Isolated analysis environment recommended ======================================================================== FILE: scripts/agent.py ======================================================================== #!/usr/bin/env python3 """Agent for static analysis of Android APK malware using androguard.""" import json import re import argparse from datetime import datetime try: from androguard.core.apk import APK from androguard.core.dex import DEX from androguard.misc import AnalyzeAPK except ImportError: APK = None AnalyzeAPK = None DANGEROUS_PERMISSIONS = [ "android.permission.SEND_SMS", "android.permission.READ_SMS", "android.permission.RECEIVE_SMS", "android.permission.READ_CONTACTS", "android.permission.READ_CALL_LOG", "android.permission.RECORD_AUDIO", "android.permission.CAMERA", "android.permission.ACCESS_FINE_LOCATION", "android.permission.READ_PHONE_STATE", "android.permission.CALL_PHONE", "android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.READ_EXTERNAL_STORAGE", "android.permission.INSTALL_PACKAGES", "android.permission.REQUEST_INSTALL_PACKAGES", "android.permission.SYSTEM_ALERT_WINDOW", "android.permission.BIND_ACCESSIBILITY_SERVICE", "android.permission.BIND_DEVICE_ADMIN", "android.permission.RECEIVE_BOOT_COMPLETED", "android.permission.WRITE_SETTINGS", "android.permission.CHANGE_WIFI_STATE", ] SUSPICIOUS_API_PATTERNS = [ r"Ljava/lang/Runtime;->exec", r"Ljava/lang/ProcessBuilder;->start", r"Ldalvik/system/DexClassLoader;->loadClass", r"Ljava/lang/reflect/Method;->invoke", r"Ljava/lang/Class;->forName", r"Ljavax/crypto/Cipher;->getInstance", r"Landroid/telephony/SmsManager;->sendTextMessage", r"Landroid/app/admin/DevicePolicyManager;->lockNow", r"Landroid/content/pm/PackageManager;->setComponentEnabledSetting", r"Ljava/net/HttpURLConnection;->connect", r"Lokhttp3/OkHttpClient;->newCall", r"Landroid/webkit/WebView;->loadUrl", r"Landroid/os/Build;->SERIAL", r"Landroid/provider/Settings\$Secure;->getString", ] def analyze_permissions(apk): """Analyze requested permissions and flag dangerous ones.""" permissions = apk.get_permissions() dangerous = [p for p in permissions if p in DANGEROUS_PERMISSIONS] return { "total_permissions": len(permissions), "permissions": permissions, "dangerous_permissions": dangerous, "dangerous_count": len(dangerous), "permission_risk": "CRITICAL" if len(dangerous) >= 8 else "HIGH" if len(dangerous) >= 5 else "MEDIUM" if len(dangerous) >= 2 else "LOW", } def analyze_manifest(apk): """Extract manifest components: activities, services, receivers, providers.""" activities = apk.get_activities() services = apk.get_services() receivers = apk.get_receivers() providers = apk.get_providers() return { "package_name": apk.get_package(), "app_name": apk.get_app_name(), "version_name": apk.get_androidversion_name(), "version_code": apk.get_androidversion_code(), "min_sdk": apk.get_min_sdk_version(), "target_sdk": apk.get_target_sdk_version(), "activities": list(activities), "services": list(services), "receivers": list(receivers), "providers": list(providers), "activity_count": len(activities), "service_count": len(services), "receiver_count": len(receivers), "provider_count": len(providers), } def scan_suspicious_apis(dx): """Scan DEX analysis for suspicious API calls.""" findings = [] if not dx: return findings for pattern in SUSPICIOUS_API_PATTERNS: class_name = pattern.split(";->")[0] + ";" method_name = pattern.split(";->")[1] if ";->" in pattern else None for method in dx.find_methods(classname=class_name, methodname=method_name): xrefs = list(method.get_xref_from()) if xrefs: findings.append({ "api": pattern, "callers": len(xrefs), "first_caller_class": str(xrefs[0][0].name) if xrefs else None, }) return findings def extract_strings(dx, apk): """Extract suspicious strings: URLs, IPs, base64 patterns.""" url_pattern = re.compile(r'https?://[\w\-._~:/?#\[\]@!$&\'()*+,;=]+', re.IGNORECASE) ip_pattern = re.compile(r'\b(?:\d{1,3}\.){3}\d{1,3}\b') b64_pattern = re.compile(r'[A-Za-z0-9+/]{30,}={0,2}') urls = set() ips = set() b64_strings = [] if dx: for s in dx.get_strings(): val = str(s) urls.update(url_pattern.findall(val)) ips.update(ip_pattern.findall(val)) b64_matches = b64_pattern.findall(val) b64_strings.extend(b64_matches[:5]) private_ips = {"10.", "192.168.", "172.16.", "127.0."} external_ips = [ip for ip in ips if not any(ip.startswith(p) for p in private_ips)] return { "urls": sorted(urls)[:30], "external_ips": sorted(external_ips)[:20], "suspicious_base64": b64_strings[:10], "url_count": len(urls), "external_ip_count": len(external_ips), } def detect_obfuscation(apk, dx): """Detect code obfuscation indicators.""" indicators = [] if dx: short_class_names = 0 for cls in dx.get_classes(): name = str(cls.name) parts = name.replace("/", ".").split(".") if any(len(p) == 1 and p.isalpha() for p in parts): short_class_names += 1 if short_class_names > 10: indicators.append({"type": "single_letter_classes", "count": short_class_names}) dex_files = [f for f in apk.get_files() if f.endswith(".dex")] if len(dex_files) > 1: indicators.append({"type": "multi_dex", "dex_count": len(dex_files)}) native_libs = [f for f in apk.get_files() if f.endswith(".so")] if native_libs: indicators.append({"type": "native_libraries", "libs": native_libs[:10]}) return { "obfuscation_indicators": indicators, "likely_obfuscated": len(indicators) > 0, } def full_analysis(apk_path): """Run comprehensive APK malware analysis.""" if not APK or not AnalyzeAPK: return {"error": "androguard not installed: pip install androguard"} a, d, dx = AnalyzeAPK(apk_path) perm_analysis = analyze_permissions(a) manifest = analyze_manifest(a) suspicious_apis = scan_suspicious_apis(dx) strings = extract_strings(dx, a) obfuscation = detect_obfuscation(a, dx) risk_score = 0 risk_score += min(perm_analysis["dangerous_count"] * 8, 40) risk_score += min(len(suspicious_apis) * 10, 30) risk_score += min(strings["external_ip_count"] * 5, 15) risk_score += 15 if obfuscation["likely_obfuscated"] else 0 risk_score = min(risk_score, 100) return { "analysis_type": "Android APK Static Analysis", "timestamp": datetime.utcnow().isoformat(), "file": apk_path, "manifest": manifest, "permissions": perm_analysis, "suspicious_apis": suspicious_apis[:20], "strings": strings, "obfuscation": obfuscation, "risk_score": risk_score, "risk_level": "CRITICAL" if risk_score >= 70 else "HIGH" if risk_score >= 50 else "MEDIUM" if risk_score >= 25 else "LOW", "mitre_techniques": [ {"id": "T1418", "name": "Software Discovery"} if manifest["service_count"] > 5 else None, {"id": "T1417", "name": "Input Capture"} if "android.permission.BIND_ACCESSIBILITY_SERVICE" in perm_analysis["permissions"] else None, {"id": "T1582", "name": "SMS Control"} if "android.permission.SEND_SMS" in perm_analysis["permissions"] else None, {"id": "T1404", "name": "Exploitation for Privilege Escalation"} if any("DevicePolicyManager" in a.get("api", "") for a in suspicious_apis) else None, ], } def main(): parser = argparse.ArgumentParser(description="Android APK Malware Analysis Agent") parser.add_argument("apk", help="Path to APK file") sub = parser.add_subparsers(dest="command") sub.add_parser("permissions", help="Analyze permissions") sub.add_parser("manifest", help="Extract manifest components") sub.add_parser("apis", help="Scan for suspicious API calls") sub.add_parser("strings", help="Extract URLs, IPs, and encoded strings") sub.add_parser("full", help="Full malware analysis") args = parser.parse_args() if args.command == "full" or args.command is None: result = full_analysis(args.apk) else: a, d, dx = AnalyzeAPK(args.apk) if args.command == "permissions": result = analyze_permissions(a) elif args.command == "manifest": result = analyze_manifest(a) elif args.command == "apis": result = scan_suspicious_apis(dx) elif args.command == "strings": result = extract_strings(dx, a) print(json.dumps(result, indent=2, default=str)) if __name__ == "__main__": main()