Esempio n. 1
0
def main():

    _args = _parseargs()
	
    _a = apk.APK(_args.file)
    print("Analyse file: {:s}".format(_args.file))
    print("Package name: {:s}".format(_a.get_package()))
	
    _vm = dvm.DalvikVMFormat(_a.get_dex())
    _vmx = uVMAnalysis(_vm)
	
    if 'android.permission.INTERNET' in _vmx.get_permissions([]):
        print "App requires INTERNET permission. Continue analysis..."
		
        _vm.create_python_export()
        _gx = GVMAnalysis(_vmx, None)

        _vm.set_vmanalysis(_vmx)
        _vm.set_gvmanalysis(_gx)
        _vm.create_dref(_vmx)
        _vm.create_xref(_vmx)
		
        _result = {'trustmanager' : [], 'hostnameverifier' : [], 'onreceivedsslerror' : []}
        _result = _check_all(_vm, _vmx, _gx)
		
        if not _args.xml:
            _print_result(_result, _java=_args.java)
        else:
            _xml_result(_a, _result)
		
        if _args.dir:
                print "Store decompiled Java code in {:s}".format(_args.dir)
                _store_java(_vm, _args)
        else:
            print "App does not require INTERNET permission. No need to worry about SSL misuse... Abort!"
    def __init__(self, args):

        self.apk = args.apk
        self.verbosity = args.verbosity
        self.output_location = args.output_location
        self.file_identifier = args.apk.split('.')[0]
        self.file_identifier = self.file_identifier[-24:]

        # print "Analyzing " + self.apk
        # print " Output Location " + self.output_location
        # print "File Identifier " + self.file_identifier

        # analyze the dex file
        print "From LOCATION = ", self.apk
        self.a = APK(self.apk)

        # get the vm analysis
        self.d = DalvikVMFormat(self.a.get_dex())
        self.dx = VMAnalysis(self.d)
        self.gx = GVMAnalysis(self.dx, None)

        self.d.set_vmanalysis(self.dx)
        self.d.set_gvmanalysis(self.gx)

        # create the cross reference
        self.d.create_xref()
        self.d.create_dref()

        print 'CWD: ', os.getcwd()
        predictor = Predict_Input(self.output_location, self.file_identifier)
        self.predictions = predictor.predict(self.apk, self.apk[:-4],
                                             self.output_location,
                                             self.file_identifier)

        try:
            # get the classes for this apk
            # store them in a dict
            self.classes = self.get_class_dict()

            # Find the R$layout class
            self.Rlayout = self.get_RLayout(self.d.get_classes())

            # Find the R$id class
            self.Rid = self.get_Rid(self.d.get_classes())

            # Store all fields referenced in R$id
            self.fields, self.field_refs = self.get_fields(self.Rid)
        except Exception, e:
            print e
Esempio n. 3
0
    def __init__(self, apk_name):
        self.apk_name = apk_name
        self.apk = INPUT_APK_DIR + self.apk_name + ".apk"

        # analyze the dex file
        self.a = APK(self.apk)

        # get the vm analysis
        self.d = DalvikVMFormat(self.a.get_dex())
        self.dx = VMAnalysis(self.d)
        self.gx = GVMAnalysis(self.dx, None)

        self.d.set_vmanalysis(self.dx)
        self.d.set_gvmanalysis(self.gx)

        # create the cross reference
        self.d.create_xref()
        self.d.create_dref()
Esempio n. 4
0
def _store_java(_vm, _args):
    _vm.create_python_export()
    _vmx = uVMAnalysis(_vm)
    _gx = GVMAnalysis(_vmx, None)
    _vm.set_vmanalysis(_vmx)
    _vm.set_gvmanalysis(_gx)
    _vm.create_dref(_vmx)
    _vm.create_xref(_vmx)

    for _class in _vm.get_classes():
        try:
            _ms = decompile.DvClass(_class, _vmx)
            _ms.process()
            _f = _file_name(_class.get_name(), _args.storejava)
            _ensure_dir(_f)
            with open(_f, "w") as f:
                _java = str(_ms.get_source())
                f.write(_java)
        except Exception, e:
                print("Could not process {:s}: {:s}".format(_class.get_name(), str(e)))
