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")
示例#2
0
def extract_static_features(filename, raw=False):

    app = apk.APK(filename, raw)
    d = dvm.DalvikVMFormat(app.get_dex())
    dvmx = analysis.VMAnalysis(d)
    d.set_vmanalysis(dvmx)
    return parse_static_features(app, d, dvmx)
示例#3
0
    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
示例#4
0
    def analyze(self, d):

        ret = False
        dvmx = analysis.VMAnalysis(d)

        if analysis.is_native_code(dvmx):
            ret = True
            self.extra += "NativeCodeFound; "

        if analysis.is_dyn_code(dvmx):
            ret = True
            self.extra += "DynCodeFound; "

        if analysis.is_reflection_code(dvmx):
            ret = True
            self.extra += "ReflexionCodeFound; "

        #if analysis.is_ascii_obfuscation(d):
        #ret = True
        #self.extra + "AsciiObfuscationCodeFound; "

        #if analysis.is_crypto_code(d):
        #ret = True
        #self.extra + "AsciiObfuscationCodeFound; "

        return ret
示例#5
0
def export_apps_to_format(a, output, dot=None, _format=None):
    output_name = output
    if output_name[-1] != "/":
        output_name = output_name + "/"

    for vm in a.get_vms():
        x = analysis.VMAnalysis(vm)
        for method in vm.get_methods():
            filename = output_name + valid_class_name(method.get_class_name())
            if filename[-1] != "/":
                filename = filename + "/"

            descriptor = method.get_descriptor()
            descriptor = descriptor.replace(";", "")
            descriptor = descriptor.replace(" ", "")
            descriptor = descriptor.replace("(", "-")
            descriptor = descriptor.replace(")", "-")
            descriptor = descriptor.replace("/", "_")

            filename = filename + method.get_name() + descriptor

            buff = method2dot(x.get_method(method))

            if dot:
                fd = open(filename + ".dot", "w")
                fd.write(buff)
                fd.close()

            if _format:
                method2format(filename + "." + _format, _format, raw=buff)
示例#6
0
def parse_APK(APKFile):
    '''
	parse apk to a data-structure
	'''
    a = apk.APK(APKFile)
    d = dvm.DalvikVMFormat(a.get_dex())
    dx = analysis.VMAnalysis(d)
    return (a, d, dx)
示例#7
0
def get_plugin_prevalues(args, filename):
    result = {}
    a = apk.APK(filename)
    result['apk'] = a
    result['dvm'] = dvm.DalvikVMFormat(a.get_dex())
    result['dx'] = analysis.VMAnalysis(result['dvm'])
    result['zipfile'] = ZipFile(filename)
    return result
示例#8
0
 def get_androguard_obj(self):
     """获取androguard对象"""
     try:
         a = apk.APK(self.apkfile, False, "r", None, 2)  # 获取APK文件对象
         d = dvm.DalvikVMFormat(a.get_dex())  # 获取DEX文件对象
         x = analysis.VMAnalysis(d)  # 获取分析结果对象
         return a, d, x
     except BadZipfile:
         return None
示例#9
0
    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 AnalyzeDex(f):

    d = dvm.DalvikVMFormat(f.get_dex())

    # VMAnalysis
    dx = analysis.VMAnalysis(d)
    #dx = uVMAnalysis( d )

    d.set_vmanalysis(dx)

    return d, dx
示例#11
0
def diffMethod(dexO, dexR, classNameO, methodNameO, classNameR, methodNameR):
    vm = dvm.DalvikVMFormat(open(dexO, "r").read())
    vmx = analysis.VMAnalysis(vm)

    vmR = dvm.DalvikVMFormat(open(dexR, "r").read())
    vmxR = analysis.VMAnalysis(vmR)

    for method in vm.get_methods():
        for methodR in vmR.get_methods():
            if (method.get_class_name() == classNameO and method.get_name() == methodNameO) and (methodR.get_class_name() == classNameR and methodR.get_name() == methodNameR):
                mx = vmx.get_method(method)            
                ms = decompile.DvMethod(mx)
                ms.process()

                mxR = vmxR.get_method(methodR)
                msR = decompile.DvMethod(mxR)
                msR.process()

                text = (_unidiff_output(ms.get_source(), msR.get_source()))
                print("getOneMethod")
                return text
