示例#1
0
    def _load_file(self, file_path):
        self.file_path = file_path
        file_type = os.path.splitext(file_path)[1]

        if file_type == ".apk":
            self.a = apk.APK(file_path)

            self.filename = os.path.basename(self.a.get_filename())
            self.appID = self.a.get_package()
            self.permissions = self.a.get_permissions()

            # Multidex app support
            for dex in self.a.get_dex():
                _d = dvm.DalvikVMFormat(dex)
                _dx = analysis.uVMAnalysis(_d)

                self.d.append(_d)
                self.dx.append(_dx)

            self.classes_names = self._get_classes_names()

        elif file_type == ".dex":
            _d = dvm.DalvikVMFormat(read(file_path))
            _dx = analysis.uVMAnalysis(_d)

            self.d = [_d]
            self.dx = [_dx]
            self.classes_names = self._get_classes_names()

        elif file_type == ".json":
            with open(file_path) as fd:
                data = json.load(fd)

            # If this is an app profile
            if "appID" in data:
                self.filename = data["filename"]
                self.appID = data["appID"]
                self.permissions = data["permissions"]
            # If this is a lib profile
            else:
                self.lib_name = data["name"]
                self.lib_version = data["version"]
                self.category = data["category"]
                self.root_package = data["root_package"]

            self._classes_signatures = data["classes_signatures"]
            self.classes_names = self._classes_signatures.keys()
            self._classes_xref_tos = data["classes_xref_tos"]
            self._classes_interfaces = data["classes_interfaces"]
            self._classes_superclass = data["classes_superclass"]
示例#2
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!"
示例#3
0
    def run(self):

        """
        Search for logging API usage within target class and methods
        """

        x = analysis.uVMAnalysis(self.apks.get_vm())
        vm = self.apks.get_vm()

        if x:
            print(t.green("[{0}] ".format(datetime.now()) + t.yellow("Performing surgery ...")))
            # Get enum values
            #
            for a, b in self.enum.values.items():
                for c in b:
                    paths = x.get_tainted_packages().search_methods("{0}".format(a), "{0}".format(c), ".")
                    if paths:
                        for p in paths:
                            for method in self.apks.get_methods():
                                if method.get_name() == p.get_src(vm.get_class_manager())[1]:
                                    if method.get_class_name() == p.get_src(vm.get_class_manager())[0]:
                                        print(t.green("[{0}] ".format(datetime.now()) +
                                              t.yellow("Found: ") +
                                              "{0}".format(c)))
                                        print(t.green("[{0}] ".format(datetime.now()) +
                                                      t.yellow("Class: ") +
                                                      "{0}".format(method.get_class_name())))
                                        print(t.green("[{0}] ".format(datetime.now()) +
                                                      t.yellow("Method: ") +
                                                      "{0}".format(method.get_name())))
                                        print(method.show())
示例#4
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!"
示例#5
0
文件: risk.py 项目: hetykai/works
    def with_apk(self, apk_file):
        if apk_file.is_valid_APK():
            d = dvm.DalvikVMFormat(apk_file.get_dex())
            dx = analysis.uVMAnalysis(d)

            return self.with_apk_direct(apk_file, d, dx)
        return {}
示例#6
0
文件: decompile.py 项目: DarioI/ARES
 def __init__(self, name):
     vm = auto_vm(name)
     if vm is None:
         raise ValueError('Format not recognised: %s' % name)
     self.vma = analysis.uVMAnalysis(vm)
     self.classes = dict((dvclass.get_name(), dvclass)
                         for dvclass in vm.get_classes())
示例#7
0
    def run(self):

        """
        Search for storage API usage within target class and methods
        """

        x = analysis.uVMAnalysis(self.apks.get_vm())
        vm = self.apks.get_vm()

        if x:
            print(t.green("[{0}] ".format(datetime.now()) + t.yellow("Performing surgery ...")))
            # Get enum values
            #
            for v in self.enum.values:
                # This returns PathP
                # objects into a list
                #
                paths = x.get_tainted_packages().search_methods("android.content.Context", "{0}".format(v), ".")

                if paths:
                    for p in paths:
                        for method in self.apks.get_methods():
                            if method.get_name() == p.get_src(vm.get_class_manager())[1]:
                                if method.get_class_name() == p.get_src(vm.get_class_manager())[0]:
                                    print(t.green("[{0}] ".format(datetime.now()) +
                                          t.yellow("Found: ") +
                                          "{0}".format(v)))
                                    print(t.green("[{0}] ".format(datetime.now()) +
                                                  t.yellow("Class: ") +
                                                  "{0}".format(method.get_class_name())))
                                    print(t.green("[{0}] ".format(datetime.now()) +
                                                  t.yellow("Method: ") +
                                                  "{0}".format(method.get_name())))
                                    print(method.show())
示例#8
0
    def loadedApk(self, success):
        self.sample_dialog.close()
        if not success:
            self.__logger.log(
                Logger.ERROR, "Analysis of %s failed :(" %
                str(self.fileLoadingThread.file_path))
            self.set_loading_progressbar_disabled()
            return

        self.d = self.session.get_DalvikForm()
        self.d.create_python_export()
        self.x = uVMAnalysis(self.d)

        self.setupTree()
        self.setupResourceController()
        self.load_app_info_table()
        self.load_permissions()
        try:
            self.__logger.log(
                Logger.INFO,
                "Analysis of %s done!" % str(self.apk.get_app_name()))
            self.ui.loadedAPK_label.setText("Loaded: " +
                                            str(self.apk.get_app_name()))
        except UnicodeEncodeError:
            self.ui.loadedAPK_label.setText(
                "APK Loaded! (non-ascii chars detected)")
            self.__logger.log(
                Logger.WARNING,
                "Non ascii code characters detected, some strings are possibly not displayed properly."
            )
        self.set_loading_progressbar_disabled()
示例#9
0
文件: bowser.py 项目: ye-man/lobotomy
    def run_bowser(self):
        """
        Run the bowser toolkit
        """

        # Search for parseUri()
        #
        x = analysis.uVMAnalysis(self.apks.get_vm())

        if x:
            print(
                t.green("[{0}] ".format(datetime.now()) +
                        t.yellow("Searching for parseUri()")))
            analysis.show_Paths(
                self.apks,
                x.get_tainted_packages().search_methods(".", "parseUri", "."))

            print(
                t.green("[{0}] ".format(datetime.now()) +
                        t.yellow("Searching for loadUrl()")))
            analysis.show_Paths(
                self.apks,
                x.get_tainted_packages().search_methods(".", "loadUrl", "."))

            print(
                t.green("[{0}] ".format(datetime.now()) +
                        t.yellow("Searching for addJavascriptInterface()")))
            analysis.show_Paths(
                self.apks,
                x.get_tainted_packages().search_methods(
                    ".", "addJavascriptInterface", "."))
示例#10
0
    def with_apk(self, apk_file):
        if apk_file.is_valid_APK():
            d = dvm.DalvikVMFormat(apk_file.get_dex())
            dx = analysis.uVMAnalysis(d)

            return self.with_apk_direct(apk_file, d, dx)
        return {}
示例#11
0
 def __init__(self, name):
     vm = auto_vm(name)
     if vm is None:
         raise ValueError('Format not recognised: %s' % name)
     self.vma = analysis.uVMAnalysis(vm)
     self.classes = dict(
         (dvclass.get_name(), dvclass) for dvclass in vm.get_classes())
示例#12
0
    def run(self):
        """Run androguard to extract static android information
                @return: list of static features
        """
        self.key = "apkinfo"
        apkinfo = {}

        if "file" not in self.task["category"]:
            return

        from androguard.core.bytecodes.apk import APK
        from androguard.core.bytecodes.dvm import DalvikVMFormat
        from androguard.core.analysis.analysis import uVMAnalysis
        from androguard.core.analysis import analysis

        f = File(self.task["target"])
        if f.get_name().endswith((".zip", ".apk")) or "zip" in f.get_type():
            if not os.path.exists(self.file_path):
                raise CuckooProcessingError("Sample file doesn't exist: \"%s\"" % self.file_path)

            try:
                a = APK(self.file_path)
                if a.is_valid_APK():
                    manifest = {}
                    apkinfo["files"] = self._apk_files(a)
                    manifest["package"] = a.get_package()
                    # manifest["permissions"]=a.get_details_permissions_new()
                    manifest["main_activity"] = a.get_main_activity()
                    manifest["activities"] = a.get_activities()
                    manifest["services"] = a.get_services()
                    manifest["receivers"] = a.get_receivers()
                    # manifest["receivers_actions"]=a.get__extended_receivers()
                    manifest["providers"] = a.get_providers()
                    manifest["libraries"] = a.get_libraries()
                    apkinfo["manifest"] = manifest
                    # apkinfo["certificate"] = a.get_certificate()
                    static_calls = {}
                    if self.check_size(apkinfo["files"]):
                        vm = DalvikVMFormat(a.get_dex())
                        vmx = uVMAnalysis(vm)

                        static_calls["all_methods"] = self.get_methods(vmx)
                        static_calls["is_native_code"] = analysis.is_native_code(vmx)
                        static_calls["is_dynamic_code"] = analysis.is_dyn_code(vmx)
                        static_calls["is_reflection_code"] = analysis.is_reflection_code(vmx)

                        # static_calls["dynamic_method_calls"]= analysis.get_show_DynCode(vmx)
                        # static_calls["reflection_method_calls"]= analysis.get_show_ReflectionCode(vmx)
                        # static_calls["permissions_method_calls"]= analysis.get_show_Permissions(vmx)
                        # static_calls["crypto_method_calls"]= analysis.get_show_CryptoCode(vmx)
                        # static_calls["native_method_calls"]= analysis.get_show_NativeMethods(vmx)
                    else:
                        log.warning("Dex size bigger than: %s",
                                    self.options.decompilation_threshold)
                    apkinfo["static_method_calls"] = static_calls
            except (IOError, OSError, zipfile.BadZipfile) as e:
                raise CuckooProcessingError("Error opening file %s" % e)

        return apkinfo