Esempio n. 5
0
    def process_vm(self):
        """
        Process the application's classes.dex

        Args:
            None

        Results:
            None
        """
        # Make sure classes.dex exists
        if self.find_dex():
            self.dex = self.apk.get_dex()
            # Analyze classes.dex
            # TODO Throw in a progress bar, this can take awhile
            if self.dex:
                self.logger.log("info", "Loading classes.dex ...")
                from androguard.core.bytecodes.dvm import DalvikVMFormat
                from androguard.core.analysis.analysis import VMAnalysis
                from androguard.core.analysis.ganalysis import GVMAnalysis
                # Create a new virtual machine instance
                self.vm = DalvikVMFormat(self.dex)
                if self.vm:
                    print(self.t.yellow("\n\t--> Loaded classes.dex (!)\n"))
                    self.logger.log("info", "Analyzing classes.dex ...")
                    # Analyze the virtual machine instance
                    self.vmx = VMAnalysis(self.vm)
                    self.gmx = GVMAnalysis(self.vmx, None)
                    if self.vmx and self.gmx:
                        print(self.t.yellow("\n\t--> Analyzed classes.dex (!)\n"))
                        self.vm.set_vmanalysis(self.vmx)
                        self.vm.set_gvmanalysis(self.gmx)
                        # Generate xref(s)
                        self.vm.create_xref()
                        self.vm.create_dref()
                    else:
                        CommandError("Cannot analyze VM instance (!)")
                else:
                    CommandError("Cannot load VM instance (!)")
        else:
            CommandError("classes.dex not found (!)")
Esempio n. 6
0
def runMallodroid(app):
    assert isinstance(app, Apps), "app is not type Apps: %r" % app
    logger.info("%s running Mallodroid ", app.package)
    _a = apk.APK(app.path_to_apk)

    _vm = dvm.DalvikVMFormat(_a.get_dex())
    _vmx = uVMAnalysis(_vm)

    if 'android.permission.INTERNET' in _vmx.get_permissions([]):
        logger.debug('%s requires INTERNET permission. Continue analysis',
                     app.package)

        _vm.create_python_export()
        _gx = GVMAnalysis(_vmx, None)

        _vm.set_vmanalysis(_vmx)
        _vm.set_gvmanalysis(_gx)
        _vm.create_dref(_vmx)
        _vm.create_xref(_vmx)

        _result = {
            'trustmanager': [],
            'hostnameverifier': [],
            'onreceivedsslerror': []
        }
        _result = mallodroid._check_all(_vm, _vmx, _gx)

        try:
            return mallodroid._xml_result(_a, _result)
        except TypeError as e:
            logger.error("error %s .. proceeding" % e)
        #    print "Store decompiled Java code in {:s}".format(_args.dir)
        #   _store_java(_vm, _args)

    else:
        logger.info(
            "%s does not require INTERNET permission. No need to worry about SSL misuse... Abort!",
            app.package)
        return "NO SSL"
Esempio n. 7
0
    def __init__(self, args):
        self.apk = args.apk
        self.verbosity = args.verbosity

        print "Analyzing " + self.apk

        # analyze the dex file
        self.a = APK(self.apk)

        # get the vm analysis
        self.d = DalvikVMFormat(self.a.get_dex())
        self.dx = VMAnalysis(self.d)
        self.gx = GVMAnalysis(self.dx, None)

        self.d.set_vmanalysis(self.dx)
        self.d.set_gvmanalysis(self.gx)

        # create the cross reference
        self.d.create_xref()
        self.d.create_dref()

        try:
            # get the classes for this apk
            # store them in a dict
            self.classes = self.get_class_dict()

            # Find the R$layout class
            self.Rlayout = self.get_RLayout(self.d.get_classes())

            # Find the R$id class
            self.Rid = self.get_Rid(self.d.get_classes())

            # Store all fields referenced in R$id
            self.fields, self.field_refs = self.get_fields(self.Rid)
        except Exception, e:
            print e