示例#12
0
def get_apis(path):
    """
  Get the APIs from an app.

  Parameters:
    path - The path of the app to be decompiled

  Returns:
    A sorted list of APIs with parameters

  """

    # You can see the documents of androguard to get the further details
    # of the decompilation procedures.
    app = apk.APK(path)
    app_dex = dvm.DalvikVMFormat(app.get_dex())
    app_x = analysis.VMAnalysis(app_dex)

    methods = set()
    cs = [cc.get_name() for cc in app_dex.get_classes()]

    for method in app_dex.get_methods():
        g = app_x.get_method(method)

        if method.get_code() == None:
            continue

        for i in g.get_basic_blocks().get():
            for ins in i.get_instructions():
                # This is a string that contains methods, variables, or
                # anything else.
                output = ins.get_output()

                # Here we use regular expression to check if it is a function
                # call. A function call comprises four parts: a class name, a
                # function name, zero or more parameters, and a return type.
                # The pattern is actually simple:
                #
                #      CLASS NAME: starts with a character L and ends in a right
                #                  arrow.
                #   FUNCTION NAME: starts with the right arrow and ends in a
                #                  left parenthesis.
                #      PARAMETERS: are between the parentheses.
                #     RETURN TYPE: is the rest of the string.
                #
                match = re.search(r'(L[^;]*;)->[^\(]*\([^\)]*\).*', output)
                if match and match.group(1) not in cs:
                    methods.add(match.group())

    methods = list(methods)
    methods.sort()

    return methods
示例#13
0
    def _check_dalvik(self, buff):
        if self.debug:
            print "loading dex..",
            sys.stdout.flush()

        vm = dvm.DalvikVMFormat(buff)

        if self.debug:
            print "analysis..",
            sys.stdout.flush()

        vmx = analysis.VMAnalysis(vm)
        return self._check_dalvik_direct(vm, vmx)
示例#14
0
def getNewMethods(dexR, classNameR, methodNameR):
    vmR = dvm.DalvikVMFormat(open(dexR, "r").read())
    vmxR = analysis.VMAnalysis(vmR)

    for methodR in vmR.get_methods():
        if (methodR.get_class_name() == classNameR and methodR.get_name() == methodNameR):
            mxR = vmxR.get_method(methodR)
            msR = decompile.DvMethod(mxR)
            msR.process()

            text = msR.get_source()
            print("getNewMethod")
            return text
示例#15
0
文件: vulfinder.py 项目: plowsec/REAL
    def parse_input_file(self):
        """This function will analyze the file given as input"""

        extension = self.get_type(self.filename)

        if extension == ".apk":
            if not self.quiet:
                print "[*] Opening APK..."

            try:
                self.application = apk.APK(self.filename)
                self.dalvik_executable = dvm.DalvikVMFormat(self.application.get_dex())
            except:
                return None
        
        elif extension == ".odex":
            if not self.quiet:
                print "[*] Opening .odex file..."
                
            self.dalvik_executable = dvm.DalvikOdexVMFormat(open(self.filename, "r").read())
        
        elif extension == ".dex":
            if not self.quiet:
                print "[*] Opening .dex file"

            self.dalvik_executable = dvm.DalvikVMFormat(open(self.filename, "r").read())
        
        else:

            if not self.quiet:
                print "[!] Invalid type for %s...skipping" % (self.filename)

            return None
        
        if not self.quiet:
            #print "[*] This application uses the following permissions :"
            #print self.application.get_permissions()

            print "[*] Analyzing dex file..."

        self.analyzed_dex = analysis.VMAnalysis(self.dalvik_executable)
        self.gx = ganalysis.GVMAnalysis(self.analyzed_dex, None)

        self.dalvik_executable.set_vmanalysis(self.analyzed_dex)
        self.dalvik_executable.set_gvmanalysis(self.gx)

        if not self.quiet:
            print "[*] Creating xrefs..."

        self.dalvik_executable.create_xref()
        self.dalvik_executable.create_python_export()
    def getGexf(self, gexfOut):
        """
        Use Androgexf in androguard to generate graph
        """
        try:
            self.gexfOut = gexfOut
            vm = dvm.DalvikVMFormat(self.apkObj.get_dex())

            vmx = analysis.VMAnalysis(vm)
            gvmx = ganalysis.GVMAnalysis(vmx, self.apkObj)

            b = gvmx.export_to_gexf()
            androconf.save_to_disk(b, self.gexfOut)
        except Exception:
            ex = traceback.format_exc()
            self.log.exce(ex)