示例#13
0
    def run(self):
        """Run androguard to extract static android information
                @return: list of static features
        """
        self.key = "apkinfo"
        apkinfo = {}

        if "file" not in self.task["category"] or not HAVE_ANDROGUARD:
            return

        f = File(self.task["target"])
        if f.get_name().endswith((".zip", ".apk")) or "zip" in f.get_type():
            if not os.path.exists(self.file_path):
                raise CuckooProcessingError(
                    "Sample file doesn't exist: \"%s\"" % self.file_path)

            try:
                a = APK(self.file_path)
                if a.is_valid_APK():
                    manifest = {}
                    apkinfo["files"] = self._apk_files(a)
                    manifest["package"] = a.get_package()
                    # manifest["permissions"]=a.get_details_permissions_new()
                    manifest["main_activity"] = a.get_main_activity()
                    manifest["activities"] = a.get_activities()
                    manifest["services"] = a.get_services()
                    manifest["receivers"] = a.get_receivers()
                    # manifest["receivers_actions"]=a.get__extended_receivers()
                    manifest["providers"] = a.get_providers()
                    manifest["libraries"] = a.get_libraries()
                    apkinfo["manifest"] = manifest
                    # apkinfo["certificate"] = a.get_certificate()
                    static_calls = {}
                    if self.check_size(apkinfo["files"]):
                        vm = DalvikVMFormat(a.get_dex())
                        vmx = uVMAnalysis(vm)

                        static_calls["all_methods"] = self.get_methods(vmx)
                        static_calls[
                            "is_native_code"] = analysis.is_native_code(vmx)
                        static_calls["is_dynamic_code"] = analysis.is_dyn_code(
                            vmx)
                        static_calls[
                            "is_reflection_code"] = analysis.is_reflection_code(
                                vmx)

                        # static_calls["dynamic_method_calls"]= analysis.get_show_DynCode(vmx)
                        # static_calls["reflection_method_calls"]= analysis.get_show_ReflectionCode(vmx)
                        # static_calls["permissions_method_calls"]= analysis.get_show_Permissions(vmx)
                        # static_calls["crypto_method_calls"]= analysis.get_show_CryptoCode(vmx)
                        # static_calls["native_method_calls"]= analysis.get_show_NativeMethods(vmx)
                    else:
                        log.warning("Dex size bigger than: %s",
                                    self.options.decompilation_threshold)
                    apkinfo["static_method_calls"] = static_calls
            except (IOError, OSError, BadZipfile) as e:
                raise CuckooProcessingError("Error opening file %s" % e)

        return apkinfo
示例#14
0
 def __init__(self, name):
     vm = AndroguardS(name).get_vm()
     vma = analysis.uVMAnalysis(vm)
     self.classes = {
         dvclass.get_name(): DvClass(dvclass, vma)
         for dvclass in vm.get_classes()
     }
     util.merge_inner(self.classes)
示例#15
0
    def run_find_mapping(self):
        """
        Map permissions to API calls with the analyzed
        bytecode
        """

        # APIMappings enum
        # structure
        #
        enums = APIMappings()

        # VM analysis
        # object
        #
        x = analysis.uVMAnalysis(self.apks.get_vm())

        for permission in self.apk.get_permissions():
            for a, b in enums.mappings.items():
                for c, d in b.items():
                    if "permission" in c:
                        if permission == d:
                            print(
                                t.green(
                                    "[{0}] ".format(datetime.now()) +
                                    t.yellow("Found permission mapping : ") +
                                    permission))

                            if b.get("class"):
                                for e, f in b.get("class").items():
                                    print(
                                        t.green(
                                            "[{0}] ".format(datetime.now()) +
                                            t.yellow("Searching for : ") + e))

                                    if f.get("method"):
                                        self.run_search_method(
                                            self.apks, x, e, f.get("method"))

                                    elif f.get("methods"):
                                        for method in f.get("methods"):
                                            self.run_search_method(
                                                self.apks, x, e, method)

                            elif b.get("classes"):
                                for g, h in b.get("classes").items():
                                    print(
                                        t.green(
                                            "[{0}] ".format(datetime.now()) +
                                            t.yellow("Searching for : ") + g))

                                    if h.get("method"):
                                        self.run_search_method(
                                            self.apks, x, g, h.get("method"))

                                    elif h.get("methods"):
                                        for method in h.get("methods"):
                                            self.run_search_method(
                                                self.apks, x, g, method)
def extract_permissions(file):
    a = APK(file)
    d = DalvikVMFormat(a.get_dex())
    dx = VMAnalysis(d)
    vm = dvm.DalvikVMFormat(a.get_dex())
    vmx = analysis.uVMAnalysis(vm)
    d.set_vmanalysis(dx)
    d.set_decompiler(DecompilerDAD(d, dx))
    return a.get_permissions() 
示例#17
0
    def create_adex(self, log, dexobj):
        """
      This method is called in order to create a VMAnalysis object

      :param log: an object which corresponds to a unique app
      :param dexobj: a :class:`DalvikVMFormat` object

      :rytpe: a :class:`VMAnalysis` object
    """
        return analysis.uVMAnalysis(dexobj)
示例#18
0
    def with_dex(self, dex_file):
        """
              @param dex_file : a buffer

              @rtype : return the risk of the dex file (from 0.0 to 100.0)
        """
        d = dvm.DalvikVMFormat(dex_file)
        dx = analysis.uVMAnalysis(d)

        return self.with_dex_direct(d, dx)
示例#19
0
  def create_adex(self, log, dexobj):
    """
      This method is called in order to create a VMAnalysis object

      :param log: an object which corresponds to a unique app
      :param dexobj: a :class:`DalvikVMFormat` object

      :rytpe: a :class:`VMAnalysis` object
    """
    return analysis.uVMAnalysis(dexobj)
示例#20
0
    def analyze(self):
        self.__a = analysis.uVMAnalysis( self.__bc )
        self.__bc.set_vmanalysis( self.__a )

        self.__g = ganalysis.GVMAnalysis( self.__a, None )

        self.__bc.set_gvmanalysis( self.__g )

        self.__bc.create_xref()
        self.__bc.create_dref()
示例#21
0
文件: risk.py 项目: hetykai/works
    def with_dex(self, dex_file):
        """
            @param dex_file : a buffer

            @rtype : return the risk of the dex file (from 0.0 to 100.0)
      """
        d = dvm.DalvikVMFormat(dex_file)
        dx = analysis.uVMAnalysis(d)

        return self.with_dex_direct(d, dx)
示例#22
0
    def analyze(self) :
        self.__a = analysis.uVMAnalysis( self.__bc )
        self.__bc.set_vmanalysis( self.__a )

        self.__g = ganalysis.GVMAnalysis( self.__a, None )

        self.__bc.set_gvmanalysis( self.__g )

        self.__bc.create_xref()
        self.__bc.create_dref()
示例#23
0
    def do_build_apk_report(self, a):
        output = StringIO()

        a.get_files_types()

        output.write("[FILES] \n")
        for i in a.get_files():
            try: 
                output.write("\t%s %s %x\n" % (i, a.files[i], a.files_crc32[i], ))
            except KeyError:
                output.write("\t%s %x\n" % (i, a.files_crc32[i], ))

        output.write("\n[PERMISSIONS] \n")
        details_permissions = a.get_details_permissions()
        for i in details_permissions:
            output.write("\t%s %s\n" % (i, details_permissions[i], ))

        output.write("\n[MAIN ACTIVITY]\n\t%s\n" % (a.get_main_activity(), ))

        output.write("\n[ACTIVITIES] \n")
        activities = a.get_activities()
        for i in activities:
            filters = a.get_intent_filters("activity", i)
            output.write("\t%s %s\n" % (i, filters or "", ))

        output.write("\n[SERVICES] \n")
        services = a.get_services()
        for i in services:
            filters = a.get_intent_filters("service", i)
            output.write("\t%s %s\n" % (i, filters or "", ))

        output.write("\n[RECEIVERS] \n")
        receivers = a.get_receivers()
        for i in receivers:
            filters = a.get_intent_filters("receiver", i)
            output.write("\t%s %s\n" % (i, filters or "", ))

        output.write("\n[PROVIDERS]\n\t%s\n\n" % (a.get_providers(), ))

        vm  = dvm.DalvikVMFormat(a.get_dex())
        vmx = analysis.uVMAnalysis(vm)

        output.write("Native code      : %s\n"   % (analysis.is_native_code(vmx), ))
        output.write("Dynamic code     : %s\n"   % (analysis.is_dyn_code(vmx), ))
        output.write("Reflection code  : %s\n"   % (analysis.is_reflection_code(vmx), ))
        output.write("ASCII Obfuscation: %s\n\n" % (analysis.is_ascii_obfuscation(vm), ))

        for i in vmx.get_methods():
            i.create_tags()
            if not i.tags.empty():
                output.write("%s %s %s\n" % (i.method.get_class_name(),
                                             i.method.get_name(),
                                             i.tags, ))

        return output
示例#24
0
    def do_build_apk_report(self, a):
        output = StringIO()

        a.get_files_types()

        output.write("[FILES] \n")
        for i in a.get_files():
            try:
                output.write("\t%s %s %x\n" % (i, a.files[i], a.files_crc32[i], ))
            except KeyError:
                output.write("\t%s %x\n" % (i, a.files_crc32[i], ))

        output.write("\n[PERMISSIONS] \n")
        details_permissions = a.get_details_permissions()
        for i in details_permissions:
            output.write("\t%s %s\n" % (i, details_permissions[i], ))

        output.write("\n[MAIN ACTIVITY]\n\t%s\n" % (a.get_main_activity(), ))

        output.write("\n[ACTIVITIES] \n")
        activities = a.get_activities()
        for i in activities:
            filters = a.get_intent_filters("activity", i)
            output.write("\t%s %s\n" % (i, filters or "", ))

        output.write("\n[SERVICES] \n")
        services = a.get_services()
        for i in services:
            filters = a.get_intent_filters("service", i)
            output.write("\t%s %s\n" % (i, filters or "", ))

        output.write("\n[RECEIVERS] \n")
        receivers = a.get_receivers()
        for i in receivers:
            filters = a.get_intent_filters("receiver", i)
            output.write("\t%s %s\n" % (i, filters or "", ))

        output.write("\n[PROVIDERS]\n\t%s\n\n" % (a.get_providers(), ))

        vm  = dvm.DalvikVMFormat(a.get_dex())
        vmx = analysis.uVMAnalysis(vm)

        output.write("Native code      : %s\n"   % (analysis.is_native_code(vmx), ))
        output.write("Dynamic code     : %s\n"   % (analysis.is_dyn_code(vmx), ))
        output.write("Reflection code  : %s\n"   % (analysis.is_reflection_code(vmx), ))
        output.write("ASCII Obfuscation: %s\n\n" % (analysis.is_ascii_obfuscation(vm), ))

        for i in vmx.get_methods():
            i.create_tags()
            if not i.tags.empty():
                output.write("%s %s %s\n" % (i.method.get_class_name(),
                                             i.method.get_name(),
                                             i.tags, ))

        return output
