def retrieve_source_code(path, subpath): """ retrieve source codes from dataset path and store as files :param path: dataset path :param subpath: path to single apk :return: """ try: # analyse apk with androguard a, d, _ = AnalyzeAPK(path) # do not re-analyse files if os.path.isfile(subpath + '/' + a.get_package() + '.txt'): # only analyse new apks to save time print('file exists') return with open(subpath + '/' + a.get_package() + '.txt', 'w+') as code_file: for dalvik in d: for c_name in dalvik.get_classes_names(): if c_name.startswith('L' + a.package.replace('.', '/')): # retrieve java code # print(dalvik.get_class(c_name).get_source()) for method in dalvik.get_class(c_name).get_methods(): # method = m.get_method() code = "" byte_code = method.get_code() if byte_code is not None: byte_code = byte_code.get_bc() for i in byte_code.get_instructions(): code += i.get_name() + ' ' + i.get_output( ) + '\n' code_file.write(code.encode('utf-8') + '\n') except Exception: print('ignoring file')
def analyse(self, apk): a, d, dx = AnalyzeAPK(apk) print('Analysing', a.get_package()) self.package = a.get_package() self.graph = dx.get_call_graph(classname='L' + self.package.replace('.', '/') + '/*') # not only internal classes are in graph -> delete external nodes self.graph.remove_nodes_from([ (n if not n.class_name.startswith('L' + self.package.replace('.', '/')) else None) for n in self.graph.nodes ]) print(self.graph.order())
def loadApp(dir, cls): files = glob.glob(dir) files = sorted(files) done = read_log(cls) count = 0 print("\nSearching folder ", dir) if set(files).issubset(set(done)): print("\nNo new files to extract") return for f in files: done = read_log(cls) if f in done: continue print("\n\nOpening file ", f) try: a, d, dx = AnalyzeAPK(f) name = a.get_package() except: print("\nError opening ", f) done.append(f) continue yield (name, a, d, dx) del a del d del dx print(name, "extracted successfully...") print("\n\n", len(done) + 1, "files extracted. \n\n") write_log(cls, f)
def each(self, target): self.results = dict() try: apk, vm, vm_analysis = AnalyzeAPK(target) # First, get basic information about the APK self.results['name'] = apk.get_app_name() self.results['package'] = apk.get_package() self.results['permissions'] = apk.get_permissions() self.results['main_activity'] = apk.get_main_activity() self.results['receivers'] = apk.get_receivers() self.results['services'] = apk.get_services() self.results['main_activity_content'] = vm.get_class("L{};".format( self.results['main_activity']).replace('.', '/')).get_source() except: apk = None vm, vm_analysis = AnalyzeDex(target) self.results['dex'] = True # Then, run all the APK Plugins in order to see if this is a known malware for plugin in APKPlugin.__subclasses__(): plugin = plugin(target, apk, vm, vm_analysis) plugin.apply(self) return True
class Apkinfo: def __init__(self, apk_path): print(f"Init {apk_path}") self.apk, self.dalvikvmformat, self.analysis = AnalyzeAPK(apk_path) # get package name and the main launch activity to start the app. self._packageName = self.apk.get_package() self._mainActivity = self.apk.get_main_activity() @property def package_name(self): return self._packageName @property def main_activity(self): return self._mainActivity def get_android_api(self): """ Returns a list of Android APIs call. :return: (class_name, method_name) """ method_analysis = self.analysis.get_android_api_usage() for meth in method_analysis: yield meth.class_name, meth.name def launch_activity(self): return f"{self._packageName}/{self._mainActivity}"
def each(self, target): self.results = dict(name=None, files=[], package=None, permissions=[], declared_permissions=[], main_activity=None, activities=[], receivers=[], services=[], manifest=None, libraries=[], main_activity_content=None, internal_classes=[]) try: apk, vm, vm_analysis = AnalyzeAPK(target) # First, get basic information about the APK self.results['name'] = apk.get_app_name() self.results['files'] = apk.get_files_types() self.results['package'] = apk.get_package() self.results['permissions'] = apk.get_details_permissions() self.results[ 'declared_permissions'] = apk.get_declared_permissions_details( ) self.results['main_activity'] = apk.get_main_activity() self.results['activities'] = apk.get_activities() self.results['receivers'] = apk.get_receivers() self.results['services'] = apk.get_services() self.results['manifest'] = apk.get_android_manifest_axml().get_xml( ) self.results['libraries'] = list(apk.get_libraries()) self.results['main_activity_content'] = None self.results['internal_classes'] = [] try: self.results['main_activity_content'] = self.results[ 'main_activity_content'] = vm[0].get_class( "L{};".format(self.results['main_activity']).replace( '.', '/')).get_source() except: self.log('error', traceback.print_exc()) try: self.results['internal_classes'] = self._get_internal_classes( vm_analysis) self._store_internal_classes() except: self.log('error', traceback.print_exc()) # Then, run all the APK Plugins in order to see if this is a known malware for plugin in APKPlugin.__subclasses__(): plugin = plugin(target, apk, vm, vm_analysis) plugin.apply(self) except: self.log('error', traceback.print_exc()) return True
def analyze(self): self.packed_files = dict() self.malware_detect() for file in self.a.get_files(): file_type = check_header(self.a.get_file(file)[0:4].hex()) if file_type == "JAR": write_file_to_dir(self.output_dir, file.split("/")[-1], a.get_file(file)) try: a, d, dx = AnalyzeAPK(self.output_dir + file.split("/")[-1]) if a.get_package(): self.packed_files[self.a.get_package()] = {file: {}} else: continue except Exception as e: # not an APK file continue with open(PERMISSIONS_FILE) as json_file: permissions = json.load(json_file) perms_desc = {} dangerous_perms = {} if a.get_permissions(): for perm in a.get_permissions(): try: perms_desc[perm] = { "description": permissions[perm]["description"], "level": permissions[perm]["protection_lvl"] } if any( re.findall( r'dangerous', permissions[perm]["protection_lvl"], re.IGNORECASE)): # Permission is flagged as dangerous dangerous_perms[permissions[perm] ["permission"]] = permissions[ perm]["description"] except Exception as e: continue self.packed_files[self.a.get_package()][file] = dangerous_perms return { "packed_file": self.packed_files, "detected_malware": self.detected_malware }
def main(args=None, stdout_suppress=False, stderr_suppress=False): with open(os.devnull, "w") as devnull: old_stdout = sys.stdout old_stderr = sys.stderr sys.stdout = devnull if stdout_suppress else sys.stdout sys.stderr = devnull if stderr_suppress else sys.stderr results = None try: if args and not isinstance(args, list): raise TypeError(f"Args are {type(args)}, which is not a list.") _args = _parseargs(args) _a, _vm, _vmx = AnalyzeAPK(_args.file) print(("Analyse file: {:s}".format(_args.file))) print(("Package name: {:s}".format(_a.get_package()))) if "android.permission.INTERNET" in _a.get_permissions(): print("App requires INTERNET permission. Continue analysis...") _result = { "trustmanager": [], "hostnameverifier": [], "onreceivedsslerror": [], } _result = _check_all(_vm, _vmx) results = _result if not _args.xml and not _args.output: _print_result(_result, _java=_args.java) else: _xml_result( _a, _result, printed=True if _args.xml else False, file=_args.output if _args.output else None, ) if _args.dir: print("Store decompiled Java code in {:s}".format(_args.dir)) _store_java(_vmx, _vm, _args) else: print( "App does not require INTERNET permission. No need to worry about SSL misuse... Abort!" ) except: import traceback # printing stack trace traceback.print_exc() finally: sys.stdout = old_stdout sys.stderr = old_stderr return results
def each(self, target): self.tmpdir = tempdir() self.results = dict() apk, vm, vm_analysis = AnalyzeAPK(target) self.results['package'] = apk.get_package() self.validate_signature(target) ref_apk = self.download_reference_apk() self.validate_signature(ref_apk, "ref") self.results['verification_result'] = self.results['target_status'] and self.results['ref_status'] and (self.results['target_certificate'] == self.results['ref_certificate']) return True
def analyse(self): self.packed_files = dict() self.malware_detect() for file in self.a.get_files(): file_type = check_header(self.a.get_file(file)[0:4].hex()) if file_type == "JAR": if not os.path.isdir(self.output_dir): os.makedirs(self.output_dir) f = open(self.output_dir + file.split("/")[-1], 'wb') f.write(self.a.get_file(file)) f.close() try: a, d, dx = AnalyzeAPK(self.output_dir + file.split("/")[-1]) if a.get_package(): self.packed_files[self.a.get_package()] = {file: {}} else: continue except Exception as e: # not an APK file continue with open(PERMISSIONS_FILE) as json_file: permissions = json.load(json_file) perms_desc = {} dangerous_perms = {} if a.get_permissions(): for perm in a.get_permissions(): try: mapped = list(filter(lambda x: x["permission"] == perm, permissions)) perms_desc[perm] = {"desc": mapped[0]["desc"], "level": mapped[0]["protection_lvl"]} if any(re.findall(r'dangerous', mapped[0]["protection_lvl"], re.IGNORECASE)): # Permission is flagged as dangerous dangerous_perms[mapped[0]["permission"]] = mapped[0]["desc"] except Exception as e: continue self.packed_files[self.a.get_package()][file] = dangerous_perms return {"packed_file": self.packed_files, "detected_malware": self.detected_malware}
class AndroidPackage(object): """Static android information.""" def __init__(self, filepath): self.filepath = filepath self.apk = None self.analysis = None def _get_detailed_permissions(self): """Return a list of all permission requests by the application.""" perms = [] for k, v in self.apk.get_details_permissions().items(): perms.append({ "name": k, "protection_level": v[0], "description": v[2] }) return perms def _enumerate_services(self): """Return a list of all services with their actions""" services = [] for _service in self.apk.get_services(): service = {} service["name"] = _service service["action"] = [] intent_filters = self.apk.get_intent_filters("service", _service) if "action" in intent_filters: service["action"] = intent_filters["action"] services.append(service) return services def _enumerate_receivers(self): """Return a list of all BroadcastReceiver's with their actions""" receivers = [] for _receiver in self.apk.get_receivers(): receiver = {} receiver["name"] = _receiver receiver["action"] = [] intent_filters = self.apk.get_intent_filters("receiver", _receiver) if "action" in intent_filters: receiver["action"] = intent_filters["action"] receivers.append(receiver) return receivers def _enumerate_apk_files(self): """Return a list of files in the APK.""" files = [] for filename, filetype in self.apk.get_files_types().items(): buf = self.apk.zip.read(filename) files.append({ "name": filename, "md5": hashlib.md5(buf).hexdigest(), "size": len(buf), "type": filetype, }) return files def _enumerate_encrypted_assets(self): """Returns a list of files in the APK assets that have high entropy.""" files = [] for filename, filetype in self.apk.get_files_types().items(): if "assets" in filename: buf = self.apk.zip.read(filename) file_entropy = entropy.shannon_entropy(buf) if file_entropy > 0.9: files.append({ "name": filename, "entropy": file_entropy, "size": len(buf), "type": filetype, }) return files def _get_certificates_info(self): """Return a list of APK certificates""" certficates = [] for cert in self.apk.get_certificates(): not_valid_after = cert['tbs_certificate']['validity'][ 'not_after'].native not_valid_before = cert['tbs_certificate']['validity'][ 'not_before'].native certficates.append({ "sha1": cert.sha1.encode("hex"), "sha256": cert.sha256.encode("hex"), "issuer": cert.issuer.human_friendly, "subject": cert.subject.human_friendly, "not_valid_after": not_valid_after.strftime("%Y-%m-%d %H:%M:%S"), "not_valid_before": not_valid_before.strftime("%Y-%m-%d %H:%M:%S"), "public_key_algorithm": cert.public_key.algorithm, "public_key_size": "%d bit" % cert.public_key.bit_size, "signature_algorithm": cert.signature_algo + " with " + cert.hash_algo, "signature": cert.signature.encode("hex"), "serial_number": str(cert.serial_number) }) return certficates def _enumerate_native_methods(self): """Return a list of all methods compiled in the application""" methods = [] for mca in self.analysis.get_methods(): if mca.is_external(): continue if not mca.get_method().get_access_flags() & 0x0100: continue methods.append(self._get_pretty_method(mca)) return methods def _get_pretty_method(self, mca): """Return a string representation of an API method. @param mca: MethodClassAnalysis object. """ class_name = mca.get_method().get_class_name().replace("/", ".")[1:-1] method_name = mca.get_method().get_name() return "%s.%s%s" % (class_name, method_name, mca.descriptor) def _enumerate_api_calls(self): """Return a dictionary of all APIs with their xrefs.""" classes = [] exclude_pattern = re.compile( "^(Lcom/google/|Landroid|Ljava|Lcom/sun/|Lorg/apache/|" "Lorg/spongycastle|Lmyjava/|Lkotlin/)") for ca in self.analysis.get_classes(): if ca.is_external(): continue if exclude_pattern.match(ca.name): continue classes.append(ca.name) calls = [] for class_name in classes: for mca in self.analysis.find_methods(class_name): xrefs_to = [] for _, m, _ in mca.get_xref_to(): callee_class = m.get_class_name().replace("/", ".")[1:-1] callee_api = "%s.%s" % (callee_class, m.get_name()) xrefs_to.append(callee_api) if not xrefs_to: continue api = {} api["name"] = self._get_pretty_method(mca) api["callees"] = xrefs_to calls.append(api) return calls def run(self): """Run androguard to extract static APK information @return: dict of static features. """ from androguard.misc import AnalyzeAPK logging.getLogger("androguard.dvm").setLevel(logging.WARNING) logging.getLogger("androguard.analysis").setLevel(logging.WARNING) logging.getLogger("androguard.misc").setLevel(logging.WARNING) logging.getLogger("androguard.apk").setLevel(logging.CRITICAL) try: self.apk, _, self.analysis = AnalyzeAPK(self.filepath) except (OSError, zipfile.BadZipfile) as e: log.error("Error parsing APK file: %s", e) return None manifest = {} if self.apk.is_valid_APK(): manifest["package"] = self.apk.get_package() manifest["services"] = self._enumerate_services() manifest["receivers"] = self._enumerate_receivers() manifest["providers"] = self.apk.get_providers() manifest["activities"] = self.apk.get_activities() manifest["main_activity"] = self.apk.get_main_activity() manifest["permissions"] = self._get_detailed_permissions() apkinfo = {} apkinfo["manifest"] = manifest apkinfo["files"] = self._enumerate_apk_files() apkinfo["encrypted_assets"] = self._enumerate_encrypted_assets() apkinfo["is_signed_v1"] = self.apk.is_signed_v1() apkinfo["is_signed_v2"] = self.apk.is_signed_v2() apkinfo["certificates"] = self._get_certificates_info() apkinfo["native_methods"] = self._enumerate_native_methods() apkinfo["api_calls"] = self._enumerate_api_calls() return apkinfo
def generate_facts(app_folder,result_prefix,rules,storage=None): files = get_all_in_dir(app_folder,"*") send_intent_actions_stats = Counter() recv_intent_actions_stats = Counter() len_files = 0 is_apk = None for file in files: logging.info("Analyzing file %s",file) try: a,d, dx = AnalyzeAPK(file) is_apk = True # Create package to file relations except: is_apk = None print "Not valid APK file: "+file try: if is_apk: with open(result_prefix+"_packages.txt", 'a') as f: f.write("package('"+a.get_package()+"','"+ntpath.basename(file)+"').\n") # Permissions permissions = [] permissions.extend([(str(a.get_package()), permission) for permission in a.get_permissions()]) with open(result_prefix+"_uses_aux.txt", 'a') as f: for permission in permissions: f.write("uses('"+permission[0]+"','"+permission[1]+"').\n") # Intents logging.info("Looking for Intent Sends") sends = Set() sends.update([(str(a.get_package()),"i_"+intent.action) for intent in get_implicit_intents(a,d,dx)]) send_intent_actions_stats.update([send[1] for send in sends]) # Shared Prefs logging.info("Looking for Shared Prefs Sends") sends.update([(str(a.get_package()),"sp_"+shared.package+"_"+shared.preference_file) for shared in get_shared_preferences_writes(a,d,dx)]) with open(result_prefix+"_trans_aux.txt", 'a') as f: for send in sends: f.write("trans('"+send[0]+"','"+escape_quotes(send[1])+"').\n") # Receivers logging.info("Looking for Dynamic Receivers") receives = Set() receives.update([(str(a.get_package()),"i_"+receiver.get_action()) for receiver in get_dynamic_receivers(a,d,dx)]) logging.info("Looking for Static Receivers") receives.update([(str(a.get_package()),"i_"+receiver.get_action()) for receiver in get_static_receivers(a)]) recv_intent_actions_stats.update([receive[1] for receive in receives]) # Shared Prefs logging.info("Looking for Shared Prefs Receives") receives.update([(str(a.get_package()),"sp_"+shared.package+"_"+shared.preference_file) for shared in get_shared_preferences_reads(a,d,dx)]) with open(result_prefix+"_recv_aux.txt", 'a') as f: for receive in receives: f.write("recv('"+receive[0]+"','"+escape_quotes(receive[1])+"').\n") len_files += 1 utils.remove_duplicate_lines(result_prefix+"_uses_aux.txt",result_prefix+"_uses.txt",True) utils.remove_duplicate_lines(result_prefix+"_trans_aux.txt",result_prefix+"_trans.txt",True) utils.remove_duplicate_lines(result_prefix+"_recv_aux.txt",result_prefix+"_recv.txt",True) except: print "Error during analysis: "+file traceback.print_exc() if rules != "": with open(os.path.splitext(rules)[0]+"_program.pl", 'w') as f: #write packages with open(result_prefix+"_packages.txt", 'r') as to_read: f.writelines(to_read.readlines()) #write uses with open(result_prefix+"_uses.txt", 'r') as to_read: f.writelines(to_read.readlines()) #write trans with open(result_prefix+"_trans.txt", 'r') as to_read: f.writelines(to_read.readlines()) if storage: f.write("trans(A,'external_storage'):- uses(A,'android.permission.WRITE_EXTERNAL_STORAGE').\n") #write receives with open(result_prefix+"_recv.txt", 'r') as to_read: f.writelines(to_read.readlines()) if storage: f.write("recv(A,'external_storage'):- uses(A,'android.permission.WRITE_EXTERNAL_STORAGE').\n") f.write("recv(A,'external_storage'):- uses(A,'android.permission.READ_EXTERNAL_STORAGE').\n") with open(rules, 'r') as to_read: f.writelines(to_read.readlines()) with open(result_prefix+"_intent_send_stats",'w') as send_stats_file: send_stats_file.write("**** Results for send intent analysis ****\n") send_stats_file.write("Files analized: ") send_stats_file.write(str(len_files)) send_stats_file.write("\n") for send_stat in send_intent_actions_stats.most_common(): freq = send_stat[1]/len_files send_stats_file.write(send_stat[0]+", "+"{0:.2f}".format(round(freq,2))+", "+str(send_stat[1])+"\n") with open(result_prefix+"_intent_recv_stats",'w') as recv_stats_file: recv_stats_file.write("**** Results for send intent analysis ****\n") recv_stats_file.write("Files analized: ") recv_stats_file.write(str(len_files)) recv_stats_file.write("\n") for recv_stat in recv_intent_actions_stats.most_common(): freq = recv_stat[1]/len_files recv_stats_file.write(recv_stat[0]+", "+"{0:.2f}".format(round(freq,2))+", "+str(recv_stat[1])+"\n") logging.info("Results saved in %s files",result_prefix) return os.path.splitext(rules)[0]+"_program.pl"
def run_application_checks(PATH_TO_FILES,results_file): files=[] for i in range(0,5): P=PATH_TO_FILES.replace("_i","_"+str(i)) for path, subdirs, files_w in os.walk(P): for name in files_w: n=os.path.join(path, name) if not n.endswith(".apk"): continue files.append(n) results=open(results_file,"a",buffering=0)#open the results file #loop the files for f in files: subprocess.Popen("adb logcat -b all -c", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: a, d, dx = AnalyzeAPK(f) package_name=a.get_package() os.system("adb install "+f)#install the app p = subprocess.Popen("adb shell pm dump "+package_name+" | grep -A 1 MAIN",shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]#+" | grep -A 1 MAIN", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] lines=p.split("\n") #print lines intent_main="android.intent.action.MAIN:" activity_name="" activity_check=0 #get the main activity for line in lines: if intent_main in line: index=lines.index(line) opts=lines[index+1].split(" ") for option in opts: if option.startswith(package_name):#found the activity name activity_name=option activity_check=1 break break if activity_check==1: try: os.system("adb shell am start -a android.intent.action.MAIN -n "+activity_name)#run the app time.sleep(1.5) out = subprocess.Popen("adb logcat -d", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] lines=out.split("\n") dictOfLines = { l : 0 for l in lines} if "--------- beginning of crash" in dictOfLines: results.write(package_name+" 1\n") else: results.write(package_name+" 0\n") os.system("adb shell am force-stop "+package_name)#stop the app except: results.write(package_name+" 3\n") else: results.write(package_name+" 2\n") subprocess.Popen("adb logcat -b all -c", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) os.system("adb shell pm uninstall "+package_name) except: subprocess.Popen("adb logcat -b all -c", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) os.system("adb shell pm uninstall "+package_name) continue
class AndroHelper: def __init__(self, apk_path, output_dir): self.apk_path = apk_path # output directory self.output_dir = output_dir + "/" self.packed_files = dict() self.a, self.d, self.dx = AnalyzeAPK(self.apk_path) self.detected_malware = dict() def analyse(self): self.packed_files = dict() self.malware_detect() for file in self.a.get_files(): file_type = check_header(self.a.get_file(file)[0:4].hex()) if file_type == "JAR": if not os.path.isdir(self.output_dir): os.makedirs(self.output_dir) f = open(self.output_dir + file.split("/")[-1], 'wb') f.write(self.a.get_file(file)) f.close() try: a, d, dx = AnalyzeAPK(self.output_dir + file.split("/")[-1]) if a.get_package(): self.packed_files[self.a.get_package()] = {file: {}} else: continue except Exception as e: # not an APK file continue with open(PERMISSIONS_FILE) as json_file: permissions = json.load(json_file) perms_desc = {} dangerous_perms = {} if a.get_permissions(): for perm in a.get_permissions(): try: mapped = list(filter(lambda x: x["permission"] == perm, permissions)) perms_desc[perm] = {"desc": mapped[0]["desc"], "level": mapped[0]["protection_lvl"]} if any(re.findall(r'dangerous', mapped[0]["protection_lvl"], re.IGNORECASE)): # Permission is flagged as dangerous dangerous_perms[mapped[0]["permission"]] = mapped[0]["desc"] except Exception as e: continue self.packed_files[self.a.get_package()][file] = dangerous_perms return {"packed_file": self.packed_files, "detected_malware": self.detected_malware} def malware_detect(self): action_spy = ActionSpy(apk_path=self.apk_path, output_dir=self.output_dir) succeeded_test = action_spy.check() self.detected_malware["actionspy"] = succeeded_test wolf_rat = WolfRat(apk_path=self.apk_path, output_dir=self.output_dir) succeeded_test = wolf_rat.check() self.detected_malware["wolfrat"] = succeeded_test anubis = Anubis(apk_path=self.apk_path, output_dir=self.output_dir) succeeded_test = anubis.check() self.detected_malware["anubis"] = succeeded_test
def get_package_name(filename): a, d, dx = AnalyzeAPK(filename) return a.get_package()
if not os.path.isfile(args.APK): print("Invalid file path") sys.exit(1) ret_type = androconf.is_android(args.APK) if ret_type != "APK": print("Not an APK file") sys.exit(1) apk, dex, dexes = AnalyzeAPK(args.APK) res = { 'app_name': apk.get_app_name(), 'package_name': apk.get_package(), 'providers': apk.get_providers(), 'new_permissions': extract_new_permissions(apk.get_permissions()), 'filters': get_intent_filers(apk), 'certificate': {}, 'wearable': apk.is_wearable(), 'max_sdk_version': (apk.get_max_sdk_version()), 'min_sdk_version': int(apk.get_min_sdk_version()), 'version_code': apk.xml['AndroidManifest.xml'].get( '{http://schemas.android.com/apk/res/android}versionCode'),
def main(): input_dir = './recv' file_num = 1 tic = time.time() # user_input = raw_input("Masukkan Lokasi File: ") user_input = os.path.join(input_dir, '%06d.apk' % file_num) assert os.path.exists( user_input), "file tidak ditemukan pada, " + str(user_input) print("File Ditemukan !!") a, d, dx = AnalyzeAPK(user_input) dx.create_xref() package_name = a.get_package() permissions = a.get_permissions() val = [ "android.permission.READ_PHONE_STATE", "android.permission.RECEIVE_BOOT_COMPLETED", "android.permission.READ_SMS", "android.permission.WRITE_SMS", "android.permission.SEND_SMS", "android.permission.RECEIVE_SMS", "android.permission.CALL_PHONE", "android.permission.CHANGE_WIFI_STATE", "android.permission.RESTART_PACKAGES", "android.permission.GET_TASKS" ] # valApi = ['Landroid/content/Intent;->getAction()','Ldalvik/system/DexClassLoader;->loadClass','Landroid/telephony/TelephonyManager;->getDeviceId()','Landroid/telephony/TelephonyManager;->getLine1Number()','Landroid/telephony/TelephonyManager;->getNetworkOperator()','Landroid/telephony/TelephonyManager;->getSimSerialNumber()','Landroid/telephony/TelephonyManager;->getSimOperator()','Landroid/telephony/TelephonyManager;->getSubscriberId()','Landroid/telephony/SmsManager;->sendTextMessage','Landroid/location/LocationManager;->getLastKnownLocation'] ps = [] API_freq = dict() frequency(dx, API_freq) fs = open( os.path.join('./Documents/API-Kurang/coba', package_name + '.txt'), "w") #datas = str(sorted(API_freq.items(), key=lambda b:b[1], reverse=True)) datas = str(sorted(API_freq.items(), key=lambda b: b[1], reverse=True)) #print(sorted(API_freq.items(), key=lambda b:b[1], reverse=True)) print(permissions) for i in range(0, len(val)): if (check(permissions, val[i])): ps.append(1) else: ps.append(0) if 'Landroid/content/Intent;->getAction()' in datas: ps.append(1) else: ps.append(0) if 'Ldalvik/system/DexClassLoader;->loadClass' in datas: ps.append(1) else: ps.append(0) if 'Landroid/telephony/TelephonyManager;->getDeviceId()' in datas: ps.append(1) else: ps.append(0) if 'Landroid/telephony/TelephonyManager;->getLine1Number()' in datas: ps.append(1) else: ps.append(0) if 'Landroid/telephony/TelephonyManager;->getNetworkOperator()' in datas: ps.append(1) else: ps.append(0) if 'Landroid/telephony/TelephonyManager;->getSimSerialNumber()' in datas: ps.append(1) else: ps.append(0) if 'Landroid/telephony/TelephonyManager;->getSimOperator()' in datas: ps.append(1) else: ps.append(0) if 'Landroid/telephony/TelephonyManager;->getSubscriberId()' in datas: ps.append(1) else: ps.append(0) if 'Landroid/telephony/SmsManager;->sendTextMessage' in datas: ps.append(1) else: ps.append(0) if 'Landroid/location/LocationManager;->getLastKnownLocation' in datas: ps.append(1) else: ps.append(0) ps.append(package_name) print(ps) # fs.write(datas) # #print(time.time()-tic) # fs.close() #print(sorted(API_freq.items(), key=lambda b:b[1], reverse=True)) print(time.time() - tic) print("Done !!!") return ps file_num += 1
from androguard.misc import AnalyzeAPK import os, sys if len(sys.argv) != 2: print("Usage: strings.py <APK>") sys.exit(-1) print("analyzing APK...") a,d,dx = AnalyzeAPK(sys.argv[1]) print("") # package name packname = a.get_package().split(".")[-1] # filter strings, print only if occurs in application not in framework printable = [] longest_str = 0 for string in dx.strings: for _, meth in dx.strings[string].get_xref_from(): if packname in meth.class_name: printable.append([string, meth.class_name, meth.name]) if len(string) > longest_str: longest_str = len(string) # format output for p in printable: string = p[0].ljust(longest_str, ' ') print("{}\t{}\t{}".format(string, p[1], p[2]))
class AnalyseApkCrypto: """ Analyse an APK. Accessible attributes: app_name: str App name of the APK. package_name: str Package name of the APK. classes_with_crypto: dict[str, dict[str, MethInfo]] The keys are crypto names, the values are dictionaries, whose keys are method names, values are MethInfo objects. Only classes or methods that contains crypto names are included. elf_analyse_result: list[ApkElfAnalyseResult] A list of ApkElfAnalyseResult """ def __init__(self, filename): self.a, self.d, self.dx = AnalyzeAPK(filename) self.classes_with_crypto = {} self.elf_analyse_result, self.pack_elf = analyse_apk_elf(self.a.zip) self.package_name = self.a.get_package() self.method_cnt = len(list(self.dx.get_methods())) self.class_cnt = len(list(self.dx.get_classes())) self.elf_cnt = len(self.elf_analyse_result) try: self.app_name = self.a.get_app_name() except: # If we can't get app name, use package name instead logger.warning( 'Failed to get app name, using package name instead.') self.app_name = self.package_name self._get_classes_with_crypto() self._get_classes_with_crypto_strings() def _get_classes_methods(self): results = {} classes = self.dx.get_classes() for c in classes: results[c.name] = [] for meth in c.get_methods(): results[c.name].append(meth.name) return results def _get_classes_with_crypto(self): classes = self.dx.get_classes() for c in classes: ana = ClassCryptoAnalysis(c) if ana.matched: self.classes_with_crypto[ana.name] = ana def _get_classes_with_crypto_strings(self): for s_ana in self.dx.get_strings(): s_value = s_ana.get_orig_value() crypto_name = match_crypto_name(s_value, exclude_cert=True) if crypto_name: for c, meth in s_ana.get_xref_from(): # Type of c is androguard.core.analysis.analysis.ClassAnalysis # Type of meth is androguard.core.bytecodes.dvm.EncodedMethod if c.name in self.classes_with_crypto: self.classes_with_crypto[c.name].add_string( meth.name, s_value) else: class_ana = ClassCryptoAnalysis(c, from_str=True) class_ana.add_string(meth.name, s_value) self.classes_with_crypto[c.name] = class_ana def __repr__(self) -> str: ret = ( 'App name: {}'.format(self.app_name), 'Package name: {}'.format(self.package_name), 'Class info:\n{}'.format(self.classes_with_crypto.values()), ) return '\n'.join(ret)
from androguard.misc import AnalyzeAPK a, d, dx = AnalyzeAPK('Virus0e69af88dcbb469e30f16609b10c926c.apk') app_name = a.get_app_name() pkg = a.get_package() aversion = a.get_androidversion_code() print(app_name) print(pkg) print(aversion) ''' Certificado com.security.service 1 '''
class androidguard_decompiler(object): """ analysis result of androguard """ def __init__(self, app_path): """ :param app_path: local file path of app, should not be None analyse app specified by app_path """ self.app_path = app_path try: self.a = APK(self.app_path) except: raise self.ds = None self.dx = None def get_detailed_analysis(self): self.a, self.ds, self.dx = AnalyzeAPK(self.app_path) print("decompiler done.") # # def get_fast_analysis(self): # self.ds = DalvikVMFormat( self.a.get_dex() ) def save_session(self, outputpath): save_session([self.a, self.ds, self.dx], "{}/session.json".format(outputpath)) def process_and_savesession_multiplefolder(self, outputdirs): print("filename: ", os.path.basename(self.app_path)) filename = os.path.basename(self.app_path) filename = filename.replace(".apk", "") for outputdir in outputdirs: outputpath = "{}{}".format(outputdir, filename) if os.path.exists(outputpath): print("skip based on filename: {}.".format(filename)) return self.process_and_savesession(outputdirs[-1]) def process_and_savesession(self, outputdir): packagename = self.a.get_package() outputpath = "{}{}".format(outputdir, packagename) if os.path.exists(outputpath): print("skip based on package name: {}.".format(packagename)) return os.mkdir(outputpath) try: if self.ds == None: self.get_detailed_analysis() self.save_session(outputpath) # writeDexToFile(self.ds, packagename, outputpath) except Exception as e: print(e) os.rmdir(outputpath) def output_sorce(self, outputdir): packagename = self.a.get_package() outputpath = "{}{}".format(outputdir, packagename) if os.path.exists(outputpath): print("skip {}.".format(packagename)) return os.mkdir(outputpath) try: if self.ds == None: self.get_detailed_analysis() writeDexToFile(self.ds, packagename, outputpath) except Exception as e: print(e) os.rmdir(outputpath)