示例#17
0
def main(options, arguments):
    #--------
    file_d = open('../Analysis_androgd/API_sig.txt', 'w')
    file_d.close()
    #--------
    if options.input != None:
        a = None
        ret_type = androconf.is_android(options.input[0])
        if ret_type == "APK":
            a = apk.APK(options.input[0])
            d1 = dvm.DalvikVMFormat(a.get_dex())
        elif ret_type == "DEX":
            d1 = dvm.DalvikVMFormat(open(options.input[0], "rb").read())

        dx1 = analysis.VMAnalysis(d1)

        threshold = None
        if options.threshold != None:
            threshold = float(options.threshold)

#print "1111111"
        FS = FILTERS_DALVIK_SIM
        #print FS
        FS[elsim.FILTER_SKIPPED_METH].set_regexp(options.exclude)
        FS[elsim.FILTER_SKIPPED_METH].set_size(options.size)
        #print FS
        new = True
        if options.new != None:
            new = False

        library = True
        if options.library != None:
            library = options.library
            if options.library == "python":
                library = False

        if os.path.isdir(options.input[1]) == False:
            check_one_file(a, d1, dx1, FS, threshold, options.input[1],
                           options.input[0], options.xstrings, new,
                           library)  # The argument input[0] is added by me
        else:
            check_one_directory(a, d1, dx1, FS, threshold, options.input[1],
                                options.xstrings, new, library)

    elif options.version != None:
        print "Androsim version %s" % androconf.ANDROGUARD_VERSION
示例#18
0
def makefeeder(filein, fileout):
    root = etree.Element("root")

    app = apk.APK(filein)
    addElement(root, 'sdkmin', app.get_min_sdk_version())
    addElement(root, 'sdktarget', app.get_target_sdk_version())

    #print "****************the .apk contents are************"

    #for afile in app.get_files():
    #print afile

    #print "**************************************************"
    #print "the sdk version and permissions needed are"
    #print ""

    for areceiver in app.get_receivers():
        #print areceiver
        addElement(root, 'receiver', areceiver)

    for act in app.get_elements("activity", "android:name"):
        #print act
        addElement(root, 'activity', act)

    for action in app.get_elements("action", "android:name"):
        #print action
        addElement(root, 'action', action)

    dx = analysis.VMAnalysis(dvm.DalvikVMFormat(app.get_dex()))
    for perm in dx.get_permissions([]):
        #print perm
        addElement(root, 'rint', perm)

    for perm in app.get_permissions():
        #print perm
        addElement(root, 'permission', perm)

    addElement(root, 'package', app.get_package())

    feed = open(fileout, 'w')
    s = etree.tostring(root, pretty_print=True)
    feed.write(s)
    feed.close()
示例#19
0
def check_one_directory(directory):
    for root, dirs, files in os.walk(directory, followlinks=True):
        if files != []:
            for f in files:
                real_filename = root
                if real_filename[-1] != "/":
                    real_filename += "/"
                real_filename += f

                print("filename: %s ..." % real_filename)
                ret_type = androconf.is_android(real_filename)
                if ret_type == "APK":
                    a = apk.APK(real_filename)
                    d1 = dvm.DalvikVMFormat(a.get_dex())
                elif ret_type == "DEX":
                    d1 = dvm.DalvikVMFormat(read(real_filename))

                dx1 = analysis.VMAnalysis(d1)
                check_one_file(d1, dx1)