示例#25
0
def display_dvm_info(apk):
    vm = dvm.DalvikVMFormat(apk.get_dex())
    vmx = analysis.uVMAnalysis(vm)

    print "Native code:", analysis.is_native_code(vmx)
    print "Dynamic code:", analysis.is_dyn_code(vmx)
    print "Reflection code:", analysis.is_reflection_code(vmx)

    for i in vmx.get_methods():
        i.create_tags()
        if not i.tags.empty():
            print i.method.get_class_name(), i.method.get_name(), i.tags
示例#26
0
def display_dvm_info(apk) :
    vm = dvm.DalvikVMFormat( apk.get_dex() )
    vmx = analysis.uVMAnalysis( vm )

    print "Native code:", analysis.is_native_code(vmx)
    print "Dynamic code:", analysis.is_dyn_code(vmx)
    print "Reflection code:", analysis.is_reflection_code(vmx)

    for i in vmx.get_methods() :
      i.create_tags()
      if not i.tags.empty() :
        print i.method.get_class_name(), i.method.get_name(), i.tags
示例#27
0
    def run_find_mapping(self):

        """
        Map permissions to API calls with the analyzed
        bytecode
        """

        # APIMappings enum
        # structure
        #
        enums = APIMappings()

        # VM analysis
        # object
        #
        x = analysis.uVMAnalysis(self.apks.get_vm())

        for permission in self.apk.get_permissions():
            for a, b in enums.mappings.items():
                for c, d in b.items():
                    if "permission" in c:
                        if permission == d:
                            print(t.green("[{0}] ".format(datetime.now()) +
                                          t.yellow("Found permission mapping : ") +
                                          permission))

                            if b.get("class"):
                                for e, f in b.get("class").items():
                                    print(t.green("[{0}] ".format(datetime.now()) +
                                          t.yellow("Searching for : ") +
                                          e))

                                    if f.get("method"):
                                        self.run_search_method(self.apks, x, e, f.get("method"))

                                    elif f.get("methods"):
                                        for method in f.get("methods"):
                                            self.run_search_method(self.apks, x, e, method)

                            elif b.get("classes"):
                                for g, h in b.get("classes").items():
                                    print(t.green("[{0}] ".format(datetime.now()) +
                                          t.yellow("Searching for : ") +
                                          g))

                                    if h.get("method"):
                                        self.run_search_method(self.apks, x, g, h.get("method"))

                                    elif h.get("methods"):
                                        for method in h.get("methods"):
                                            self.run_search_method(self.apks, x, g, method)
示例#28
0
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()
示例#29
0
def extract_method_calls(apk):
	vm = dvm.DalvikVMFormat(apk.get_dex())
	vmx = analysis.uVMAnalysis(vm)
	vmu = analysis.VMAnalysis(vm)
	apis=dict()
	for i in vmx.get_methods():
		i.create_tags()
		cla=i.method.get_class_name()
		met=i.method.get_name()
		tags = i.tags
		cla = string.replace(cla[1:len(cla)-2], "/", ".")
		k=cla+"."+met
		apis[k]=tags
		ist = i.method.get_instructions()
		print k
		for inst in ist:
			print "\t", inst.get_name(), inst.get_output()	
	return dict()
示例#30
0
文件: crypto.py 项目: ye-man/lobotomy
    def run(self):
        """
        Search for crypto API usage within target class and methods
        """

        x = analysis.uVMAnalysis(self.apks.get_vm())
        vm = self.apks.get_vm()

        if x:
            print(
                t.green("[{0}] ".format(datetime.now()) +
                        t.yellow("Performing surgery ...")))
            # Get enum values
            #
            for a, b in self.enum.values.items():
                for c in b:
                    paths = x.get_tainted_packages().search_methods(
                        "{0}".format(a), "{0}".format(c), ".")
                    if paths:
                        for p in paths:
                            for method in self.apks.get_methods():
                                if method.get_name() == p.get_src(
                                        vm.get_class_manager())[1]:
                                    if method.get_class_name() == p.get_src(
                                            vm.get_class_manager())[0]:
                                        print(
                                            t.green("[{0}] ".format(
                                                datetime.now()) +
                                                    t.yellow("Found: ") +
                                                    "{0}".format(c)))
                                        print(
                                            t.green(
                                                "[{0}] ".format(datetime.now())
                                                + t.yellow("Class: ") +
                                                "{0}".format(
                                                    method.get_class_name())))
                                        print(
                                            t.green("[{0}] ".format(
                                                datetime.now()) +
                                                    t.yellow("Method: ") +
                                                    "{0}".format(
                                                        method.get_name())))
                                        print(method.show())
示例#31
0
    def run(self):

        """
        Search for storage API usage within target class and methods
        """

        x = analysis.uVMAnalysis(self.apks.get_vm())
        vm = self.apks.get_vm()

        if x:
            print(t.green("[{0}] ".format(datetime.now()) + t.yellow("Performing surgery ...")))
            # Get enum values
            #
            for v in self.enum.values:
                # This returns PathP
                # objects into a list
                #
                paths = x.get_tainted_packages().search_methods("android.content.Context", "{0}".format(v), ".")

                if paths:
                    for p in paths:
                        for method in self.apks.get_methods():
                            if method.get_name() == p.get_src(vm.get_class_manager())[1]:
                                if method.get_class_name() == p.get_src(vm.get_class_manager())[0]:
                                    print(
                                        t.green("[{0}] ".format(datetime.now()) + t.yellow("Found: ") + "{0}".format(v))
                                    )
                                    print(
                                        t.green(
                                            "[{0}] ".format(datetime.now())
                                            + t.yellow("Class: ")
                                            + "{0}".format(method.get_class_name())
                                        )
                                    )
                                    print(
                                        t.green(
                                            "[{0}] ".format(datetime.now())
                                            + t.yellow("Method: ")
                                            + "{0}".format(method.get_name())
                                        )
                                    )
                                    print(method.show())
示例#32
0
文件: wrapper.py 项目: 0xr0ot/bowser
def main(apk):

    """
    Handle APK analysis
    """

    try:
        # Perform analysis on target APK
        print(t.yellow("[{0}] Performing analysis ...".format(datetime.datetime.now())))
        a, apks, dx = APK(apk), AndroguardS(apk), analysis.uVMAnalysis(DVM.DalvikVMFormat(APK(apk).get_dex()))

        # Validate the returned objects
        if a and apks and dx:
            print(t.yellow("[{0}] Analysis successful!".format(datetime.datetime.now())))
            # Call search function
            search(apks, dx)
        else:
            print(t.yellow("[{0}] Analysis failed!".format(datetime.datetime.now())))
    except zipfile.BadZipfile:
        print(t.yellow("[{0}] Bad APK file!".format(datetime.datetime.now())))
示例#33
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)))
示例#34
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)))
示例#35
0
文件: ipc.py 项目: nnn7h/lobotomy
    def run(self):

        x = analysis.uVMAnalysis(self.apks.get_vm())
        vm = self.apks.get_vm()

        selections = ["activity", "intent", "receiver", "context", "service"]

        print(t.green("[{0}] ".format(datetime.now()) +
                      t.yellow("Available selections: ")))

        for s in selections:
            print(t.green("[{0}] ".format(datetime.now())) + "{0}".format(s))

        selection = raw_input(t.green("[{0}] ".format(datetime.now()) + t.yellow("Enter selection: ")))

        for a, b in self.enum.values.items():
            if selection in a.lower():
                for c in b:
                    paths = x.get_tainted_packages().search_methods("{0}".format(a), "{0}".format(c), ".")
                    if paths:
                        for p in paths:
                            for method in self.apks.get_methods():
                                if method.get_name() == p.get_src(vm.get_class_manager())[1]:
                                    if method.get_class_name() == p.get_src(vm.get_class_manager())[0]:

                                        mx = x.get_method(method)
                                        d = decompile.DvMethod(mx)
                                        d.process()

                                        print(t.green("[{0}] ".format(datetime.now()) +
                                              t.yellow("Found: ") +
                                              "{0}".format(c)))
                                        print(t.green("[{0}] ".format(datetime.now()) +
                                                      t.yellow("Class: ") +
                                                      "{0}".format(method.get_class_name())))
                                        print(t.green("[{0}] ".format(datetime.now()) +
                                                      t.yellow("Method: ") +
                                                      "{0}".format(method.get_name())))

                                        print(method.show())
                                        print(d.get_source())
示例#36
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"
示例#37
0
    def loadedApk(self, success):
        self.sample_dialog.close()
        if not success:
            self.__logger.log(Logger.ERROR,"Analysis of %s failed :(" % str(self.fileLoadingThread.file_path))
            self.set_loading_progressbar_disabled()
            return

        self.d = self.session.get_DalvikForm()
        self.d.create_python_export()
        self.x = uVMAnalysis(self.d)

        self.setupTree()
        self.setupResourceController()
        self.load_app_info_table()
        self.load_permissions()
        try:
            self.__logger.log(Logger.INFO,"Analysis of %s done!" % str(self.apk.get_app_name()))
            self.ui.loadedAPK_label.setText("Loaded: "+str(self.apk.get_app_name()))
        except UnicodeEncodeError:
            self.ui.loadedAPK_label.setText("APK Loaded! (non-ascii chars detected)")
            self.__logger.log(Logger.WARNING,"Non ascii code characters detected, some strings are possibly not displayed properly.")
        self.set_loading_progressbar_disabled()
