def main(options, arguments): if options.database == None or options.config == None: return s = dalvik_elsign.MSignature(options.database, options.config, options.verbose != None, ps=dalvik_elsign.PublicSignature) if options.input != None: ret_type = androconf.is_android(options.input) print(os.path.basename(options.input), ":", end=' ') sys.stdout.flush() if ret_type == "APK": try: a = apk.APK(options.input) if a.is_valid_APK(): display(s.check_apk(a), options.verbose) else: print("INVALID") except Exception as e: print("ERROR", e) elif ret_type == "DEX": display(s.check_dex(read(options.input)), options.verbose) elif options.directory != None: for root, dirs, files in os.walk(options.directory, followlinks=True): if files != []: for f in files: real_filename = root if real_filename[-1] != "/": real_filename += "/" real_filename += f ret_type = androconf.is_android(real_filename) if ret_type == "APK": print(os.path.basename(real_filename), ":", end=' ') sys.stdout.flush() try: a = apk.APK(real_filename) if a.is_valid_APK(): display(s.check_apk(a), options.verbose) else: print("INVALID APK") except Exception as e: print("ERROR", e) elif ret_type == "DEX": try: print(os.path.basename(real_filename), ":", end=' ') sys.stdout.flush() display(s.check_dex(read(real_filename)), options.verbose) except Exception as e: print("ERROR", e) elif options.version != None: print("Androsign version %s" % androconf.ANDROGUARD_VERSION)
def main(options, arguments) : ri = risk.RiskIndicator() ri.add_risk_analysis( risk.RedFlags() ) ri.add_risk_analysis( risk.FuzzyRisk() ) if options.input != None : ret_type = androconf.is_android( options.input ) if ret_type == "APK" : a = apk.APK( options.input ) analyze_app( options.input, ri, a ) elif ret_type == "DEX" : analyze_dex( options.input, ri, open(options.input, "r").read() ) elif options.directory != None : for root, dirs, files in os.walk( options.directory, followlinks=True ) : if files != [] : for f in files : real_filename = root if real_filename[-1] != "/" : real_filename += "/" real_filename += f ret_type = androconf.is_android( real_filename ) if ret_type == "APK" : try : a = apk.APK( real_filename ) analyze_app( real_filename, ri, a ) except Exception, e : print e elif ret_type == "DEX" : analyze_dex( real_filename, ri, open(real_filename, "r").read() )
def main(options, arguments): if options.database == None or options.config == None: return s = dalvik_elsign.MSignature( options.database, options.config, options.verbose != None, ps=dalvik_elsign.PublicSignature ) if options.input != None: ret_type = androconf.is_android(options.input) print(os.path.basename(options.input), ":", end=" ") sys.stdout.flush() if ret_type == "APK": try: a = apk.APK(options.input) if a.is_valid_APK(): display(s.check_apk(a), options.verbose) else: print("INVALID") except Exception as e: print("ERROR", e) elif ret_type == "DEX": display(s.check_dex(read(options.input)), options.verbose) elif options.directory != None: for root, dirs, files in os.walk(options.directory, followlinks=True): if files != []: for f in files: real_filename = root if real_filename[-1] != "/": real_filename += "/" real_filename += f ret_type = androconf.is_android(real_filename) if ret_type == "APK": print(os.path.basename(real_filename), ":", end=" ") sys.stdout.flush() try: a = apk.APK(real_filename) if a.is_valid_APK(): display(s.check_apk(a), options.verbose) else: print("INVALID APK") except Exception as e: print("ERROR", e) elif ret_type == "DEX": try: print(os.path.basename(real_filename), ":", end=" ") sys.stdout.flush() display(s.check_dex(read(real_filename)), options.verbose) except Exception as e: print("ERROR", e) elif options.version != None: print("Androsign version %s" % androconf.ANDROGUARD_VERSION)
def main(options, arguments) : if options.input != None : ret_type = androconf.is_android( options.input ) print os.path.basename(options.input), ":" if ret_type == "APK" : #try : if 1==1: a = apk.APK(options.input, zipmodule=2) print a.package print a.androidversion["Code"] print a.androidversion["Name"] print a.permissions sys.exit() if a.is_valid_APK() : a.show() display_dvm_info( a ) else : print "INVALID" #except Exception, e : else: print "ERROR", e import traceback traceback.print_exc() elif options.directory != None : for root, dirs, files in os.walk( options.directory, followlinks=True ) : if files != [] : for f in files : real_filename = root if real_filename[-1] != "/" : real_filename += "/" real_filename += f ret_type = androconf.is_android( real_filename ) if ret_type == "APK" : print os.path.basename( real_filename ), ":" try : a = apk.APK( real_filename ) if a.is_valid_APK() : a.show() display_dvm_info( a ) else : print "INVALID APK" raise("ooos") except Exception, e : print "ERROR", e raise("ooos")
def dealapk(options, kwargs): print 'waiting...' apk_sum = 0 if options.directory: for root, dirs, files in os.walk(options.directory, followlinks=True): if files: for f in files: real_filename = root if real_filename[-1] != "/": real_filename += "/" real_filename += f ret_type = androconf.is_android(real_filename) if ret_type == "APK": # print os.path.basename(real_filename), ":" try: a = apk.APK(real_filename) if a.is_valid_APK(): apk_sum += 1 else: print "INVALID" os.remove(real_filename) except Exception, e: print "ERROR", e os.remove(real_filename) else: print "directory not exists!!!"
def predict_ad_classifier(self, classifier_name, apk_path): """ :param classifier_name: the classifier name :param apk_path: a apk path that you want to detector :return: 1->content ad 0->not contentad """ # 加载训练好的分类器 clf = joblib.load(CLASSIFIER_PATH + classifier_name + ".m") # clf, train_id = self.train_classifier(clf, classifier_name) stand_permissions = self.get_standard_permission_from_mongodb() ret_type = androconf.is_android(apk_path) if ret_type == "APK": try: a = apk.APK(apk_path) if a.is_valid_APK(): predict_permission = self.create_permission_vector( stand_permissions, self.get_permission_from_apk(a)) logger.info(os.path.basename(apk_path) + ' classified as: ') logger.info(clf.predict(predict_permission)) return clf.predict(predict_permission)[0] else: logger.info("INVALID") except Exception, e: logger.info(e)
def get_apk_info(apk_path): """ get the apk base information then save to log :param apk_path: :return: """ ret_type = androconf.is_android(apk_path) if ret_type == "APK": logger.info(os.path.basename(apk_path) + ":") try: a = apk.APK(apk_path) if a.is_valid_APK(): activities = a.get_activities() for i in activities: logger.info(i) services = a.get_services() for i in services: logger.info(i) receivers = a.get_receivers() for i in receivers: logger.info(i) permissions = a.get_requested_permissions() for i in permissions: logger.info(i) except Exception, e: logger.info(e)
def main(): parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(help='Plugins') # Init plugins plugins = init_plugins() for p in sorted(plugins.keys()): sp = subparsers.add_parser(plugins[p].name, help=plugins[p].description) plugins[p].add_arguments(sp) sp.add_argument('APK', help='an APK file') sp.set_defaults(plugin=p) args = parser.parse_args() if hasattr(args, 'plugin'): if not os.path.isfile(args.APK): print("File not found") sys.exit(1) ret_type = androconf.is_android(args.APK) if ret_type != "APK": print("Not an APK file") sys.exit(1) a, d, dx = AnalyzeAPK(args.APK) plugins[args.plugin].run(args, a, d, dx) else: parser.print_help()
def getapkinfo(apkfile): goodapk = False if apkfile is not None: ret_type = androconf.is_android(apkfile) apkinfo['filename'] = apkfile if ret_type == "APK": jsonfile = re.sub('\.apk$', '.apkinfo.json', apkfile) if not os.path.exists(jsonfile): # print('Analyzing APK: %s ...' % apkfile) from androguard.core.bytecodes import apk try: a = apk.APK(apkfile) if a.is_valid_APK(): extract_dvm_info(a, apkfile) goodapk = True else: print("%s - INVALID" % apkfile) return False except Exception as e: print("%s ERROR" % apkfile, e) import traceback traceback.print_exc() else: goodapk = True else: pass return goodapk
def create_graph(input, output): if input != None and output != None: ret_type = androconf.is_android(input) vm = None a = None if ret_type == "APK": a = apk.APK(input) if a.is_valid_APK(): vm = dvm.DalvikVMFormat(a.get_dex()) else: print "INVALID APK" elif ret_type == "DEX": try: vm = dvm.DalvikVMFormat(open(input, "rb").read()) except Exception, e: print "INVALID DEX", e vmx = analysis.VMAnalysis(vm) gvmx = ganalysis.GVMAnalysis(vmx, a) create_directories(vm, output) dd = data.Data(vm, vmx, gvmx, a) buff = dd.export_methodcalls_to_gml() androconf.save_to_disk(buff, output + "/" + "methodcalls.graphml")
def predict_ad_classifier(self, classifier_name, apk_path): """ :param classifier_name: the classifier name :param apk_path: a apk path that you want to detector :return: 1->content ad 0->not contentad """ # 加载训练好的分类器 clf = joblib.load(CLASSIFIER_PATH + classifier_name + ".m") # clf, train_id = self.train_classifier(clf, classifier_name) stand_permissions = self.get_standard_permission_from_mongodb() ret_type = androconf.is_android(apk_path) if ret_type == "APK": try: a = apk.APK(apk_path) if a.is_valid_APK(): predict_permission = self.create_permission_vector( stand_permissions, self.get_permission_from_apk(a)) logger.info( os.path.basename(apk_path) + ' classified as: ') logger.info(clf.predict(predict_permission)) return clf.predict(predict_permission)[0] else: logger.info("INVALID") except Exception, e: logger.info(e)
def get_train_permission(self): """ get train permission and classvec then write to mongo :return: """ classvec = [] permission_list = [] train_permission = [] for root, dirs, files in os.walk(TRAIN_APK_PATH, followlinks=True): if files: for f in files: real_filename = root if real_filename[-1] != "/": real_filename += "/" real_filename += f ret_type = androconf.is_android(real_filename) if ret_type == "APK": try: a = apk.APK(real_filename) if a.is_valid_APK(): logger.info(os.path.basename(real_filename)) if "notContentAds" in root: classvec.append(0) else: classvec.append(1) permission_list.append(self.get_permission_from_apk(a)) else: logger.info("it not a real apk") except Exception, e: logger.info(e) else: logger.info("directory not exists!!!")
def _analyze(self): for i in self.__files: ret_type = androconf.is_android( i ) if ret_type == "APK": x = apk.APK( i ) bc = dvm.DalvikVMFormat( x.get_dex() ) n = 1 if x.get_dex2() != '': # bc2 = dvm.DalvikOdexVMFormat( x.get_dex2() ) bc2 = dvm.DalvikVMFormat( x.get_dex2() ) n = 2 elif ret_type == "DEX": bc = dvm.DalvikVMFormat( read(i) ) elif ret_type == "DEY": bc = dvm.DalvikOdexVMFormat( read(i) ) elif ret_type == "ELF": from androguard.core.binaries import elf bc = elf.ELF( read(i) ) else: raise( "Unknown format" ) self.__bc.append( (i, BC( bc )) ) if n == 2: self.__bc.append( (i, BC( bc2 )) ) self.__bc.append( n )
def main(options, filename) : if filename != None : buff = "" ret_type = androconf.is_android(filename) if ret_type == "APK": a = apk.APK(filename) dom = a.get_android_manifest_xml() #buff = a.get_android_manifest_xml().toprettyxml(encoding="utf-8") #a.get_activities() xml2parse(dom) elif ".xml" in filename: ap = apk.AXMLPrinter(open(filename, "rb").read()) buff = minidom.parseString(ap.get_buff()).toprettyxml(encoding="utf-8") else: print "Unknown file type" return #if options.output != None : # fd = codecs.open(options.output, "w", "utf-8") # fd.write( buff ) # fd.close() #else : # print buff elif options.version != None : print "Androaxml version %s" % androconf.ANDROGUARD_VERSION
def main(options, arguments) : if options.input != None : buff = "" ret_type = androconf.is_android(options.input) if ret_type == "APK": a = apk.APK(options.input) buff = a.xml["AndroidManifest.xml"].toprettyxml(encoding="utf-8") a.get_activities() elif ".xml" in options.input: ap = apk.AXMLPrinter(open(options.input, "rb").read()) buff = minidom.parseString(ap.get_buff()).toprettyxml(encoding="utf-8") else: print "Unknown file type" return if options.output != None : fd = codecs.open(options.output, "w", "utf-8") fd.write( buff ) fd.close() else : print buff elif options.version != None : print "Androaxml version %s" % androconf.ANDROGUARD_VERSION
def select_not_found(apk_file): """ select the not found apk_path which used ad feature :param apk_file: :return: """ logger = DetectorLogger(path="not_checked_ad_logger.log") apklist = os.listdir(apk_file) not_check_sum = 0 for apk_path in apklist: apk_path = os.path.join(apk_file, apk_path) if not check_adware_from_config(apk_path): ret_type = androconf.is_android(apk_path) if ret_type == "APK": try: a = apk.APK(apk_path) if a.is_valid_APK(): logger.info('//') logger.info(os.path.basename(apk_path)) not_check_sum += 1 activities = a.get_activities() services = a.get_services() receivers = a.get_receivers() for i in activities: logger.info(i) for i in services: logger.info(i) for i in receivers: logger.info(i) else: logger.info("INVALID") except Exception, e: logger.info(e)
def get_info(self, srules) : rules = json.loads( srules ) ret_type = androconf.is_android( rules[0]["SAMPLE"] ) if ret_type == "APK" : a = apk.APK( rules[0]["SAMPLE"] ) classes_dex = a.get_dex() elif ret_type == "DEX" : classes_dex = read( rules[0]["SAMPLE"]) #elif ret_type == "ELF" : #elf_file = read( rules[0]["SAMPLE"]) else : return None if ret_type == "APK" or ret_type == "DEX" : vm = dvm.DalvikVMFormat( classes_dex ) vmx = analysis.VMAnalysis( vm ) res = [] for i in rules[1:] : for j in i["SIGNATURE"] : if j["TYPE"] == "METHSIM" : m = vm.get_method_descriptor( j["CN"], j["MN"], j["D"] ) if m == None : print "impossible to find", j["CN"], j["MN"], j["D"] else : res.append( m ) elif j["TYPE"] == "CLASSSIM" : for c in vm.get_classes() : if j["CN"] == c.get_name() : res.append( c ) return vm, vmx, res
def parseApk(filename, permissions): if filename is not None: ret_type = androconf.is_android(filename) vm = None a = None md5 = None if ret_type == 'APK': a = apk.APK(filename) md5 = a.md5 outs = {} for and_permission in a.get_permissions(): and_permission = and_permission.rsplit('.', 1)[-1] if and_permission in permissions: if isinstance(permissions[and_permission], basestring): outs.setdefault(permissions[and_permission]) elif isinstance(permissions[and_permission], list): for and_perm in permissions[and_permission]: outs.setdefault(and_perm) if a.is_valid_APK(): vm = dvm.DalvikVMFormat(a.get_dex()) vmx = analysis.VMAnalysis(vm) for str in vm.get_strings(): if "IMAGE_CAPTURE" in str: outs.setdefault("PERM_ID_RECORDER") for and_permission in vmx.get_permissions([]): if and_permission in permissions: if isinstance(permissions[and_permission], basestring): outs.setdefault(permissions[and_permission]) elif isinstance(permissions[and_permission], list): for and_perm in permissions[and_permission]: outs.setdefault(and_perm) return outs.keys()
def main(options, arguments): if options.database == None or options.config == None: return s = dalvik_elsign.MSignature(options.database, options.config, options.verbose != None, ps=dalvik_elsign.PublicSignature) if options.input != None: ret_type = androconf.is_android(options.input) print os.path.basename(options.input), ":", sys.stdout.flush() if ret_type == "APK": try: a = apk.APK(options.input) if a.is_valid_APK(): display(s.check_apk(a), options.verbose) else: print "INVALID" except Exception, e: print "ERROR", e elif ret_type == "DEX": display(s.check_dex(read(options.input)), options.verbose)
def _analyze(self): for i in self.__files: #print "processing ", i if ".class" in i: bc = jvm.JVMFormat(self.__orig_raw[i]) elif ".jar" in i: x = jvm.JAR(i) bc = x.get_classes() elif ".dex" in i: bc = dvm.DalvikVMFormat(self.__orig_raw[i]) elif ".apk" in i: x = apk.APK(i) bc = dvm.DalvikVMFormat(x.get_dex()) else: ret_type = androconf.is_android(i) if ret_type == "APK": x = apk.APK(i) bc = dvm.DalvikVMFormat(x.get_dex()) elif ret_type == "DEX": bc = dvm.DalvikVMFormat(open(i, "rb").read()) elif ret_type == "ELF": from androguard.core.binaries import elf bc = elf.ELF(open(i, "rb").read()) else: raise ("Unknown bytecode") if isinstance(bc, list): for j in bc: self.__bc.append((j[0], BC(jvm.JVMFormat(j[1])))) else: self.__bc.append((i, BC(bc)))
def _analyze(self) : for i in self.__files : #print "processing ", i if ".class" in i : bc = jvm.JVMFormat( self.__orig_raw[ i ] ) elif ".jar" in i : x = jvm.JAR( i ) bc = x.get_classes() elif ".dex" in i : bc = dvm.DalvikVMFormat( self.__orig_raw[ i ] ) elif ".apk" in i : x = apk.APK( i ) bc = dvm.DalvikVMFormat( x.get_dex() ) else : ret_type = androconf.is_android( i ) if ret_type == "APK" : x = apk.APK( i ) bc = dvm.DalvikVMFormat( x.get_dex() ) elif ret_type == "DEX" : bc = dvm.DalvikVMFormat( open(i, "rb").read() ) elif ret_type == "ELF" : from androguard.core.binaries import elf bc = elf.ELF( open(i, "rb").read() ) else : raise( "Unknown bytecode" ) if isinstance(bc, list) : for j in bc : self.__bc.append( (j[0], BC( jvm.JVMFormat(j[1]) ) ) ) else : self.__bc.append( (i, BC( bc )) )
def handle_android(self, url, content): ret = False m = hashlib.md5() m.update(content) md5sum = m.hexdigest() rfile = os.path.join(log.ThugLogging.baseDir, md5sum) with open(rfile, 'wb') as fd: fd.write(content) ret_type = androconf.is_android(rfile) if ret_type not in ("APK", ): os.remove(rfile) return ret try: a = apk.APK(rfile, zipmodule=2) if a.is_valid_APK(): self.build_apk_report(url, a, md5sum) ret = True except: pass os.remove(rfile) return ret
def main(): malware_path = '/home/kevin/Temps/android-security/samples' permission_dict = {} app_count = 0 for root, dirs, files in os.walk(malware_path, followlinks=True): if files: for f in files: real_filename = root if real_filename[-1] != "/": real_filename += "/" real_filename += f ret_type = androconf.is_android(real_filename) if ret_type == "APK": # print os.path.basename(real_filename), ":" app_count += 1 try: a = apk.APK(real_filename) if a.is_valid_APK(): permissions = a.get_requested_permissions() temp_permissions = [] for per in permissions: if per not in temp_permissions: if per in permission_dict: permission_dict[per] += 1 else: permission_dict[per] = 1 temp_permissions.append(per) else: print "INVALID" except Exception, e: print "ERROR", e else: print "directory not exists!!!"
def main(options, arguments): if options.input is not None: buff = "" ret_type = androconf.is_android(options.input) if ret_type == "APK": a = apk.APK(options.input) buff = a.get_android_manifest_xml().toprettyxml(encoding="utf-8") elif ".xml" in options.input: ap = apk.AXMLPrinter(read(options.input)) buff = minidom.parseString(ap.get_buff()).toprettyxml( encoding="utf-8") else: print("Unknown file type") return if options.output is not None: fd = codecs.open(options.output, "w", "utf-8") fd.write(buff) fd.close() else: print(buff) elif options.version is not None: print("Androaxml version %s" % androconf.ANDROGUARD_VERSION)
def androaxml_main(inp, outp=None, resource=None): ret_type = androconf.is_android(inp) if ret_type == "APK": a = apk.APK(inp) if resource: if resource not in a.files: print("The APK does not contain a file called '{}'".format( resource), file=sys.stderr) sys.exit(1) axml = AXMLPrinter(a.get_file(resource)).get_xml_obj() else: axml = a.get_android_manifest_xml() elif ".xml" in inp: axml = AXMLPrinter(read(inp)).get_xml_obj() else: print("Unknown file type") sys.exit(1) buff = etree.tostring(axml, pretty_print=True, encoding="utf-8") if outp: with open(outp, "wb") as fd: fd.write(buff) else: sys.stdout.write( highlight(buff.decode("UTF-8"), get_lexer_by_name("xml"), TerminalFormatter()))
def basic_upload_view(request): if request.method == 'POST': form = BasicUploadForm(request.POST, request.FILES) if form.is_valid(): apk = request.FILES['apk'] if apk.size > settings.MAX_APK_UPLOAD_SIZE: messages.warning(request, 'Submitted file is too large.') return redirect(reverse_lazy('front:home')) with NamedTemporaryFile() as tmp: for chunk in apk.chunks(): tmp.write(chunk) tmp.seek(0) if is_android(tmp.name) != 'APK': messages.warning(request, 'Submitted file is not a valid APK.') return redirect(reverse_lazy('front:home')) sha256 = get_sha256_of_file(tmp) if default_storage.exists(sha256): # analyze(sha256, force=True) return redirect(reverse_lazy('front:report', [sha256])) else: default_storage.save(sha256, tmp) analyze(sha256) return redirect(reverse_lazy('front:report', [sha256])) return redirect(reverse_lazy('front:home'))
def main(filename): logging.debug('intput: %s' % filename) logging.debug('output: %s' % filename.replace('.apk', '.csv')) print 'intput: %s' % filename print 'output: %s' % filename.replace('.apk', '.csv') if filename != None: ret_type = androconf.is_android(filename) vm = None a = None if ret_type == 'APK': a = apk.APK(filename) package = a.package versionCode = a.androidversion['Code'] versionName = a.androidversion['Name'] md5 = a.md5 if a.is_valid_APK(): vm = dvm.DalvikVMFormat(a.get_dex()) else: print 'INVALID APK' else: print 'INPUT ERROR' vmx = analysis.VMAnalysis(vm) gvmx = ganalysis.GVMAnalysis(vmx, a) permissionfile = os.path.join(os.getcwd(), 'permission.cfg') permissions = {} with open(permissionfile) as files: for line in files: line_info = line.strip().split(',') lbe_permission = line_info[0] permissions.setdefault(lbe_permission) lines = '' with open(filename.replace('.apk', '.csv'), 'w') as files: files.write('%s,%s\n' % ('package', package)) files.write('%s,%s\n' % ('versionCode', versionCode)) files.write('%s,%s\n' % ('md5', md5)) last_lbe_permission = '' last_permission = '' for lbe_permission in gvmx.get_result(): permission_dict = gvmx.get_result()[lbe_permission] for permission in permission_dict: for method in permission_dict[permission]: result = [lbe_permission, permission, method] files.write('%s\n' % ','.join(result)) lbe_permission = ' ' permission = '' for lbe_permission in gvmx.get_otherresult(): permission_dict = gvmx.get_otherresult()[lbe_permission] for permission in permission_dict: for method in permission_dict[permission]: result = [lbe_permission, permission, method] files.write('%s\n' % ','.join(result)) lbe_permission = ' ' permission = ''
def main(options, arguments): if options.input != None: buff = "" ret_type = androconf.is_android(options.input) if ret_type == "APK": a = apk.APK(options.input) buff = a.get_android_manifest_xml().toprettyxml(encoding="utf-8") elif ".xml" in options.input: ap = apk.AXMLPrinter(read(options.input)) buff = minidom.parseString( ap.get_buff()).toprettyxml(encoding="utf-8") else: print "Unknown file type" return if options.output != None: fd = codecs.open(options.output, "w", "utf-8") fd.write(buff) fd.close() else: print buff elif options.version != None: print "Androaxml version %s" % androconf.ANDROGUARD_VERSION
def get_info(self, srules): rules = json.loads(srules) ret_type = androconf.is_android(rules[0]["SAMPLE"]) if ret_type == "APK": a = apk.APK(rules[0]["SAMPLE"]) classes_dex = a.get_dex() elif ret_type == "DEX": classes_dex = open(rules[0]["SAMPLE"], "rb").read() #elif ret_type == "ELF" : #elf_file = open( rules[0]["SAMPLE"], "rb" ).read() else: return None if ret_type == "APK" or ret_type == "DEX": vm = dvm.DalvikVMFormat(classes_dex) vmx = analysis.VMAnalysis(vm) res = [] for i in rules[1:]: for j in i["SIGNATURE"]: if j["TYPE"] == "METHSIM": m = vm.get_method_descriptor(j["CN"], j["MN"], j["D"]) if m == None: print "impossible to find", j["CN"], j["MN"], j["D"] else: res.append(m) elif j["TYPE"] == "CLASSSIM": for c in vm.get_classes(): if j["CN"] == c.get_name(): res.append(c) return vm, vmx, res
def main(options, filename): if filename != None: buff = "" ret_type = androconf.is_android(filename) if ret_type == "APK": a = apk.APK(filename) dom = a.get_android_manifest_xml() #buff = a.get_android_manifest_xml().toprettyxml(encoding="utf-8") #a.get_activities() xml2parse(dom) elif ".xml" in filename: ap = apk.AXMLPrinter(open(filename, "rb").read()) buff = minidom.parseString( ap.get_buff()).toprettyxml(encoding="utf-8") else: print "Unknown file type" return #if options.output != None : # fd = codecs.open(options.output, "w", "utf-8") # fd.write( buff ) # fd.close() #else : # print buff elif options.version != None: print "Androaxml version %s" % androconf.ANDROGUARD_VERSION
def handle_android(self, url, content): ret = False m = hashlib.md5() m.update(content) md5sum = m.hexdigest() rfile = os.path.join(log.ThugLogging.baseDir, md5sum) with open(rfile, 'wb') as fd: fd.write(content) ret_type = androconf.is_android(rfile) if ret_type not in ("APK", ): os.remove(rfile) return ret try : a = apk.APK(rfile, zipmodule = 2) if a.is_valid_APK(): self.build_apk_report(url, a, md5sum) ret = True except: pass os.remove(rfile) return ret
def parseApk(filename, permissions): if filename is not None: ret_type = androconf.is_android(filename) vm = None a = None if ret_type == 'APK': a = apk.APK(filename) md5 = a.md5 if a.is_valid_APK(): vm = dvm.DalvikVMFormat(a.get_dex()) else: print 'INVALID APK' return "Error" else: print 'INPUT ERROR' return "Error" vmx = analysis.VMAnalysis(vm) gvmx = ganalysis.GVMAnalysis(vmx, a) outs = {} for and_permission in gvmx.get_and_permissions(): if and_permission in permissions: outs.setdefault(permissions[and_permission]) result = [md5] for lbe_permission in outs: result.append(lbe_permission) strings = '%s' % ','.join(result) return strings
def load(self, file_path): self.file_path = file_path if file_path.endswith(".ag"): self.incoming_file = (file_path, 'SESSION') else: file_type = androconf.is_android(file_path) self.incoming_file = (file_path, file_type) self.start(QtCore.QThread.LowestPriority)
def main(options, arguments): if options.input != None: ret_type = androconf.is_android(options.input) if ret_type == "APK" or ret_type == "DEX": autograph(options.input) else: print "input file should be apk/dex..." return 0
def main(options, arguments) : if options.input != None : ret_type = androconf.is_android( options.input ) if ret_type == "APK" or ret_type == "DEX" : autograph( options.input ) else: print "input file should be apk/dex..." return 0
def auto_vm(filename): ret = androconf.is_android(filename) if ret == 'APK': return dvm.DalvikVMFormat(apk.APK(filename).get_dex()) elif ret == 'DEX': return dvm.DalvikVMFormat(read(filename)) elif ret == 'DEY': return dvm.DalvikOdexVMFormat(read(filename)) return None
def auto_vm(filename): ret = androconf.is_android(filename) if ret == 'APK': return dvm.DalvikVMFormat(apk.APK(filename).get_dex()) elif ret == 'DEX': return dvm.DalvikVMFormat(read(filename)) elif ret == 'DEY': return dvm.DalvikOdexVMFormat(read(filename)) raise Exception("unsupported file %s" % filename)
def get_apk_base_info(self, apk_path, json_store_path): """ get the apk base information then save to log :param apk_path: :return: """ time_start = time.time() base_info_dict = {} permission_info = {} for temp in os.listdir(apk_path): path = os.path.join(apk_path, temp) temp = temp.split(".")[0] base_info_dict[temp] = {} base_info_dict[temp]["activity"] = [] base_info_dict[temp]["service"] = [] base_info_dict[temp]["receiver"] = [] base_info_dict[temp]["permission"] = [] permission_info[temp] = [] ret_type = androconf.is_android(path) if ret_type == "APK": logger.info(os.path.basename(path) + ":") try: a = apk.APK(path) p = a.get_package() base_info_dict[temp]["package_name"] = p if a.is_valid_APK(): activities = a.get_activities() for i in activities: logger.info(i) base_info_dict[temp]["activity"].append(i) services = a.get_services() for i in services: logger.info(i) base_info_dict[temp]["service"].append(i) receivers = a.get_receivers() for i in receivers: logger.info(i) base_info_dict[temp]["receiver"].append(i) permissions = a.get_requested_permissions() for i in permissions: logger.info(i) base_info_dict[temp]["permission"].append(i) permission_info[temp].append(i) except Exception, e: logger.info(e) time_end = time.time()
def load_analysis(filename): """Return an AnalysisObject depding on the filetype""" ret_type = androconf.is_android(filename) if ret_type == "APK": _, _, dx = AnalyzeAPK(filename) return dx if ret_type == "DEX": _, _, dx = AnalyzeDex(filename) return dx return None
def makeFileAnalysis(self, file_path): logger.debug("Performing analysis of file [%s]..." % file_path) a = None d = None dx = None ret_type = androconf.is_android(file_path) if ret_type == "APK": a = apk.APK(file_path) d = dvm.DalvikVMFormat(a.get_dex()) elif ret_type == "DEX": try: d = dvm.DalvikVMFormat(open(file_path, "rb").read()) except Exception as e: logger.error("[%s] is not valid dex file!" % file_path, e) return dx = analysis.VMAnalysis(d) invokeMethodPaths = analysis.seccon_get_invoke_method_paths(dx) newInstanceMethodPaths = analysis.seccon_get_newInstance_method_paths( dx) dynamicMethodPaths = analysis.seccon_get_dyncode_loading_paths(dx) if invokeMethodPaths: t = None for path in invokeMethodPaths: src = path.get_src(d.get_class_manager()) dst = path.get_dst(d.get_class_manager()) t = (src, dst) self._sources_invoke.append(t) self._uncovered_invoke.append(t) if newInstanceMethodPaths: t = None for path in newInstanceMethodPaths: src = path.get_src(d.get_class_manager()) dst = path.get_dst(d.get_class_manager()) t = (src, dst) self._sources_newInstance.append(t) self._uncovered_newInstance.append(t) if dynamicMethodPaths: t = None for path in dynamicMethodPaths: src = path.get_src(d.get_class_manager()) dst = path.get_dst(d.get_class_manager()) t = (src, dst) self._sources_dexload.append(t) self._uncovered_dexload.append(t) #building MFG for the file self._stadynaMcg.analyseFile(dx, a)
def makeFileAnalysis(self, file_path): logger.debug("Performing analysis of file [%s]..." % file_path) a = None d = None dx = None ret_type = androconf.is_android(file_path) if ret_type == "APK": a = apk.APK(file_path) d = dvm.DalvikVMFormat(a.get_dex()) elif ret_type == "DEX" : try : d = dvm.DalvikVMFormat(open(file_path, "rb").read()) except Exception as e : logger.error("[%s] is not valid dex file!" % file_path, e) return dx = analysis.VMAnalysis(d) invokeMethodPaths = analysis.seccon_get_invoke_method_paths(dx) newInstanceMethodPaths = analysis.seccon_get_newInstance_method_paths(dx) dynamicMethodPaths = analysis.seccon_get_dyncode_loading_paths(dx) if invokeMethodPaths: t = None for path in invokeMethodPaths: src = path.get_src(d.get_class_manager()) dst = path.get_dst(d.get_class_manager()) t = (src, dst) self._sources_invoke.append(t) self._uncovered_invoke.append(t) if newInstanceMethodPaths: t = None for path in newInstanceMethodPaths: src = path.get_src(d.get_class_manager()) dst = path.get_dst(d.get_class_manager()) t = (src, dst) self._sources_newInstance.append(t) self._uncovered_newInstance.append(t) if dynamicMethodPaths: t = None for path in dynamicMethodPaths: src = path.get_src(d.get_class_manager()) dst = path.get_dst(d.get_class_manager()) t = (src, dst) self._sources_dexload.append(t) self._uncovered_dexload.append(t) #building MFG for the file self._stadynaMcg.analyseFile(dx, a)
def run(name, dir=""): ri = risk.RiskIndicator() ri.add_risk_analysis(risk.RedFlags()) ri.add_risk_analysis(risk.FuzzyRisk()) ret_type = androconf.is_android(dir + name + ".apk") if ret_type == "APK": a = apk.APK(dir + name + ".apk") return analyze_app(name, ri, a) else: print "ret_type was not APK"
def getSelected(options): # -f / --file if options.file != None: if os.path.isfile(options.file): ret_type = androconf.is_android(options.file) if ret_type == "APK" or ret_type == "DEX": return ["file/report", options.file] else: print "input file should be apk/dex..." return None else: print "Could not find file..." return None # -x / --hash elif options.hash != None: return ["file/report", options.hash] # -s / --scan elif options.scan != None: if os.path.isfile(options.scan): ret_type = androconf.is_android(options.scan) if ret_type == "APK" or ret_type == "DEX": return ["file/scan", options.scan] else: print "input file should be apk/dex..." return None else: print "Could not find file..." return None # -c / --comment elif options.comment != None: return ["comments/put", options.comment] # -r / --rescan elif options.rescan != None: return ["file/rescan", options.rescan] else: return None
def getSelected( options ): # -f / --file if options.file != None: if os.path.isfile(options.file): ret_type = androconf.is_android( options.file ) if ret_type == "APK" or ret_type == "DEX" : return ["file/report", options.file] else: print "input file should be apk/dex..." return None else: print "Could not find file..." return None # -x / --hash elif options.hash != None: return ["file/report", options.hash] # -s / --scan elif options.scan != None: if os.path.isfile(options.scan): ret_type = androconf.is_android( options.scan ) if ret_type == "APK" or ret_type == "DEX" : return ["file/scan", options.scan] else: print "input file should be apk/dex..." return None else: print "Could not find file..." return None # -c / --comment elif options.comment != None: return ["comments/put", options.comment] # -r / --rescan elif options.rescan != None: return ["file/rescan", options.rescan] else: return None
def recognize(self, dataModel): self.dataModel = dataModel try: ret_type = androconf.is_android(self.dataModel.source) self.apk = apk.APK(self.dataModel.source) if ret_type == "APK": return True except: return False return False
def main(apkfile) : if (androconf.is_android(apkfile) == "APK") : try : a = apk.APK(apkfile, zipmodule=2) if a.is_valid_APK(): apis=extract_method_calls( a ) ks=apis.keys() print "Number of API calls:", len(ks) else : print "INVALID" except Exception, e : print "ERROR", e
def _check_application_advertisement(self, application): ret_type = androconf.is_android(application) if ret_type == "APK": try: a = apk.APK(application) if a.is_valid_APK(): return check_adware_from_config(a) else: return False except Exception, e: print(e.message)
def main(options, args) : print options.input print options.output if options.input == None or options.output == None : print "static_analysis.py -i <inputfile> -o <outputfolder>" sys.exit(2) else : ret_type = androconf.is_android( options.input ) if ret_type == "APK" : try : a = apk.APK(options.input, zipmodule=2) if a.is_valid_APK() : vm = dvm.DalvikVMFormat(a.get_dex()) vmx = analysis.uVMAnalysis(vm) data = { 'mainActivity' : a.get_main_activity(), 'activities' : a.get_activities(), 'providers' : a.get_providers(), 'receivers' : a.get_receivers(), 'services' : a.get_services(), 'androidVersion' : a.get_androidversion_code(), 'maxSdkVersion' : a.get_max_sdk_version(), 'minSdkVersion' : a.get_min_sdk_version(), 'targetSdkVersion' : a.get_target_sdk_version(), 'package' : a.get_package(), 'libraries' : a.get_libraries(), 'isCryptoCode' : analysis.is_crypto_code(vmx), 'isDynamicCode' : analysis.is_dyn_code(vmx), 'isNativeCode' : analysis.is_native_code(vmx), 'nativeMethodCount' : native_method_count(vm), 'isReflectionCode' : analysis.is_reflection_code(vmx), 'reflectionCount' : len(vmx.get_tainted_packages().search_methods("Ljava/lang/reflect/Method;", ".", ".")), 'isAsciiObfuscation' : analysis.is_ascii_obfuscation(vm), 'permissions' : a.get_permissions(), 'actualPermissions' : actual_permissions(vm, vmx), #'internalMethodCalls' : get_methods(vm.get_class_manager(), vmx.get_tainted_packages().get_internal_packages(), {}), 'externalMethodCalls' : get_methods(vm.get_class_manager(), vmx.get_tainted_packages().get_external_packages(), {}) } with io.open(options.output + "/" + hashfile(options.input) + ".json", 'w', encoding='utf-8') as f: f.write(unicode(json.dumps(data, sort_keys=False, indent=2, separators=(',', ': '), ensure_ascii=False))) else : print "INVALID APK" except Exception, e : print "ERROR", e import traceback traceback.print_exc()
def __init__(self, fname, dbg=False): self.fname = fname self.debug = dbg if androconf.is_android(self.fname) == 'APK': # Try to cast the application as an Android APK try: self.app = apk.APK(fname) # If the file isn't an Android application, set a variable so we know except Exception, e: if self.debug: print "[-] File was not a valid Android Application!" self.isvalid = False if not self.app.is_valid_APK(): self.isvalid = False
def checkInputFile(inputPath): logger.debug("Checking input path [%s]..." % inputPath) if not os.path.isfile(inputPath): logger.error("Input path [%s] does not point to a file!" % inputPath) return False logger.debug("The path [%s] point to the file!" % inputPath) ret_type = androconf.is_android(inputPath) if ret_type != "APK": logger.error("Input file [%s] is not APK file!" % inputPath) return False logger.debug("File [%s] is an APK file!" % inputPath) return True
def main(options, arguments) : if options.input != None : ret_type = androconf.is_android( options.input ) print os.path.basename(options.input), ":" if ret_type == "APK" : try : a = apk.APK( options.input ) if a.is_valid_APK() : a.show() display_dvm_info( a ) else : print "INVALID" except Exception, e : print "ERROR", e