示例#20
0
def main(options, arguments) :
    if options.input != None  and options.output != None and options.name != None and options.subname != None :
        edi = ElsimDBIn( options.output )

        ret_type = androconf.is_android( options.input )
        if ret_type == "APK" :
            a = apk.APK( options.input )
            d1 = dvm.DalvikVMFormat( a.get_dex() )
        elif ret_type == "DEX" :
            d1 = dvm.DalvikVMFormat( open(options.input, "rb").read() )

        dx1 = analysis.VMAnalysis( d1 )

        regexp_pattern = None
        regexp_exclude_pattern = None

        edi.add( d1, dx1, options.name, options.sname, regexp_pattern, regexp_exclude_pattern)
        edi.save()

    elif options.version != None :
        print "Androapptodb version %s" % androconf.ANDROGUARD_VERSION
示例#21
0
def initStatic(APKFile):
    a = apk.APK(APKFile)
    d = dvm.DalvikVMFormat(a.get_dex())
    dx = analysis.VMAnalysis(d)
    vm = dx.get_vm()
    cm = vm.get_class_manager()
    per = a.get_permissions()
    pa = dx.get_permissions([])
    USE = [p for p in SPECIAL_PERMS if "android.permission." + p in per]
    specialPath = dx.get_tainted_packages().search_methods(
        "Landroid/content/ContentResolver;", ".", ".")
    specialPath += dx.get_tainted_packages().search_methods(
        "Landroid/content/ContentProvider;", ".", ".")
    specialPath += dx.get_tainted_packages().search_methods(
        "Landroid/content/ContentProviderClient;", ".", ".")
    specialPath += dx.get_tainted_packages().search_methods(
        "Landroid/net/Uri;", "parse", ".")
    if len(specialPath) > 0 and len(USE) > 0:
        for i in USE:
            pa[i] = specialPath

    for i in pa:
        if i in PERM_DESCRIPTION:
            met = set()
            for j in pa[i]:
                t = returnMethod(j, cm)
                if t != 0:
                    met.add(t)
            permap[i] = met

    execPath = dx.get_tainted_packages().search_methods(
        "Ljava/lang/Runtime;", "exec", ".")
    if len(execPath) > 0:
        met = set()
        for j in execPath:
            t = returnMethod(j, cm)
            if t != 0:
                met.add(t)
        permap['CMD_EXEC'] = met
示例#22
0
def main(options, arguments):
    if options.input != None and options.database != None:
        ret_type = androconf.is_android(options.input)
        if ret_type == "APK":
            a = apk.APK(options.input)
            d1 = dvm.DalvikVMFormat(a.get_dex())
        elif ret_type == "DEX":
            d1 = dvm.DalvikVMFormat(read(options.input))

        dx1 = analysis.VMAnalysis(d1)

        check_one_file(d1, dx1)

    elif options.directory != None and options.database != None:
        check_one_directory(options.directory)

    elif options.database != None and options.listdatabase != None:
        db = DBFormat(options.database)
        db.show()

    elif options.version != None:
        print("Androappindb version %s" % androconf.ANDROGUARD_VERSION)
示例#23
0
def main(options, arguments):
    if options.input != None:
        a = None
        ret_type = androconf.is_android(options.input[0])
        if ret_type == "APK":
            a = apk.APK(options.input[0])
            d1 = dvm.DalvikVMFormat(a.get_dex())
        elif ret_type == "DEX":
            d1 = dvm.DalvikVMFormat(read(options.input[0]))

        dx1 = analysis.VMAnalysis(d1)

        threshold = None
        if options.threshold != None:
            threshold = float(options.threshold)

        FS = FILTERS_DALVIK_SIM
        FS[elsim.FILTER_SKIPPED_METH].set_regexp(options.exclude)
        FS[elsim.FILTER_SKIPPED_METH].set_size(options.size)

        new = True
        if options.new != None:
            new = False

        library = False
        if options.library != None:
            library = options.library
            if options.library == "python":
                library = False

        if os.path.isdir(options.input[1]) == False:
            check_one_file(a, d1, dx1, FS, threshold, options.input[1],
                           options.xstrings, new, library)
        else:
            check_one_directory(a, d1, dx1, FS, threshold, options.input[1],
                                options.xstrings, new, library)

    elif options.version != None:
        print "Androsim version %s" % androconf.ANDROGUARD_VERSION