示例#38
0
    def run_bowser(self):

        """
        Run the bowser toolkit
        """

        # Search for parseUri()
        #
        x = analysis.uVMAnalysis(self.apks.get_vm())

        if x:
            print(t.green("[{0}] ".format(datetime.now()) +
                          t.yellow("Searching for parseUri()")))
            analysis.show_Paths(self.apks, x.get_tainted_packages().search_methods(".", "parseUri", "."))

            print(t.green("[{0}] ".format(datetime.now()) +
                          t.yellow("Searching for loadUrl()")))
            analysis.show_Paths(self.apks, x.get_tainted_packages().search_methods(".", "loadUrl", "."))

            print(t.green("[{0}] ".format(datetime.now()) +
                          t.yellow("Searching for addJavascriptInterface()")))
            analysis.show_Paths(self.apks, x.get_tainted_packages().search_methods(".", "addJavascriptInterface", "."))
示例#39
0
文件: socket.py 项目: nnn7h/lobotomy
    def run(self):

        """
        Search for socket service API implemenations
        """

        x = analysis.uVMAnalysis(self.apks.get_vm())
        vm = self.apks.get_vm()

        if x:
            print(t.green("[{0}] ".format(datetime.now()) + t.yellow("Performing surgery ...")))
            # Get enum values
            #
            for a, b in self.enum.values.items():
                for c in b:
                    paths = x.get_tainted_packages().search_methods("{0}".format(a), "{0}".format(c), ".")
                    if paths:
                        for p in paths:
                            for method in self.apks.get_methods():
                                if method.get_name() == p.get_src(vm.get_class_manager())[1]:
                                    if method.get_class_name() == p.get_src(vm.get_class_manager())[0]:

                                        mx = x.get_method(method)
                                        d = decompile.DvMethod(mx)
                                        d.process()

                                        print(t.green("[{0}] ".format(datetime.now()) +
                                              t.yellow("Found: ") +
                                              "{0}".format(c)))
                                        print(t.green("[{0}] ".format(datetime.now()) +
                                                      t.yellow("Class: ") +
                                                      "{0}".format(method.get_class_name())))
                                        print(t.green("[{0}] ".format(datetime.now()) +
                                                      t.yellow("Method: ") +
                                                      "{0}".format(method.get_name())))

                                        print(method.show())
                                        print(d.get_source())
示例#40
0
import sys

PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL)
from androguard.core.bytecodes import dvm
from androguard.core.bytecodes import apk
from androguard.core.androconf import CONF
from androguard.core.analysis import analysis, ganalysis

#CONF["LAZY_ANALYSIS"] = True

TEST = "examples/android/TestsAndroguard/bin/TestsAndroguard.apk"

a = apk.APK(TEST)
j = dvm.DalvikVMFormat(a.get_dex())
dx = analysis.uVMAnalysis(j)
gx = ganalysis.GVMAnalysis(dx, None)

j.set_vmanalysis(dx)
j.set_gvmanalysis(gx)

j.create_xref()
j.create_dref()

for m in dx.get_methods():
    idx = 0
    for i in m.basic_blocks.get():
        print("\t %s %x %x" % (i.name, i.start, i.end
                          ), i.get_instructions()[-1].get_name())

    print(m.method.XREFfrom, m.method.XREFto)
            # write app infomation
            fileUtils.write_app_info_to_file(appName, file_obj);
            fileUtils.write_app_activities_to_file(appName, file_obj);
            fileUtils.write_app_permissions_to_file(appName, file_obj);
            fileUtils.write_all_permissions_to_file(appName, file_obj);
            fileUtils.write_permissions_analysis_to_file(appName, file_obj);
            fileUtils.write_sensitive_apis_to_file(appName, file_obj);
            file_obj.close()


# -- comment -- create database with name is the name of the input file --
#createDatabase(analysis_init_default_value.APP_NAME)

a = AndroguardS( TEST )

x = analysis.uVMAnalysis( a.get_vm() )
#print a.get_vm().get_strings()

print a.get_vm().get_regex_strings( "access" )
print a.get_vm().get_regex_strings( "(long).*2" )
print a.get_vm().get_regex_strings( ".*(t\_t).*" )

classes = a.get_vm().get_classes_names()
vm = a.get_vm()

display_STRINGS( vm, x, classes )
#display_PERMISSION( vm, x, classes )
#display_PACKAGES( vm, x, classes )

# --- comment: This function cannot run if no activities have define in db
#display_Activities()
示例#42
0
    def run(self):
        """
        Search for SSLSocket and TrustManager API usage within target class and methods
        """

        if self.vm_type == "apks":
            # Get the DVM analysis object from Androguard
            x = analysis.uVMAnalysis(self.vm.get_vm())
            _vm = self.vm.get_vm()
            _structure = list()

            if x:
                print(
                    t.green("[{0}] ".format(datetime.now()) +
                            t.yellow("Performing surgery ...")))
                for a, b in self.enum.values.items():
                    for c in b:
                        paths = x.get_tainted_packages().search_methods(
                            "{0}".format(a), "{0}".format(c), ".")
                        if paths:
                            for p in paths:
                                for method in self.vm.get_methods():
                                    if method.get_name() == p.get_src(
                                            _vm.get_class_manager())[1]:
                                        if method.get_class_name(
                                        ) == p.get_src(
                                                _vm.get_class_manager())[0]:
                                            # Start decompilation process for each method
                                            mx = x.get_method(method)
                                            d = decompile.DvMethod(mx)
                                            d.process()
                                            _structure.append((c, method, d))
            # Iterate through the generated methods and
            # create a unique set
            methods = [s[0] for s in _structure]
            methods_set = set(methods)

            for m in methods_set:
                print(
                    t.green("[{0}] ".format(datetime.now()) +
                            t.yellow("Available ssl methods: ") +
                            "{0}".format(m)))

            print(
                t.green("[{0}] ".format(datetime.now()) +
                        t.yellow("Enter \'back\' to exit")))

            print(
                t.green(
                    "[{0}] ".format(datetime.now()) +
                    t.yellow("Enter \'list\' to show available functions")))

            while True:
                # Selected target method
                method = raw_input(
                    t.green("[{0}] ".format(datetime.now()) +
                            t.yellow("Enter method selection: ")))

                for s in _structure:
                    if method == s[0]:
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Found: ") + "{0}".format(s[0])))
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Class: ") +
                                    "{0}".format(s[1].get_class_name())))
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Method: ") +
                                    "{0}".format(s[1].get_name())))
                        print(s[1].show())
                        print(s[2].get_source())
                        console.colorize_decompiled_method(
                            str(s[2].get_source()))

                if method == "back":
                    break
                elif method == "list":
                    for m in methods_set:
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Available ssl methods: ") +
                                    "{0}".format(m)))

        elif self.vm_type == "dex":

            x = analysis.uVMAnalysis(self.vm)
            _vm = self.vm
            _structure = list()

            if x:
                print(
                    t.green("[{0}] ".format(datetime.now()) +
                            t.yellow("Performing surgery ...")))
                for a, b in self.enum.values.items():
                    for c in b:
                        paths = x.get_tainted_packages().search_methods(
                            "{0}".format(a), "{0}".format(c), ".")
                        if paths:
                            for p in paths:
                                for method in self.vm.get_methods():
                                    if method.get_name() == p.get_src(
                                            _vm.get_class_manager())[1]:
                                        if method.get_class_name(
                                        ) == p.get_src(
                                                _vm.get_class_manager())[0]:
                                            # Start decompilation process for each method
                                            mx = x.get_method(method)
                                            d = decompile.DvMethod(mx)
                                            d.process()
                                            _structure.append((c, method, d))
            # Iterate through the generated methods and
            # create a unique set
            methods = [s[0] for s in _structure]
            methods_set = set(methods)

            for m in methods_set:
                print(
                    t.green("[{0}] ".format(datetime.now()) +
                            t.yellow("Available ssl methods: ") +
                            "{0}".format(m)))

            print(
                t.green("[{0}] ".format(datetime.now()) +
                        t.yellow("Enter \'back\' to exit")))

            print(
                t.green(
                    "[{0}] ".format(datetime.now()) +
                    t.yellow("Enter \'list\' to show available functions")))

            while True:
                # Selected target method
                method = raw_input(
                    t.green("[{0}] ".format(datetime.now()) +
                            t.yellow("Enter method selection: ")))

                for s in _structure:
                    if method == s[0]:
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Found: ") + "{0}".format(s[0])))
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Class: ") +
                                    "{0}".format(s[1].get_class_name())))
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Method: ") +
                                    "{0}".format(s[1].get_name())))
                        print(s[1].show())
                        console.colorize_decompiled_method(
                            str(s[2].get_source()))

                if method == "back":
                    break
                elif method == "list":
                    for m in methods_set:
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Available ssl methods: ") +
                                    "{0}".format(m)))
示例#43
0
import sys

PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL)
from androguard.core.bytecodes import dvm
from androguard.core.bytecodes import apk
from androguard.core.androconf import CONF
from androguard.core.analysis import analysis, ganalysis

#CONF["LAZY_ANALYSIS"] = True

TEST = "examples/android/TestsAndroguard/bin/TestsAndroguard.apk"

a = apk.APK(TEST)
j = dvm.DalvikVMFormat(a.get_dex())
dx = analysis.uVMAnalysis(j)
gx = ganalysis.GVMAnalysis(dx, None)

j.set_vmanalysis(dx)
j.set_gvmanalysis(gx)

j.create_xref()
j.create_dref()

for m in dx.get_methods():
    idx = 0
    for i in m.basic_blocks.get():
        print("\t %s %x %x" % (i.name, i.start, i.end),
              i.get_instructions()[-1].get_name())

    print(m.method.XREFfrom, m.method.XREFto)