Esempio n. 8
0
def analyze_dex(filepath_or_raw,
                needs_dalvik_vm_format=True,
                needs_vm_analysis=True,
                needs_gvm_analysis=True,
                needs_xref=True,
                needs_dref=True,
                raw=False,
                decompiler="dad"):
    '''
    Open the classes.dex file `needs_dalvik_vm_format`
    and set up an analyzer for it `needs_vm_analysis`.

    Parameters
    ----------
    filepath_or_raw : path to file or raw data
         Set raw to True if `filepath_or_raw` is raw data.
    needs_dalvik_vm_format : bool, optional (default is True)
    needs_vm_analysis : bool, optional (default is True)
    needs_gvm_analysis : bool, optional (default is True)
    needs_xref : bool, optional (default is True)
    needs_dref : bool, optional (default is True)
    raw : bool, optional (default is False)
    decompiler : str, optional (default is "dad")

    Returns
    -------
    tuple<DalvikVMFormat, VMAnalysis, GVMAnalysis>

    Raises
    ------
    DexError
        If an error occurred while creating the analysis objects.
    '''

    dalvik_vm_format, vm_analysis, gvm_analysis = None, None, None
    # every requirement implies the need for the `dalvik_vm_format`
    needs_dalvik_vm_format = any((needs_dalvik_vm_format, needs_vm_analysis,
                                  needs_gvm_analysis, needs_xref, needs_dref))
    cross_ref = any((needs_xref, needs_dref))

    try:
        if needs_dalvik_vm_format:
            if raw == False:
                with open(filepath_or_raw, "rb") as f:
                    dalvik_vm_format = DalvikVMFormat(f.read())
            else:
                dalvik_vm_format = DalvikVMFormat(filepath_or_raw)

            if needs_vm_analysis or cross_ref or needs_gvm_analysis:
                vm_analysis = uVMAnalysis(dalvik_vm_format)
                dalvik_vm_format.set_vmanalysis(vm_analysis)

            if needs_gvm_analysis or cross_ref:
                gvm_analysis = GVMAnalysis(vm_analysis, None)
                dalvik_vm_format.set_gvmanalysis(gvm_analysis)

            if dalvik_vm_format:
                RunDecompiler(dalvik_vm_format, vm_analysis, decompiler)

            # create references, gvm_analysis needed!
            # we optimize through not exporting the references into the python objects
            if needs_xref:
                dalvik_vm_format.create_xref(python_export=False)
            if needs_dref:
                dalvik_vm_format.create_dref(python_export=False)

    except Exception as e:
        # androguard caused error -> propagate as DexError
        raise DexError(caused_by=e), None, sys.exc_info()[2]

    return dalvik_vm_format, vm_analysis, gvm_analysis