示例#24
0
def main(options, arguments):
    if options.input != None and options.output != None:

        ret_type = androconf.is_android(options.input)
        vm = None
        a = None
        if ret_type == "APK":
            a = apk.APK(options.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(options.input, "rb").read())
            except Exception, e:
                print "INVALID DEX", e

        vmx = analysis.VMAnalysis(vm)
        gvmx = ganalysis.GVMAnalysis(vmx, a)

        create_directories(vm, options.output)

        #        dv.export_to_gml( options.output )

        dd = data.Data(vm, vmx, gvmx, a)

        buff = dd.export_apk_to_gml()
        androconf.save_to_disk(buff, options.output + "/" + "apk.graphml")

        buff = dd.export_methodcalls_to_gml()
        androconf.save_to_disk(buff,
                               options.output + "/" + "methodcalls.graphml")

        buff = dd.export_dex_to_gml()
        for i in buff:
            androconf.save_to_disk(buff[i],
                                   options.output + "/" + i + ".graphml")
示例#25
0
def export_apps_to_xgmml(input, output, fcg, efcg):
    a = Androguard([input])

    with open(output, "w") as fd:
        fd.write("<?xml version='1.0'?>\n")
        fd.write(
            "<graph label=\"Androguard XGMML %s\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ns1=\"http://www.w3.org/1999/xlink\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns=\"http://www.cs.rpi.edu/XGMML\" directed=\"1\">\n"
            % (os.path.basename(input)))

        for vm in a.get_vms():
            x = analysis.VMAnalysis(vm)
            # CFG
            for method in vm.get_methods():
                g = x.get_method(method)
                export_xgmml_cfg(g, fd)

            if fcg:
                export_xgmml_fcg(vm, x, fd)

            if efcg:
                export_xgmml_efcg(vm, x, fd)

        fd.write("</graph>")
示例#26
0
def main(options, arguments):
    if options.input != None and options.output != None:
        ret_type = androconf.is_android(options.input)

        vm = None
        a = None
        if ret_type == "APK":
            a = apk.APK(options.input)
            if a.is_valid_APK():
                vm = dvm.DalvikVMFormat(a.get_dex())
            else:
                print("INVALID APK")
        elif ret_type == "DEX":
            try:
                vm = dvm.DalvikVMFormat(read(options.input))
            except Exception as e:
                print("INVALID DEX", e)

        vmx = analysis.VMAnalysis(vm)
        gvmx = ganalysis.GVMAnalysis(vmx, a)

        b = gvmx.export_to_gexf()
        androconf.save_to_disk(b, options.output)
示例#27
0
def main(options, arguments) :
    details = False
    if options.display != None :
        details = True
    
    if options.input != None :
        ret_type = androconf.is_android( options.input[0] )
        if ret_type == "APK" :
            a = apk.APK( options.input[0] )
            d1 = dvm.DalvikVMFormat( a.get_dex() )
        elif ret_type == "DEX" :
            d1 = dvm.DalvikVMFormat( open(options.input[0], "rb").read() )
        
        dx1 = analysis.VMAnalysis( d1 )
       
        ret_type = androconf.is_android( options.input[1] )
        if ret_type == "APK" :
            a = apk.APK( options.input[1] )
            d2 = dvm.DalvikVMFormat( a.get_dex() )
        elif ret_type == "DEX" :
            d2 = dvm.DalvikVMFormat( open(options.input[1], "rb").read() )
        
        dx2 = analysis.VMAnalysis( d2 )

        print d1, dx1, d2, dx2
        sys.stdout.flush()
        
        threshold = None
        if options.threshold != None :
            threshold = float(options.threshold)

        FS = FILTERS_DALVIK_SIM
        FS[elsim.FILTER_SKIPPED_METH].set_regexp( options.exclude )
        FS[elsim.FILTER_SKIPPED_METH].set_size( options.size )
        el = elsim.Elsim( ProxyDalvik(d1, dx1), ProxyDalvik(d2, dx2), FS, threshold, options.compressor )
        el.show()

        e1 = elsim.split_elements( el, el.get_similar_elements() )
        for i in e1 :
            j = e1[ i ]
            elb = elsim.Elsim( ProxyDalvikMethod(i), ProxyDalvikMethod(j), FILTERS_DALVIK_BB, threshold, options.compressor )
            #elb.show()

            eld = elsim.Eldiff( ProxyDalvikBasicBlock(elb), FILTERS_DALVIK_DIFF_BB )
            #eld.show()

            ddm = DiffDalvikMethod( i, j, elb, eld )
            ddm.show()

        print "NEW METHODS"
        enew = el.get_new_elements()
        for i in enew :
            el.show_element( i, False )

        print "DELETED METHODS"
        edel = el.get_deleted_elements()
        for i in edel :
            el.show_element( i )

    elif options.version != None :
        print "Androdiff version %s" % androconf.ANDROGUARD_VERSION