示例#44
0
    def execute(self):
        AndroCommand.execute(self)
        
        if self.options.all_options:
            self.options.dynamic = True
            self.options.native = True
            self.options.obfuscation = True
            self.options.reflection = True
        
        dalvik_options= [self.options.dynamic, self.options.native, self.options.obfuscation, self.options.reflection]

        a = apk.APK(self.options.apk, zipmodule=2)

        if not a.is_valid_APK():
            sys.stderr.write("Not a valid APK file.")
            exit(1)

        if not any(dalvik_options):
            sys.stderr.write("No output option selected.")
            exit(1)
            

        # create a session, get the underlying app and use a transaction to update 
        # the values
        session = self.db.session()

        try:
            app = session.query(App).filter(App.id==self.options.index).first()

            if not app:
                sys.stderr.write("Could not find app by index.")
                exit(1)

            #print 'Doing vm analysis'
            dex = a.get_dex()
            vm = dvm.DalvikVMFormat(dex)
            vmx = analysis.uVMAnalysis(vm)

            if self.options.dynamic:
                print 'Checking if application uses dynamic code...'
                app.dynamic = analysis.is_dyn_code(vmx)
                session.flush()

            if self.options.native:
                print 'Checking if application uses native code...'
                app.native = analysis.is_native_code(vmx)
                session.flush()

            # androguard 1.9 no longer supports this
            """
            if self.options.obfuscation:
                print 'Checking if application uses obfuscation...'
                app.obfuscation = analysis.is_ascii_obfuscation(vm)
                session.flush()
            """

            if self.options.reflection:
                print 'Checking if application uses reflection...'
                app.reflection = analysis.is_reflection_code(vmx)
                session.flush()

            session.commit()
            print 'Success'
        except:
            session.rollback()
            exit(1)

        exit(0)
示例#45
0
文件: ag.py 项目: 0x0mar/androguard
    def run(self):
        if androconf.is_android_raw(self.raw) == "DEY":
            dex_object = dvm.DalvikOdexVMFormat(self.raw)
        else:
            dex_object = dvm.DalvikVMFormat(self.raw)

        ana_object = analysis.uVMAnalysis(dex_object)
        gvm_object = ganalysis.GVMAnalysis(ana_object, None)

        dex_object.set_vmanalysis(ana_object)
        dex_object.set_gvmanalysis(gvm_object)

        for i in androconf.CONF:
            if is_setting(i):
                androconf.CONF[i] = get_setting(i)

        decompiler_option = get_setting("DEFAULT_DECOMPILER", "dad")

        if decompiler_option == "dex2jad":
            dex_object.set_decompiler(decompiler.DecompilerDex2Jad(
                dex_object,
                androconf.CONF["PATH_DEX2JAR"],
                androconf.CONF["BIN_DEX2JAR"],
                androconf.CONF["PATH_JAD"],
                androconf.CONF["BIN_JAD"],
                androconf.CONF["TMP_DIRECTORY"]))
        elif decompiler_option == "ded":
            dex_object.set_decompiler(decompiler.DecompilerDed(
                dex_object,
                androconf.CONF["PATH_DED"],
                androconf.CONF["BIN_DED"],
                androconf.CONF["TMP_DIRECTORY"]))
        else:
            dex_object.set_decompiler(decompiler.DecompilerDAD(dex_object, ana_object))

        dex_object.create_xref()
        dex_object.create_dref()

        self.view.set_name("%s.ag" % (self.filename))

        self.view.set_scratch(True)
        edit = self.view.begin_edit()
        self.view.sel().clear()
        self.view.set_syntax_file("Packages/ag-st/ag.tmLanguage")

        by_package = {}
        for current_class in dex_object.get_classes():
          name = current_class.get_name()

          try:
            by_package[os.path.dirname(name)].append(current_class)
          except KeyError:
            by_package[os.path.dirname(name)] = []
            by_package[os.path.dirname(name)].append(current_class)

        b_buffer = ""
        line = 0

        AG_METHODS_LINE[self.view.id()] = {}
        AG_CLASSES_LINE[self.view.id()] = {}
        AG_FIELDS_LINE[self.view.id()] = {}
        for key in sorted(by_package.iterkeys()):
            b_buffer += "%s\n" % key
            line += 1

            for c_class in sorted(by_package[key], key=lambda k: k.get_name()):
                b_buffer += "\t%s extends %s\n" % (c_class.get_name()[1:-1], c_class.get_superclassname()[1:-1])
                AG_CLASSES_LINE[self.view.id()][line] = c_class
                line += 1

                for j in c_class.get_methods():
                    b_buffer += "\t\tmethod: %s %s [%s] size:%d\n" % (j.get_name(), j.get_descriptor(), j.get_access_flags_string(), j.get_length())
                    AG_METHODS_LINE[self.view.id()][line] = j
                    line += 1

                b_buffer += "\n"
                line += 1

                for j in c_class.get_fields():
                    b_buffer += "\t\tfield: %s %s [%s %s]" % (j.get_name(), j.get_descriptor(), j.get_access_flags_string(), dvm.get_type(j.get_descriptor()))

                    init_value = j.get_init_value()
                    if init_value != None:
                        b_buffer += " (%s)" % repr(str(init_value.get_value()))
                    b_buffer += "\n"

                    AG_FIELDS_LINE[self.view.id()][line] = j
                    line += 1

                b_buffer += "\n"
                line += 1

        l = dex_object.print_classes_hierarchy()
        h_buffer = ""
        for i in l:
            h_buffer += i + "\n"

        b_buffer += h_buffer

        self.view.replace(edit, sublime.Region(0, self.view.size()), b_buffer)
        self.view.end_edit(edit)
        self.view.set_read_only(True)
        AG_DEX_VIEW[self.view.id()] = (dex_object, ana_object)
        FILENAMES[self.view.id()] = hashlib.sha1(dex_object.get_buff()).hexdigest()
 def analyze(self) :
     self.__a = analysis.uVMAnalysis( self.__bc )
     self.__bc.set_vmanalysis( self.__a )
示例#47
0
文件: dad_emul.py 项目: adrooy/works
        arg1 = arg1.visit(self)
        if not isinstance(arg1, int):
            arg1 = ord(arg1)
        arg2 = arg2.visit(self)
        if not isinstance(arg2, int):
            arg2 = ord(arg2)
        return eval('%s %s %s' % (arg1, op, arg2))

    def visit_get_static(self, cls, name):
        return self.mem[name]


TEST = './apks/pacsec/magicspiral.apk'

vm = dvm.DalvikVMFormat(apk.APK(TEST).get_dex())
vma = uVMAnalysis(vm)

method = vm.get_method('crypt')[0]

amethod = vma.get_method(method)
dvmethod = DvMethod(amethod)
dvmethod.process()  # build IR Form / control flow...

graph = dvmethod.graph
visitor = DemoEmulator(graph)

l = [94, 42, 93, 88, 3, 2, 95, 2, 13, 85, 11, 2, 19, 1, 125, 19, 0, 102,
     30, 24, 19, 99, 76, 21, 102, 22, 26, 111, 39, 125, 2, 44, 80, 10, 90,
     5, 119, 100, 119, 60, 4, 87, 79, 42, 52]
visitor.init(dvmethod.lparams[0], l)
示例#48
0
 def __init__(self, name):
     vm = AndroguardS(name).get_vm()
     vma = analysis.uVMAnalysis(vm)
     self.classes = {dvclass.get_name(): DvClass(dvclass, vma)
                                     for dvclass in vm.get_classes()}
     util.merge_inner(self.classes)
示例#49
0
    def run(self):
        if androconf.is_android_raw(self.raw) == "DEY":
            dex_object = dvm.DalvikOdexVMFormat(self.raw)
        else:
            dex_object = dvm.DalvikVMFormat(self.raw)

        ana_object = analysis.uVMAnalysis(dex_object)
        gvm_object = ganalysis.GVMAnalysis(ana_object, None)

        dex_object.set_vmanalysis(ana_object)
        dex_object.set_gvmanalysis(gvm_object)

        for i in androconf.CONF:
            if is_setting(i):
                androconf.CONF[i] = get_setting(i)

        decompiler_option = get_setting("DEFAULT_DECOMPILER", "dad")

        if decompiler_option == "dex2jad":
            dex_object.set_decompiler(
                decompiler.DecompilerDex2Jad(dex_object,
                                             androconf.CONF["PATH_DEX2JAR"],
                                             androconf.CONF["BIN_DEX2JAR"],
                                             androconf.CONF["PATH_JAD"],
                                             androconf.CONF["BIN_JAD"],
                                             androconf.CONF["TMP_DIRECTORY"]))
        elif decompiler_option == "ded":
            dex_object.set_decompiler(
                decompiler.DecompilerDed(dex_object,
                                         androconf.CONF["PATH_DED"],
                                         androconf.CONF["BIN_DED"],
                                         androconf.CONF["TMP_DIRECTORY"]))
        else:
            dex_object.set_decompiler(
                decompiler.DecompilerDAD(dex_object, ana_object))

        dex_object.create_xref()
        dex_object.create_dref()

        self.view.set_name("%s.ag" % (self.filename))

        self.view.set_scratch(True)
        edit = self.view.begin_edit()
        self.view.sel().clear()
        self.view.set_syntax_file("Packages/ag-st/ag.tmLanguage")

        by_package = {}
        for current_class in dex_object.get_classes():
            name = current_class.get_name()

            try:
                by_package[os.path.dirname(name)].append(current_class)
            except KeyError:
                by_package[os.path.dirname(name)] = []
                by_package[os.path.dirname(name)].append(current_class)

        b_buffer = ""
        line = 0

        AG_METHODS_LINE[self.view.id()] = {}
        AG_CLASSES_LINE[self.view.id()] = {}
        AG_FIELDS_LINE[self.view.id()] = {}
        for key in sorted(by_package.iterkeys()):
            b_buffer += "%s\n" % key
            line += 1

            for c_class in sorted(by_package[key], key=lambda k: k.get_name()):
                b_buffer += "\t%s extends %s\n" % (c_class.get_name(
                )[1:-1], c_class.get_superclassname()[1:-1])
                AG_CLASSES_LINE[self.view.id()][line] = c_class
                line += 1

                for j in c_class.get_methods():
                    b_buffer += "\t\tmethod: %s %s [%s] size:%d\n" % (
                        j.get_name(), j.get_descriptor(),
                        j.get_access_flags_string(), j.get_length())
                    AG_METHODS_LINE[self.view.id()][line] = j
                    line += 1

                b_buffer += "\n"
                line += 1

                for j in c_class.get_fields():
                    b_buffer += "\t\tfield: %s %s [%s %s]" % (
                        j.get_name(), j.get_descriptor(),
                        j.get_access_flags_string(),
                        dvm.get_type(j.get_descriptor()))

                    init_value = j.get_init_value()
                    if init_value != None:
                        b_buffer += " (%s)" % repr(str(init_value.get_value()))
                    b_buffer += "\n"

                    AG_FIELDS_LINE[self.view.id()][line] = j
                    line += 1

                b_buffer += "\n"
                line += 1

        l = dex_object.get_classes_hierarchy()
        h_buffer = ""
        for i in l:
            h_buffer += i + "\n"

        b_buffer += h_buffer

        self.view.replace(edit, sublime.Region(0, self.view.size()), b_buffer)
        self.view.end_edit(edit)
        self.view.set_read_only(True)
        AG_DEX_VIEW[self.view.id()] = (dex_object, ana_object)
        FILENAMES[self.view.id()] = hashlib.sha1(
            dex_object.get_buff()).hexdigest()