Esempio n. 9
0
    def process_vm(self, apk=False, dex=False):
        """
        Process the application's classes.dex

        Args:
            param1 = boolean
            param2 = boolean

        Results:
            None
        """
        try:
            if apk:
                # Make sure the APK contains a classes.dex file
                if self.find_dex():
                    self.dex = self.apk.get_dex()
                    if self.dex:
                        self.logger.log("info", "Loading classes.dex ...")
                        from androguard.core.bytecodes.dvm import DalvikVMFormat
                        from androguard.core.analysis.analysis import VMAnalysis
                        from androguard.core.analysis.ganalysis import GVMAnalysis
                        # Create a DalvikVMFormat instance ...
                        # In this case self.dex will be a file type
                        self.vm = DalvikVMFormat(self.dex)
                        if self.vm:
                            print(self.t.yellow("\n\t--> Loaded classes.dex (!)\n"))
                            self.logger.log("info", "Analyzing classes.dex ...")
                            # Analyze the DalvikVMFormat instance and return
                            # analysis instances of VMAnalysis and GVMAnalysis
                            self.vmx = VMAnalysis(self.vm)
                            self.gmx = GVMAnalysis(self.vmx, None)
                            if self.vmx and self.gmx:
                                print(self.t.yellow("\n\t--> Analyzed classes.dex (!)\n"))
                                # Set the analysis properties on the
                                # DalvikVMFormat instance
                                self.vm.set_vmanalysis(self.vmx)
                                self.vm.set_gvmanalysis(self.gmx)
                                # Generate xref(s) and dref(s)
                                self.vm.create_xref()
                                self.vm.create_dref()
                                return
                            else:
                                CommandError("process_vm : Cannot analyze VM instance (!)")
                                return
                        else:
                            CommandError("process_vm : Cannot load VM instance (!)")
                            return
                    else:
                        CommandError("process_vm : classes.dex not found (!)")
                        return
            if dex:
                if self.dex:
                    from androguard.core.bytecodes.dvm import DalvikVMFormat
                    from androguard.core.analysis.analysis import VMAnalysis
                    from androguard.core.analysis.ganalysis import GVMAnalysis
                    # Analyze the DalvikVMFormat instance and return
                    # analysis instances of VMAnalysis and GVMAnalysis
                    self.vm = DalvikVMFormat(self.util.read(self.dex))
                    if self.vm:
                        print(self.t.yellow("\n\t--> Loaded {} (!)\n"
                                            .format(self.dex
                                                    .split("/")[-1])))
                        self.logger.log("info", "Analyzing {} ..."
                                        .format(self.dex
                                                .split("/")[-1]))
                        # Set the analysis properties on the
                        # DalvikVMFormat instance
                        self.vmx = VMAnalysis(self.vm)
                        self.gmx = GVMAnalysis(self.vmx, None)
                        if self.vmx and self.gmx:
                            print(self.t.yellow("\n\t--> Analyzed {} (!)\n"
                                                .format(self.dex
                                                        .split("/")[-1])))
                            # Set the analysis properties on the
                            # DalvikVMFormat instance
                            self.vm.set_vmanalysis(self.vmx)
                            self.vm.set_gvmanalysis(self.gmx)
                            # Generate xref(s) and dref(s)
                            self.vm.create_xref()
                            self.vm.create_dref()
                            return
                        else:
                            CommandError("process_vm :" +
                                         "Cannot analyze VM instance (!)")
                            return
                    else:
                        CommandError("process_vm :" +
                                     "Cannot load VM instance (!)")
                        return
                else:
                    CommandError("process_vm : classes.dex not found (!)")
                    return
        except Exception as e:
            CommandError("process_vm : {}".format(e))
Esempio n. 10
0
            if depth == 0:
                print(m.class_name + " -> " + m.name)
            for item in m.XREFfrom.items:
                if item[0].class_name != class_name or item[
                        0].name != method_name:
                    for x in range(1, depth):
                        sys.stdout.write('--')
                    sys.stdout.write('>' + item[0].class_name + "->" +
                                     item[0].name + "\n")
                    XrefTraverse(methods, item[0].class_name, item[0].name,
                                 depth)


if len(sys.argv) > 2:
    filename = sys.argv[1]
    class_name = sys.argv[2]
    class_name = 'L' + class_name.replace(".", "/") + ";"
    #print class_name
    method_name = '<init>'
    d = DalvikVMFormat(APK(filename, False).get_dex())
    d.create_python_export()
    dx = uVMAnalysis(d)
    gx = GVMAnalysis(dx, None)
    d.set_vmanalysis(dx)
    d.set_gvmanalysis(gx)
    d.create_xref()

    XrefTraverse(d.get_methods(), class_name, method_name, 0)
else:
    print "usage: XrefTree.py [filename] [class_name]"
    print "usage: XrefTree.py filename.apk com.xyz.abc"