示例#28
0
def export_apps_to_format(filename,
                          a,
                          output,
                          methods_filter=None,
                          jar=None,
                          decompiler_type=None,
                          format=None):
    print "Dump information %s in %s" % (filename, output)

    if not os.path.exists(output):
        print "Create directory %s" % output
        os.makedirs(output)
    else:
        print "Clean directory %s" % output
        androconf.rrmdir(output)
        os.makedirs(output)

    methods_filter_expr = None
    if methods_filter:
        methods_filter_expr = re.compile(methods_filter)

    output_name = output
    if output_name[-1] != "/":
        output_name = output_name + "/"

    dump_classes = []
    for vm in a.get_vms():
        print "Analysis ...",
        sys.stdout.flush()
        vmx = analysis.VMAnalysis(vm)
        print "End"

        print "Decompilation ...",
        sys.stdout.flush()

        if not decompiler_type:
            vm.set_decompiler(decompiler.DecompilerDAD(vm, vmx))
        elif decompiler_type == "dex2jad":
            vm.set_decompiler(
                decompiler.DecompilerDex2Jad(vm,
                                             androconf.CONF["PATH_DEX2JAR"],
                                             androconf.CONF["BIN_DEX2JAR"],
                                             androconf.CONF["PATH_JAD"],
                                             androconf.CONF["BIN_JAD"],
                                             androconf.CONF["TMP_DIRECTORY"]))
        elif decompiler_type == "dex2winejad":
            vm.set_decompiler(
                decompiler.DecompilerDex2WineJad(
                    vm, androconf.CONF["PATH_DEX2JAR"],
                    androconf.CONF["BIN_DEX2JAR"], androconf.CONF["PATH_JAD"],
                    androconf.CONF["BIN_WINEJAD"],
                    androconf.CONF["TMP_DIRECTORY"]))
        elif decompiler_type == "ded":
            vm.set_decompiler(
                decompiler.DecompilerDed(vm, androconf.CONF["PATH_DED"],
                                         androconf.CONF["BIN_DED"],
                                         androconf.CONF["TMP_DIRECTORY"]))
        elif decompiler_type == "dex2fernflower":
            vm.set_decompiler(
                decompiler.DecompilerDex2Fernflower(
                    vm, androconf.CONF["PATH_DEX2JAR"],
                    androconf.CONF["BIN_DEX2JAR"],
                    androconf.CONF["PATH_FERNFLOWER"],
                    androconf.CONF["BIN_FERNFLOWER"],
                    androconf.CONF["OPTIONS_FERNFLOWER"],
                    androconf.CONF["TMP_DIRECTORY"]))
        else:
            raise ("invalid decompiler !")
        print "End"

        if options.jar:
            print "jar ...",
            filenamejar = decompiler.Dex2Jar(
                vm, androconf.CONF["PATH_DEX2JAR"],
                androconf.CONF["BIN_DEX2JAR"],
                androconf.CONF["TMP_DIRECTORY"]).get_jar()
            shutil.move(filenamejar, output + "classes.jar")
            print "End"

        for method in vm.get_methods():
            if methods_filter_expr:
                msig = "%s%s%s" % (method.get_class_name(), method.get_name(),
                                   method.get_descriptor())
                if not methods_filter_expr.search(msig):
                    continue

            filename_class = valid_class_name(method.get_class_name())
            create_directory(filename_class, output)

            print "Dump %s %s %s ..." % (method.get_class_name(),
                                         method.get_name(),
                                         method.get_descriptor()),

            filename_class = output_name + filename_class
            if filename_class[-1] != "/":
                filename_class = filename_class + "/"

            descriptor = method.get_descriptor()
            descriptor = descriptor.replace(";", "")
            descriptor = descriptor.replace(" ", "")
            descriptor = descriptor.replace("(", "-")
            descriptor = descriptor.replace(")", "-")
            descriptor = descriptor.replace("/", "_")

            filename = filename_class + method.get_name() + descriptor
            if len(method.get_name() + descriptor) > 250:
                all_identical_name_methods = vm.get_methods_descriptor(
                    method.get_class_name(), method.get_name())
                pos = 0
                for i in all_identical_name_methods:
                    if i.get_descriptor() == method.get_descriptor():
                        break
                    pos += 1

                filename = filename_class + method.get_name() + "_%d" % pos

            buff = method2dot(vmx.get_method(method))

            if format:
                print "%s ..." % format,
                method2format(filename + "." + format, format, None, buff)

            if method.get_class_name() not in dump_classes:
                print "source codes ...",
                current_class = vm.get_class(method.get_class_name())
                current_filename_class = valid_class_name(
                    current_class.get_name())
                create_directory(filename_class, output)

                current_filename_class = output_name + current_filename_class + ".java"
                fd = open(current_filename_class, "w")
                fd.write(current_class.get_source())
                fd.close()

                dump_classes.append(method.get_class_name())

            print "bytecodes ...",
            bytecode_buff = dvm.get_bytecodes_method(vm, vmx, method)
            fd = open(filename + ".ag", "w")
            fd.write(bytecode_buff)
            fd.close()

            print