示例#50
0
文件: certkey.py 项目: xtxwy/lobotomy
    def run(self):
        """
        Search for CertificateManager and Keystore API usage within target class and methods
        """

        if self.vm_type == "apks":

            _x = analysis.uVMAnalysis(self.vm.get_vm())
            _vm = self.vm.get_vm()
            _structure = list()

            if _x:
                print(
                    t.green("[{0}] ".format(datetime.now()) +
                            t.yellow("Performing surgery ...")))
                for a, b in self.enum.values.items():
                    for c in b:
                        paths = _x.get_tainted_packages().search_methods(
                            "{0}".format(a), "{0}".format(c), ".")
                        if paths:
                            for p in paths:
                                for method in self.vm.get_methods():
                                    if method.get_name() == p.get_src(
                                            _vm.get_class_manager())[1]:
                                        if method.get_class_name(
                                        ) == p.get_src(
                                                _vm.get_class_manager())[0]:
                                            mx = _x.get_method(method)
                                            d = decompile.DvMethod(mx)
                                            d.process()
                                            _structure.append((c, method, d))

            methods = [s[0] for s in _structure]
            methods_set = set(methods)

            for m in methods_set:
                print(
                    t.green("[{0}] ".format(datetime.now()) +
                            t.yellow("Available certkey method: ") +
                            "{0}".format(m)))

            print(
                t.green("[{0}] ".format(datetime.now()) +
                        t.yellow("Enter \'back\' to exit")))
            print(
                t.green("[{0}] ".format(datetime.now()) +
                        t.yellow("Enter \'list\' to show available methods")))

            while True:
                method = raw_input(
                    t.green("[{0}] ".format(datetime.now()) +
                            t.yellow("Enter method selection: ")))

                for s in _structure:
                    if method == s[0]:
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Found: ") + "{0}".format(s[0])))
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Class: ") +
                                    "{0}".format(s[1].get_class_name())))
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Method: ") +
                                    "{0}".format(s[1].get_name())))
                        print(s[1].show())
                        console.colorize_decompiled_method(
                            str(s[2].get_source()))

                if method == "back":
                    break
                elif method == "list":
                    for m in methods_set:
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Available certkey method: ") +
                                    "{0}".format(m)))

        elif self.vm_type == "dex":

            _x = analysis.uVMAnalysis(self.vm)
            _vm = self.vm
            _structure = list()

            if _x:
                print(
                    t.green("[{0}] ".format(datetime.now()) +
                            t.yellow("Performing surgery ...")))
                for a, b in self.enum.values.items():
                    for c in b:
                        paths = _x.get_tainted_packages().search_methods(
                            "{0}".format(a), "{0}".format(c), ".")
                        if paths:
                            for p in paths:
                                for method in self.vm.get_methods():
                                    if method.get_name() == p.get_src(
                                            _vm.get_class_manager())[1]:
                                        if method.get_class_name(
                                        ) == p.get_src(
                                                _vm.get_class_manager())[0]:
                                            mx = _x.get_method(method)
                                            d = decompile.DvMethod(mx)
                                            d.process()
                                            _structure.append((c, method, d))

            methods = [s[0] for s in _structure]
            methods_set = set(methods)

            for m in methods_set:
                print(
                    t.green("[{0}] ".format(datetime.now()) +
                            t.yellow("Available certkey method: ") +
                            "{0}".format(m)))

            print(
                t.green("[{0}] ".format(datetime.now()) +
                        t.yellow("Enter \'back\' to exit")))
            print(
                t.green("[{0}] ".format(datetime.now()) +
                        t.yellow("Enter \'list\' to show available methods")))

            while True:
                method = raw_input(
                    t.green("[{0}] ".format(datetime.now()) +
                            t.yellow("Enter method selection: ")))

                for s in _structure:
                    if method == s[0]:
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Found: ") + "{0}".format(s[0])))
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Class: ") +
                                    "{0}".format(s[1].get_class_name())))
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Method: ") +
                                    "{0}".format(s[1].get_name())))
                        print(s[1].show())
                        console.colorize_decompiled_method(
                            str(s[2].get_source()))

                if method == "back":
                    break
                elif method == "list":
                    for m in methods_set:
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Available certkey method: ") +
                                    "{0}".format(m)))
示例#51
0
    def run(self):

        """
        Search for storage API usage within target class and methods
        """

        if self.vm_type == "apks":

            x = analysis.uVMAnalysis(self.vm.get_vm())
            _vm = self.vm.get_vm()
            _structure = list()

            if x:
                print(t.green("[{0}] ".format(datetime.now()) + t.yellow("Performing surgery ...")))
                for a, b in self.enum.values.items():
                    for c in b:
                        paths = x.get_tainted_packages().search_methods("{0}".format(b), "{0}".format(c), ".")
                        if paths:
                            for p in paths:
                                for method in self.vm.get_methods():
                                    if method.get_name() == p.get_src(_vm.get_class_manager())[1]:
                                        if method.get_class_name() == p.get_src(_vm.get_class_manager())[0]:

                                            mx = x.get_method(method)
                                            d = decompile.DvMethod(mx)
                                            d.process()
                                            _structure.append((c, method, d))

            methods = [s[0] for s in _structure]
            methods_set = set(methods)

            for m in methods_set:
                print(t.green("[{0}] ".format(datetime.now()) +
                              t.yellow("Available storage methods: ") + "{0}".format(m)))

            print(t.green("[{0}] ".format(datetime.now()) +
                          t.yellow("Enter \'back\' to exit")))

            print(t.green("[{0}] ".format(datetime.now()) +
                          t.yellow("Enter \'list\' to show available methods")))

            while True:

                method = raw_input(t.green("[{0}] ".format(datetime.now()) + t.yellow("Enter method selection: ")))

                for s in _structure:
                    if method == s[0]:
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Found: ") +
                                      "{0}".format(s[0])))
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Class: ") +
                                      "{0}".format(s[1].get_class_name())))
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Method: ") +
                                      "{0}".format(s[1].get_name())))
                        print(s[1].show())
                        console.colorize_decompiled_method(str(s[2].get_source()))

                if method == "back":
                    break
                elif method == "list":
                    for m in methods_set:
                        print(t.green("[{0}] ".format(datetime.now()) +
                              t.yellow("Available storage methods: ") + "{0}".format(m)))

        elif self.vm_type == "dex":

            x = analysis.uVMAnalysis(self.vm)
            _vm = self.vm
            _structure = list()

            if x:
                print(t.green("[{0}] ".format(datetime.now()) + t.yellow("Performing surgery ...")))
                for a, b in self.enum.values.items():
                    for c in b:
                        paths = x.get_tainted_packages().search_methods("{0}".format(a), "{0}".format(c), ".")
                        if paths:
                            for p in paths:
                                for method in self.vm.get_methods():
                                    if method.get_name() == p.get_src(_vm.get_class_manager())[1]:
                                        if method.get_class_name() == p.get_src(_vm.get_class_manager())[0]:

                                            mx = x.get_method(method)
                                            d = decompile.DvMethod(mx)
                                            d.process()
                                            _structure.append((c, method, d))

            methods = [s[0] for s in _structure]
            methods_set = set(methods)

            for m in methods_set:
                print(t.green("[{0}] ".format(datetime.now()) +
                              t.yellow("Available storage methods: ") + "{0}".format(m)))

            print(t.green("[{0}] ".format(datetime.now()) +
                          t.yellow("Enter \'back\' to exit")))

            print(t.green("[{0}] ".format(datetime.now()) +
                          t.yellow("Enter \'list\' to show available methods")))

            while True:

                method = raw_input(t.green("[{0}] ".format(datetime.now()) + t.yellow("Enter method selection: ")))

                for s in _structure:
                    if method == s[0]:
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Found: ") +
                                      "{0}".format(s[0])))
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Class: ") +
                                      "{0}".format(s[1].get_class_name())))
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Method: ") +
                                      "{0}".format(s[1].get_name())))
                        print(s[1].show())
                        console.colorize_decompiled_method(str(s[2].get_source()))

                if method == "back":
                    break
                elif method == "list":
                    for m in methods_set:
                        print(t.green("[{0}] ".format(datetime.now()) +
                              t.yellow("Available storage methods: ") + "{0}".format(m)))
示例#52
0
from androguard.core.androgen import AndroguardS

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

TEST_CASE  = "examples/android/TestsAndroguard/bin/classes.dex"

def test(got, expected):
    if got == expected:
        prefix = ' OK '
    else:
        prefix = '  X '
    print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected))


a = AndroguardS( TEST_CASE )
x = analysis.uVMAnalysis( a.get_vm() )

for method in a.get_methods() :
    print method.get_class_name(), method.get_name(), method.get_descriptor()
    print "-> : \t", x.get_method_signature(method, predef_sign = analysis.SIGNATURE_L0_0).get_string()
    print "-> : \t", x.get_method_signature(method, predef_sign = analysis.SIGNATURE_L0_1).get_string()
    print "-> : \t", x.get_method_signature(method, predef_sign = analysis.SIGNATURE_L0_2).get_string()
    print "-> : \t", x.get_method_signature(method, predef_sign = analysis.SIGNATURE_L0_3).get_string()
    print "-> : \t", x.get_method_signature(method, predef_sign = analysis.SIGNATURE_L0_4).get_string()
    print "-> : \t", x.get_method_signature(method, predef_sign = analysis.SIGNATURE_HEX).get_string()
    print "-> : \t", x.get_method_signature(method, predef_sign = analysis.SIGNATURE_SEQUENCE_BB).get_list()

    print
示例#53
0
    def run(self):

        """
        Search for IPC API usage within target class and methods
        """

        if self.vm_type == "apks":

            x = analysis.uVMAnalysis(self.vm.get_vm())
            _vm = self.vm.get_vm()

            selections = [

                "activity",
                "intent",
                "receiver",
                "context",
                "service"

            ]

            print(t.green("[{0}] ".format(datetime.now()) +
                          t.yellow("Available selections: ")))

            for s in selections:
                print(t.green("[{0}] ".format(datetime.now())) + "{0}".format(s))

            selection = raw_input(t.green("[{0}] ".format(datetime.now()) + t.yellow("Enter selection: ")))

            _structure = list()

            for a, b in self.enum.values.items():
                if selection in a.lower():
                    for c in b:
                        paths = x.get_tainted_packages().search_methods("{0}".format(a), "{0}".format(c), ".")
                        if paths:
                            for p in paths:
                                for method in self.vm.get_methods():
                                    if method.get_name() == p.get_src(_vm.get_class_manager())[1]:
                                        if method.get_class_name() == p.get_src(_vm.get_class_manager())[0]:
                                            mx = x.get_method(method)
                                            d = decompile.DvMethod(mx)
                                            d.process()
                                            _structure.append((c, method, d))

            methods = [s[0] for s in _structure]
            methods_set = set(methods)

            for m in methods_set:
                print(t.green("[{0}] ".format(datetime.now()) +
                              t.yellow("Available {0} methods: ".format(selection)) + "{0}".format(m)))

            print(t.green("[{0}] ".format(datetime.now()) +
                          t.yellow("Enter \'back\' to exit")))

            print(t.green("[{0}] ".format(datetime.now()) +
                          t.yellow("Enter \'list\' to show available methods")))

            while True:

                method = raw_input(t.green("[{0}] ".format(datetime.now()) + t.yellow("Enter method selection: ")))

                for s in _structure:
                    if method == s[0]:
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Found: ") +
                                      "{0}".format(s[0])))
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Class: ") +
                                      "{0}".format(s[1].get_class_name())))
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Method: ") +
                                      "{0}".format(s[1].get_name())))
                        print(s[1].show())
                        console.colorize_decompiled_method(str(s[2].get_source()))

                if method == "back":
                    break
                elif method == "list":
                    for m in methods_set:
                        print(t.green("[{0}] ".format(datetime.now()) +
                              t.yellow("Available {0} methods: ".format(selection)) + "{0}".format(m)))

        elif self.vm_type == "dex":

            x = analysis.uVMAnalysis(self.vm)
            _vm = self.vm
            _structure = list()

            selections = [

                "activity",
                "intent",
                "receiver",
                "context",
                "service"

            ]

            print(t.green("[{0}] ".format(datetime.now()) +
                          t.yellow("Available ipc selections: ")))

            for s in selections:
                print(t.green("[{0}] ".format(datetime.now())) + "{0}".format(s))

            selection = raw_input(t.green("[{0}] ".format(datetime.now()) + t.yellow("Enter selection: ")))

            for a, b in self.enum.values.items():
                if selection in a.lower():
                    for c in b:
                        paths = x.get_tainted_packages().search_methods("{0}".format(a), "{0}".format(c), ".")
                        if paths:
                            for p in paths:
                                for method in self.vm.get_methods():
                                    if method.get_name() == p.get_src(_vm.get_class_manager())[1]:
                                        if method.get_class_name() == p.get_src(_vm.get_class_manager())[0]:
                                            mx = x.get_method(method)
                                            d = decompile.DvMethod(mx)
                                            d.process()
                                            _structure.append((c, method, d))

            methods = [s[0] for s in _structure]
            methods_set = set(methods)

            for m in methods_set:
                print(t.green("[{0}] ".format(datetime.now()) +
                              t.yellow("Available {0} methods: ".format(selection)) + "{0}".format(m)))

            print(t.green("[{0}] ".format(datetime.now()) +
                          t.yellow("Enter \'back\' to exit")))

            print(t.green("[{0}] ".format(datetime.now()) +
                          t.yellow("Enter \'list\' to show available methods")))

            while True:

                method = raw_input(t.green("[{0}] ".format(datetime.now()) + t.yellow("Enter method selection: ")))

                for s in _structure:
                    if method == s[0]:
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Found: ") +
                                      "{0}".format(s[0])))
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Class: ") +
                                      "{0}".format(s[1].get_class_name())))
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Method: ") +
                                      "{0}".format(s[1].get_name())))
                        print(s[1].show())
                        console.colorize_decompiled_method(str(s[2].get_source()))

                if method == "back":
                    break
                elif method == "list":
                    for m in methods_set:
                        print(t.green("[{0}] ".format(datetime.now()) +
                              t.yellow("Available {0} methods: ".format(selection)) + "{0}".format(m)))
示例#54
0
    def run(self):

        """
        Search for Web Browser API usage within target class and methods
        """

        if self.vm_type == "apks":
            _x = analysis.uVMAnalysis(self.vm.get_vm())
            _vm = self.vm.get_vm()
            _structure = list()

            if _x:
                print(t.green("[{0}] ".format(datetime.now()) + t.yellow("Performing surgery ...")))
                for a, b in self.enum.values.items():
                    for c in b:
                        paths = _x.get_tainted_packages().search_methods("{0}".format(a), "{0}".format(c), ".")
                        if paths:
                            for p in paths:
                                for method in self.vm.get_methods():
                                    if method.get_name() == p.get_src(_vm.get_class_manager())[1]:
                                        if method.get_class_name() == p.get_src(_vm.get_class_manager())[0]:
                                            mx = _x.get_method(method)
                                            d = decompile.DvMethod(mx)
                                            try:
                                                d.process()
                                            except Exception as decompile_process_error:
                                                if decompile_process_error.message == \
                                                        "'Instruction31c' object has no attribute 'get_raw_string'":
                                                    pass
                                            _structure.append((c, method, d))

            methods = [s[0] for s in _structure]
            methods_set = set(methods)

            for m in methods_set:
                print(t.green("[{0}] ".format(datetime.now()) +
                              t.yellow("Available bowser method: ") + "{0}".format(m)))

            print(t.green("[{0}] ".format(datetime.now()) + t.yellow("Enter \'back\' to exit")))
            print(t.green("[{0}] ".format(datetime.now()) + t.yellow("Enter \'list\' to show available methods")))

            while True:
                method = raw_input(t.green("[{0}] ".format(datetime.now()) + t.yellow("Enter method selection: ")))
                for s in _structure:
                    if method == s[0]:
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Found: ") +
                                      "{0}".format(s[0])))
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Class: ") +
                                      "{0}".format(s[1].get_class_name())))
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Method: ") +
                                      "{0}".format(s[1].get_name())))

                        print("".join([s[1].get_class_name(), "->", s[1].get_name(),
                                       s[1].get_descriptor(), s[1].get_access_flags_string()]))

                        print(s[1].show())
                        console.colorize_decompiled_method(str(s[2].get_source()))

                if method == "back":
                    break
                elif method == "list":
                    for m in methods_set:
                        print(t.green("[{0}] ".format(datetime.now()) +
                              t.yellow("Available bowser method: ") + "{0}".format(m)))

        elif self.vm_type == "dex":

            _x = analysis.uVMAnalysis(self.vm)
            _vm = self.vm
            _structure = list()

            if _x:
                print(t.green("[{0}] ".format(datetime.now()) + t.yellow("Performing surgery ...")))
                for a, b in self.enum.values.items():
                    for c in b:
                        paths = _x.get_tainted_packages().search_methods("{0}".format(a), "{0}".format(c), ".")
                        if paths:
                            for p in paths:
                                for method in self.vm.get_methods():
                                    if method.get_name() == p.get_src(_vm.get_class_manager())[1]:
                                        if method.get_class_name() == p.get_src(_vm.get_class_manager())[0]:
                                            mx = _x.get_method(method)
                                            d = decompile.DvMethod(mx)
                                            try:
                                                d.process()
                                            except Exception as decompile_process_error:
                                                if decompile_process_error.message == \
                                                        "'Instruction31c' object has no attribute 'get_raw_string'":
                                                    pass
                                            _structure.append((c, method, d))
            methods = [s[0] for s in _structure]
            methods_set = set(methods)

            for m in methods_set:
                print(t.green("[{0}] ".format(datetime.now()) +
                              t.yellow("Available bowser method: ") + "{0}".format(m)))

            print(t.green("[{0}] ".format(datetime.now()) + t.yellow("Enter \'back\' to exit")))
            print(t.green("[{0}] ".format(datetime.now()) + t.yellow("Enter \'list\' to show available methods")))

            while True:
                method = raw_input(t.green("[{0}] ".format(datetime.now()) + t.yellow("Enter method selection: ")))

                for s in _structure:
                    if method == s[0]:
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Found: ") +
                                      "{0}".format(s[0])))
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Class: ") +
                                      "{0}".format(s[1].get_class_name())))
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Method: ") +
                                      "{0}".format(s[1].get_name())))
                        print(s[1].show())
                        console.colorize_decompiled_method(str(s[2].get_source()))

                if method == "back":
                    break
                elif method == "list":
                    for m in methods_set:
                        print(t.green("[{0}] ".format(datetime.now()) +
                              t.yellow("Available bowser method: ") + "{0}".format(m)))