示例#29
0
        ) == "Lre/androguard/android/invalid/MainActivity;":
            #if i.get_name() == "testStrings":
            #    instructions = [ins for ins in i.get_instructions()]
            #    instructions[0].BBBB = 10000
            #    i.set_instructions(instructions)
            if i.get_name() == "testInstances":
                instructions = [ins for ins in i.get_instructions()]
                instructions[0].BBBB = 0x4141
                i.set_instructions(instructions)


FILENAME_INPUT = "./examples/android/Invalid/Invalid.apk"
FILENAME_OUTPUT = "./toto.apk"

androconf.set_debug()

a = apk.APK(FILENAME_INPUT)
vm = dvm.DalvikVMFormat(a.get_dex())
vmx = analysis.VMAnalysis(vm)

patch_dex(vm)

new_dex = vm.save()

a.new_zip(filename=FILENAME_OUTPUT,
          deleted_files="(META-INF/.)",
          new_files={"classes.dex": new_dex})

# Please configure your keystore !! :) follow the tutorial on android website
apk.sign_apk(FILENAME_OUTPUT, "./keystore/keystore1", "tototo")
示例#30
0
#!/usr/bin/env python

import sys, hashlib

PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL)

from androguard.core.androgen import AndroguardS
from androguard.core.analysis import analysis

TEST = 'examples/android/TestsAndroguard/bin/classes.dex'

a = AndroguardS(TEST)
x = analysis.VMAnalysis(a.get_vm())

for method in a.get_methods():
    g = x.get_method(method)

    if method.get_code() == None:
        continue

    idx = 0
    for i in g.basic_blocks.get():
        for ins in i.get_instructions():
            op_value = ins.get_op_value()

            # packed/sparse
            if op_value == 0x2b or op_value == 0x2c:
                special_ins = i.get_special_ins(idx)
                if special_ins != None:
                    print "\t %x" % idx, ins, special_ins, ins.get_name(