示例#55
0
文件: socket.py 项目: wflk/lobotomy
    def run(self):

        """
        Search for socket service API implemenations
        """

        if self.vm_type == "apks":

            x = analysis.uVMAnalysis(self.vm.get_vm())
            _vm = self.vm.get_vm()
            _structure = list()

            if x:
                print(t.green("[{0}] ".format(datetime.now()) + t.yellow("Performing surgery ...")))
                # Get enum values
                #
                for a, b in self.enum.values.items():
                    for c in b:
                        paths = x.get_tainted_packages().search_methods("{0}".format(a), "{0}".format(c), ".")
                        if paths:
                            for p in paths:
                                for method in self.vm.get_methods():
                                    if method.get_name() == p.get_src(_vm.get_class_manager())[1]:
                                        if method.get_class_name() == p.get_src(_vm.get_class_manager())[0]:

                                            mx = x.get_method(method)
                                            d = decompile.DvMethod(mx)
                                            d.process()
                                            _structure.append((c, method, d))

            methods = [s[0] for s in _structure]
            methods_set = set(methods)

            for m in methods_set:
                print(t.green("[{0}] ".format(datetime.now()) +
                              t.yellow("Available logging methods: ") + "{0}".format(m)))

            print(t.green("[{0}] ".format(datetime.now()) +
                          t.yellow("Enter \'back\' to exit")))

            print(t.green("[{0}] ".format(datetime.now()) +
                          t.yellow("Enter \'list\' to show available functions")))

            while True:

                method = raw_input(t.green("[{0}] ".format(datetime.now()) + t.yellow("Enter method selection: ")))

                for s in _structure:
                    if method == s[0]:
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Found: ") +
                                      "{0}".format(s[0])))
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Class: ") +
                                      "{0}".format(s[1].get_class_name())))
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Method: ") +
                                      "{0}".format(s[1].get_name())))
                        print(s[1].show())
                        print(s[2].get_source())

                if method == "back":
                    break
                elif method == "list":
                    for m in methods_set:
                        print(t.green("[{0}] ".format(datetime.now()) +
                              t.yellow("Available logging methods: ") + "{0}".format(m)))

        elif self.vm_type == "dex":

            x = analysis.uVMAnalysis(self.vm)
            _vm = self.vm
            _structure = list()

            if x:
                print(t.green("[{0}] ".format(datetime.now()) + t.yellow("Performing surgery ...")))
                # Get enum values
                #
                for a, b in self.enum.values.items():
                    for c in b:
                        paths = x.get_tainted_packages().search_methods("{0}".format(a), "{0}".format(c), ".")
                        if paths:
                            for p in paths:
                                for method in self.vm.get_methods():
                                    if method.get_name() == p.get_src(_vm.get_class_manager())[1]:
                                        if method.get_class_name() == p.get_src(_vm.get_class_manager())[0]:

                                            mx = x.get_method(method)
                                            d = decompile.DvMethod(mx)
                                            d.process()
                                            _structure.append((c, method, d))

            methods = [s[0] for s in _structure]
            methods_set = set(methods)

            for m in methods_set:
                print(t.green("[{0}] ".format(datetime.now()) +
                              t.yellow("Available logging methods: ") + "{0}".format(m)))

            print(t.green("[{0}] ".format(datetime.now()) +
                          t.yellow("Enter \'back\' to exit")))

            print(t.green("[{0}] ".format(datetime.now()) +
                          t.yellow("Enter \'list\' to show available functions")))

            while True:

                method = raw_input(t.green("[{0}] ".format(datetime.now()) + t.yellow("Enter method selection: ")))

                for s in _structure:
                    if method == s[0]:
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Found: ") +
                                      "{0}".format(s[0])))
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Class: ") +
                                      "{0}".format(s[1].get_class_name())))
                        print(t.green("[{0}] ".format(datetime.now()) +
                                      t.yellow("Method: ") +
                                      "{0}".format(s[1].get_name())))
                        print(s[1].show())
                        print(s[2].get_source())

                if method == "back":
                    break
                elif method == "list":
                    for m in methods_set:
                        print(t.green("[{0}] ".format(datetime.now()) +
                              t.yellow("Available logging methods: ") + "{0}".format(m)))
示例#56
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
 def __init__(self, name):
     vm = auto_vm(name)
     self.vma = analysis.uVMAnalysis(vm)
     self.classes = dict((dvclass.get_name(), dvclass)
                         for dvclass in vm.get_classes())
示例#58
0
        arg1 = arg1.visit(self)
        if not isinstance(arg1, int):
            arg1 = ord(arg1)
        arg2 = arg2.visit(self)
        if not isinstance(arg2, int):
            arg2 = ord(arg2)
        return eval('%s %s %s' % (arg1, op, arg2))

    def visit_get_static(self, cls, name):
        return self.mem[name]


TEST = './apks/pacsec/magicspiral.apk'

vm = dvm.DalvikVMFormat(apk.APK(TEST).get_dex())
vma = uVMAnalysis(vm)

method = vm.get_method('crypt')[0]

amethod = vma.get_method(method)
dvmethod = DvMethod(amethod)
dvmethod.process()  # build IR Form / control flow...

graph = dvmethod.graph
visitor = DemoEmulator(graph)

l = [
    94, 42, 93, 88, 3, 2, 95, 2, 13, 85, 11, 2, 19, 1, 125, 19, 0, 102, 30, 24,
    19, 99, 76, 21, 102, 22, 26, 111, 39, 125, 2, 44, 80, 10, 90, 5, 119, 100,
    119, 60, 4, 87, 79, 42, 52
]
示例#59
0
    def run(self):
        """
        Search for Web Browser API usage within target class and methods
        """

        if self.vm_type == "apks":
            _x = analysis.uVMAnalysis(self.vm.get_vm())
            _vm = self.vm.get_vm()
            _structure = list()

            if _x:
                print(
                    t.green("[{0}] ".format(datetime.now()) +
                            t.yellow("Performing surgery ...")))
                for a, b in self.enum.values.items():
                    for c in b:
                        paths = _x.get_tainted_packages().search_methods(
                            "{0}".format(a), "{0}".format(c), ".")
                        if paths:
                            for p in paths:
                                for method in self.vm.get_methods():
                                    if method.get_name() == p.get_src(
                                            _vm.get_class_manager())[1]:
                                        if method.get_class_name(
                                        ) == p.get_src(
                                                _vm.get_class_manager())[0]:
                                            mx = _x.get_method(method)
                                            d = decompile.DvMethod(mx)
                                            try:
                                                d.process()
                                            except Exception as decompile_process_error:
                                                if decompile_process_error.message == \
                                                        "'Instruction31c' object has no attribute 'get_raw_string'":
                                                    pass
                                            _structure.append((c, method, d))

            methods = [s[0] for s in _structure]
            methods_set = set(methods)

            for m in methods_set:
                print(
                    t.green("[{0}] ".format(datetime.now()) +
                            t.yellow("Available bowser method: ") +
                            "{0}".format(m)))

            print(
                t.green("[{0}] ".format(datetime.now()) +
                        t.yellow("Enter \'back\' to exit")))
            print(
                t.green("[{0}] ".format(datetime.now()) +
                        t.yellow("Enter \'list\' to show available methods")))

            while True:
                method = raw_input(
                    t.green("[{0}] ".format(datetime.now()) +
                            t.yellow("Enter method selection: ")))
                for s in _structure:
                    if method == s[0]:
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Found: ") + "{0}".format(s[0])))
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Class: ") +
                                    "{0}".format(s[1].get_class_name())))
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Method: ") +
                                    "{0}".format(s[1].get_name())))

                        print("".join([
                            s[1].get_class_name(), "->", s[1].get_name(),
                            s[1].get_descriptor(),
                            s[1].get_access_flags_string()
                        ]))

                        print(s[1].show())
                        console.colorize_decompiled_method(
                            str(s[2].get_source()))

                if method == "back":
                    break
                elif method == "list":
                    for m in methods_set:
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Available bowser method: ") +
                                    "{0}".format(m)))

        elif self.vm_type == "dex":

            _x = analysis.uVMAnalysis(self.vm)
            _vm = self.vm
            _structure = list()

            if _x:
                print(
                    t.green("[{0}] ".format(datetime.now()) +
                            t.yellow("Performing surgery ...")))
                for a, b in self.enum.values.items():
                    for c in b:
                        paths = _x.get_tainted_packages().search_methods(
                            "{0}".format(a), "{0}".format(c), ".")
                        if paths:
                            for p in paths:
                                for method in self.vm.get_methods():
                                    if method.get_name() == p.get_src(
                                            _vm.get_class_manager())[1]:
                                        if method.get_class_name(
                                        ) == p.get_src(
                                                _vm.get_class_manager())[0]:
                                            mx = _x.get_method(method)
                                            d = decompile.DvMethod(mx)
                                            try:
                                                d.process()
                                            except Exception as decompile_process_error:
                                                if decompile_process_error.message == \
                                                        "'Instruction31c' object has no attribute 'get_raw_string'":
                                                    pass
                                            _structure.append((c, method, d))
            methods = [s[0] for s in _structure]
            methods_set = set(methods)

            for m in methods_set:
                print(
                    t.green("[{0}] ".format(datetime.now()) +
                            t.yellow("Available bowser method: ") +
                            "{0}".format(m)))

            print(
                t.green("[{0}] ".format(datetime.now()) +
                        t.yellow("Enter \'back\' to exit")))
            print(
                t.green("[{0}] ".format(datetime.now()) +
                        t.yellow("Enter \'list\' to show available methods")))

            while True:
                method = raw_input(
                    t.green("[{0}] ".format(datetime.now()) +
                            t.yellow("Enter method selection: ")))

                for s in _structure:
                    if method == s[0]:
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Found: ") + "{0}".format(s[0])))
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Class: ") +
                                    "{0}".format(s[1].get_class_name())))
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Method: ") +
                                    "{0}".format(s[1].get_name())))
                        print(s[1].show())
                        console.colorize_decompiled_method(
                            str(s[2].get_source()))

                if method == "back":
                    break
                elif method == "list":
                    for m in methods_set:
                        print(
                            t.green("[{0}] ".format(datetime.now()) +
                                    t.yellow("Available bowser method: ") +
                                    "{0}".format(m)))