Example #1
0
    def module_run(self, verbose=False):

        z = self.apk.vm_analysis.tainted_packages.search_methods(
            ".", "getSystemService", ".")

        external_services = set()
        for p in z:
            method = self.apk.dalvik_vm_format.get_method_by_idx(
                p.get_src_idx())
            if method.get_code() is None:
                continue
            mx = self.apk.vm_analysis.get_method(method)
            if self.apk.get_package() in method.get_class_name().replace(
                    "/", "."):
                ms = decompile.DvMethod(mx)
                try:
                    ms.process()
                except AttributeError as e:
                    self.warning(
                        "Error while processing disassembled Dalvik method: %s"
                        % e.message)
                source = ms.get_source()
                matches = re.findall(r'getSystemService\("([^"]*)"\)', source)
                if len(matches):
                    external_services.add(android_system_services[matches[0]])
        return {"results": sorted(external_services), "vulnerabilities": []}
Example #2
0
    def module_run(self, verbose=False):

        results = []

        z = self.apk.vm_analysis.tainted_packages.search_methods(
            "Landroid/content/Intent", "<init>", ".")

        for p in z:
            method = self.apk.dalvik_vm_format.get_method_by_idx(
                p.get_src_idx())
            if method.get_code() is None:
                continue
            if self.apk.get_package() in method.get_class_name().replace(
                    "/", "."):
                mx = self.apk.vm_analysis.get_method(method)
                ms = decompile.DvMethod(mx)
                try:
                    ms.process()
                except AttributeError as e:
                    self.warning(
                        "Error while processing disassembled Dalvik method: %s"
                        % e.message)
                source = ms.get_source()
                matches = re.findall(r'Intent\(([^\)]*)\);', source)
                if len(matches):
                    results.append({
                        "file": method.get_class_name()[1:-1],
                        "line": method.get_debug().get_line_start(),
                    })

        return {"results": results, "vulnerabilities": []}
Example #3
0
    def get_source_method(self, m):
        mx = self.vmx.get_method(m)
        z = decompile.DvMethod(mx)
        z.process()

        result = z.get_source()
        return result
Example #4
0
    def process_methods(self, found_methods):
        """
        Process and return a unique and analyzed list of methods based on usage
        findings.

        Args:
            param1: Discovered methods

        Returns:
            return: Processed methods
        """

        # Locals
        seen = set()
        unique = list()
        processed = list()

        for m in found_methods:
            if m.get_class_name() not in seen:
                unique.append(m)
                seen.add(m.get_class_name())
        for u in unique:
            if u.get_code():
                analyzed = self.vmx.get_method(u)
                src = decompile.DvMethod(analyzed)
                src.process()
                processed.append((u, analyzed, src.get_source()))
            else:
                analyzed = self.vmx.get_method(u)
                processed.append((u, analyzed, None))
        return processed
Example #5
0
    def module_run(self, verbose=False):

        logs = ""
        vulnerable = False
        providers = self.get_providers()

        z = self.apk.vm_analysis.tainted_packages.search_methods(
            ".", "addURI", ".")

        for p in z:
            method = self.apk.dalvik_vm_format.get_method_by_idx(
                p.get_src_idx())
            if method.get_code() is None:
                continue
            mx = self.apk.vm_analysis.get_method(method)
            ms = decompile.DvMethod(mx)
            try:
                ms.process()
            except AttributeError as e:
                self.warning(
                    "Error while processing disassembled Dalvik method: %s" %
                    e.message)
            source = ms.get_source()
            matches = re.findall(r'addURI\("([^"]*)", "([^"]*)"', source)
            for match in matches:
                for provider in providers:
                    if provider["authorities"] == match[0]:
                        provider["uris"].add("uri://%s/%s" %
                                             (match[0], match[1]))

        for provider in providers:
            provider["uris"] = list(provider["uris"])

            if provider["exported"] and provider["permission"] is None and provider["read_permission"] is None\
                    and provider["write_permission"] is None:
                #content was introduced in honeycomb
                if self.avd is not None and self.avd.target >= 16:
                    for uri in provider["uris"]:
                        logs += "$ adb shell content query --uri %s\n" % uri
                        logs += self.avd.shell("content query --uri %s" % uri)
                provider["vulnerable"] = True
                vulnerable = True
            else:
                provider["vulnerable"] = False

        if verbose:
            print logs
        return {
            "results":
            providers,
            "vulnerabilities": [
                framework.Vulnerability(
                    "Exported content provider.",
                    "The following application provider is exported, which means that any application can access it"
                    " without the need for any custom permission.",
                    framework.Vulnerability.MEDIUM,
                    resources=[p for p in providers if p["vulnerable"]],
                    logs=logs).__dict__
            ] if vulnerable else []
        }
Example #6
0
    def _analyze(self, apk, dalvik_vm_format, vm_analysis, gvm_analysis, *args,
                 **kwargs):

        # CFG
        for method in dalvik_vm_format.get_methods():
            try:
                mx = vm_analysis.get_method(method)

                if method.get_code() == None:
                    continue

                classname, methodname, method_descriptor = method.get_class_name(
                ), method.get_name(), method.get_descriptor()

                # skip android classes due to mongo db document limit
                if classname.find("Landroid") != -1:
                    continue

                ms = decompile.DvMethod(mx)
                # process to the decompilation
                ms.process()

                self.cres += '''%s.%s%s {
    %s
    }
''' % (classname, methodname, method_descriptor, ms.get_source())
            except:
                pass
Example #7
0
    def _analyze(self, apk, dalvik_vm_format, vm_analysis, gvm_analysis, *args, **kwargs):
        ''' This sample code is taken from `androguard` and has been modified!

        See Also
        --------
        http://code.google.com/p/androguard/wiki/RE#Source_Code
        '''

        res = self.res

        res.register_keys([CAT_DECOMPILE])

        # CFG
        for method in dalvik_vm_format.get_methods():
            mx = vm_analysis.get_method(method)

            if method.get_code() == None:
                continue
            try:
                classname, methodname, method_descriptor = method.get_class_name(), method.get_name(), method.get_descriptor()
                
                # skip android classes
                if classname.find("Landroid") != -1:
                    continue
                CAT = (CAT_DECOMPILE, classname, methodname)
                res.register_keys([method_descriptor], *CAT)
    
                ms = decompile.DvMethod(mx)
                # process to the decompilation
                ms.process()
    
                # get the source !
                res.log(method_descriptor, ms.get_source().split("\n"), *CAT)
            except:
                pass
Example #8
0
    def module_run(self, verbose=False):

        results = {}

        z = self.apk.vm_analysis.tainted_packages.search_packages("Log")
        for p in z:
            method = self.apk.dalvik_vm_format.get_method_by_idx(
                p.get_src_idx())
            if self.apk.package.replace(".",
                                        "/") in method.get_class_name()[1:-1]:
                if method.get_code() is None:
                    continue
                mx = self.apk.vm_analysis.get_method(method)
                ms = decompile.DvMethod(mx)
                try:
                    ms.process()
                except AttributeError as e:
                    self.warning(
                        "Error while processing disassembled Dalvik method: %s"
                        % e.message)
                if method.get_class_name()[1:-1] not in results:
                    results[method.get_class_name()[1:-1]] = []

                if method.get_debug().get_line_start() not in \
                        [x["line"] for x in results[method.get_class_name()[1:-1]]]:
                    results[method.get_class_name()[1:-1]].append({
                        "type":
                        ms.type,
                        "line":
                        method.get_debug().get_line_start()
                    })

        return {"results": results, "vulnerabilities": []}
Example #9
0
    def _analyze(self, apk, dalvik_vm_format, vm_analysis, gvm_analysis, *args,
                 **kwargs):
        res = self.res

        res.register_keys([CAT_PERMISSIONS])

        class_manager = dalvik_vm_format.get_class_manager()
        perm_dict = vm_analysis.get_permissions([])

        # register list for each used permissions keys
        permissions = set(perm_dict.keys())

        res.register_enum_keys(permissions, CAT_PERMISSIONS,
                               PERMISSIONS_LISTING)
        # register each permission only once!
        res.register_enum_keys(permissions, CAT_PERMISSIONS, PERMISSIONS_CODE)

        # use set to remove duplicates!
        method_names = set()
        method_analysis_objs = set()
        for permission_name, pathp_obj_list in perm_dict.items():

            # list<PathP>
            for pathp in pathp_obj_list:
                if isinstance(pathp, PathP):
                    # type: androguard.core.bytecodes.dvm.MethodIdItem
                    # the method that uses the permission
                    src_method = class_manager.get_method_ref(pathp.src_idx)
                    method_name = full_method_name(src_method)
                    method_names.add((permission_name, method_name))

                    # the api function for the permission
                    #dst_method = class_manager.get_method_ref(pathp.dst_idx)

                    # get androguard.core.bytecodes.dvm.EncodedMethod
                    encoded_method = dalvik_vm_format.get_method(
                        src_method.get_name())[0]

                    # get androguard.core.analysis.analysis.MethodAnalysis
                    method_analysis = vm_analysis.get_method(encoded_method)

                    method_analysis_objs.add(
                        (permission_name, method_name, method_analysis))

        for permission_name, method_name in method_names:
            # log which classes use which permissions
            res.log_append_to_enum(permission_name, method_name,
                                   CAT_PERMISSIONS, PERMISSIONS_LISTING)

        for permission_name, method_name, method_analysis in method_analysis_objs:

            ms = decompile.DvMethod(method_analysis)
            ms.process()

            source_code = ms.get_source()

            # decompile these methods too!
            log_val = {method_name: source_code.split("\n")[1:-1]}
            res.log_append_to_enum(permission_name, log_val, CAT_PERMISSIONS,
                                   PERMISSIONS_CODE)
Example #10
0
    def module_run(self, verbose=False):

        results = {}
        apis = {
            "Crypto": ["javax.crypto", "java.security", "android.security"],
            "Networking":
            ["java.net", "org.apache.http", "javax.net", "javax.net.ssl"],
            "IO": ["java.io"],
            "Databases": ["android.database", "javax.sql", "java.sql"],
            "Communications": [
                "android.telephony", "android.bluetooth", "android.net.sip",
                "android.net.wifi", "android.net.wifi.p2p", "android.nfc"
            ],
            "Geolocation": ["android.location"]
        }

        for api in apis:
            results[api] = {}
            if verbose:
                self.output("Searching for %s calls" % api)
            for package in apis[api]:
                results[api][package] = {}
                z = self.apk.vm_analysis.tainted_packages.search_packages(
                    package)
                for p in z:
                    method = self.apk.dalvik_vm_format.get_method_by_idx(
                        p.get_src_idx())
                    if self.apk.package.replace(
                            ".", "/") in method.get_class_name()[1:-1]:
                        if method.get_code() is None:
                            continue
                        mx = self.apk.vm_analysis.get_method(method)
                        ms = decompile.DvMethod(mx)
                        try:
                            ms.process()
                        except AttributeError as e:
                            self.warning(
                                "Error while processing disassembled Dalvik method: %s"
                                % e.message)
                        if method.get_class_name(
                        )[1:-1] not in results[api][package]:
                            results[api][package][method.get_class_name()
                                                  [1:-1]] = []

                        if method.get_debug().get_line_start() not in \
                                [x["line"] for x in results[api][package][method.get_class_name()[1:-1]]]:
                            results[api][package][
                                method.get_class_name()[1:-1]].append({
                                    "line":
                                    method.get_debug().get_line_start()
                                })
        for api in apis:
            total = 0
            for package in apis[api]:
                total += len(results[api][package])
            if not total:
                del (results[api])

        return {"results": results, "logs": "", "vulnerabilities": []}
Example #11
0
def decompileMethod(dx, method):
    mx = dx.get_method(method)

    ms = decompile.DvMethod(mx)
    # process to the decompilation
    ms.process()

    # get the source !
    return ms.get_source()
Example #12
0
def grab_source_code(d, dx):
    source = collections.OrderedDict()

    for classe in d.get_classes():
        data = collections.OrderedDict()
        for metodo in classe.get_methods():
            method = dx.get_method(metodo)
            ms = decompile.DvMethod(method)
            ms.process()
            data[metodo.name] = ms.get_source()
        source[classe.get_name()] = data
    return source
Example #13
0
def diffMethod(dexO, dexR, classNameO, methodNameO, classNameR, methodNameR):
    vm = dvm.DalvikVMFormat(open(dexO, "r").read())
    vmx = analysis.VMAnalysis(vm)

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

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

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

                text = (_unidiff_output(ms.get_source(), msR.get_source()))
                print("getOneMethod")
                return text
Example #14
0
    def display_source(self, m) :
        mx = self.vmx.get_method( m )
        
        from androguard.decompiler.dad import decompile 

        z = decompile.DvMethod( mx )
        z.process()

        lexer = get_lexer_by_name("java", stripall=True)
        formatter = TerminalFormatter()
        result = highlight(z.get_source(), lexer, formatter)
        print result
Example #15
0
    def module_run(self, verbose=False):

        results = []

        z = self.apk.vm_analysis.tainted_packages.search_methods(
            ".", "rawQuery", ".")
        z += self.apk.vm_analysis.tainted_packages.search_methods(
            ".", "query", ".")

        for p in z:
            method = self.apk.dalvik_vm_format.get_method_by_idx(
                p.get_src_idx())
            if method.get_code() is None:
                continue
            mx = self.apk.vm_analysis.get_method(method)
            if self.apk.get_package() in method.get_class_name().replace(
                    "/", "."):
                ms = decompile.DvMethod(mx)
                try:
                    ms.process()
                except AttributeError as e:
                    self.warning(
                        "Error while processing disassembled Dalvik method: %s"
                        % e.message)
                if method.get_class_name()[1:-1] not in [
                        x["file"] for x in results
                ]:
                    results.append({
                        "file":
                        method.get_class_name()[1:-1],
                        "lines": [method.get_debug().get_line_start()]
                    })
                else:
                    for r in results:
                        if r["file"] == method.get_class_name()[1:-1]:
                            if method.get_debug().get_line_start(
                            ) not in r["lines"]:
                                r["lines"].append(
                                    method.get_debug().get_line_start())

        return {
            "results":
            results,
            "vulnerabilities": [
                framework.Vulnerability(
                    "Multiple SQL injection vectors.",
                    "The application do not make use of prepared statement which could lead to SQL injection vulnerabilities.\n"
                    "Review the results to see if these raw queries can be exploited.",
                    framework.Vulnerability.MEDIUM,
                    resources=results).__dict__
            ] if len(results) else []
        }
Example #16
0
def getNewMethods(dexR, classNameR, methodNameR):
    vmR = dvm.DalvikVMFormat(open(dexR, "r").read())
    vmxR = analysis.VMAnalysis(vmR)

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

            text = msR.get_source()
            print("getNewMethod")
            return text
Example #17
0
    def module_run(self, verbose=False):

        results = {}

        #external storage
        z = self.apk.vm_analysis.tainted_packages.search_methods(
            ".", "getExternalStorageState()", ".")
        z += self.apk.vm_analysis.tainted_packages.search_methods(
            ".", "getExternalStoragePublicDirectory", ".")
        z += self.apk.vm_analysis.tainted_packages.search_methods(
            ".", "getExternalFilesDirs()", ".")
        z += self.apk.vm_analysis.tainted_packages.search_methods(
            ".", "getExternalCacheDirs()", ".")

        #internal storage
        z += self.apk.vm_analysis.tainted_packages.search_methods(
            ".", "getFilesDir()", ".")
        z += self.apk.vm_analysis.tainted_packages.search_methods(
            ".", "getDir()", ".")
        z += self.apk.vm_analysis.tainted_packages.search_methods(
            ".", "deleteFile()", ".")
        z += self.apk.vm_analysis.tainted_packages.search_methods(
            ".", "fileList()", ".")

        for p in z:
            method = self.apk.dalvik_vm_format.get_method_by_idx(
                p.get_src_idx())
            if method.get_code() is None:
                continue
            mx = self.apk.vm_analysis.get_method(method)
            if self.apk.get_package() in method.get_class_name().replace(
                    "/", "."):
                ms = decompile.DvMethod(mx)
                try:
                    ms.process()
                except AttributeError as e:
                    self.warning(
                        "Error while processing disassembled Dalvik method: %s"
                        % e.message)
                if method.get_class_name()[1:-1] not in results:
                    results[method.get_class_name()[1:-1]] = []

                if method.get_debug().get_line_start() not in \
                        [x["line"] for x in results[method.get_class_name()[1:-1]]]:
                    results[method.get_class_name()[1:-1]].append({
                        "source":
                        ms.get_source(),
                        "line":
                        method.get_debug().get_line_start()
                    })
        return {"results": results, "vulnerabilities": []}
Example #18
0
def ast_for_method_analysis(method_analysis):
    '''
    Create the abstract syntax tree.
    
    Parameters
    ----------
    method_analysis: androguard.androguard.core.analysis.analysis.MethodAnalysis
        
    Returns
    -------
    dict
        The abstract syntax tree of the `method_analysis`.
    '''
    dv_method = decompile.DvMethod(method_analysis)
    dv_method.process(doAST=True)
    return dv_method.ast
def decompileMethod(methodObj, analysis):
    # <methodObj> e un obiect de tipul EncodedMethod
    # <analysis> e un obiect de tipul VMAnalysis
    if method.get_code() == None:
        return None
    methodAnalysis = analysis.get_method(
        method)  # returns MethodAnalysis object
    decompMethod = decompile.DvMethod(methodAnalysis)
    try:
        decompMethod.process()
        methodSource = decompMethod.get_source()
    except:
        print 'Failed to decompile [%s]' % methodObj.get_name()
        return '''   method %s() {
        // failed to decompile
    }'''
    return methodSource
Example #20
0
    def module_run(self, verbose=False):

        results = {}

        z = self.apk.vm_analysis.tainted_packages.search_objects(
            "SQLiteClosable")
        z += self.apk.vm_analysis.tainted_packages.search_objects(
            "SQLiteCursor")
        z += self.apk.vm_analysis.tainted_packages.search_objects(
            "SQLiteDatabase")
        z += self.apk.vm_analysis.tainted_packages.search_objects(
            "SQLiteOpenHelper")
        z += self.apk.vm_analysis.tainted_packages.search_objects(
            "SQLiteProgram")
        z += self.apk.vm_analysis.tainted_packages.search_objects(
            "SQLiteQuery")
        z += self.apk.vm_analysis.tainted_packages.search_objects(
            "SQLiteQueryBuilder")
        z += self.apk.vm_analysis.tainted_packages.search_objects(
            "SQLiteStatement")

        for p in z:
            method = self.apk.dalvik_vm_format.get_method_by_idx(
                p.get_src_idx())
            if method.get_code() is None:
                continue
            mx = self.apk.vm_analysis.get_method(method)
            if self.apk.get_package() in method.get_class_name().replace(
                    "/", "."):
                ms = decompile.DvMethod(mx)
                try:
                    ms.process()
                except AttributeError as e:
                    self.warning(
                        "Error while processing disassembled Dalvik method: %s"
                        % e.message)
                if method.get_class_name()[1:-1] not in results:
                    results[method.get_class_name()[1:-1]] = []

                if method.get_debug().get_line_start() not in \
                        [x["line"] for x in results[method.get_class_name()[1:-1]]]:
                    results[method.get_class_name()[1:-1]].append(
                        {"line": method.get_debug().get_line_start()})

        return {"results": results, "vulnerabilities": []}
Example #21
0
    def decompile_method(self, method_to_decompile):
        """This function will decompile the given method. Maybe there is a better way. """
        if not self.quiet:
            print "Method to decompile :", method_to_decompile
            print "------------"
            
        for method in self.dalvik_executable.get_methods():
            mx = self.analyzed_dex.get_method(method)

            if method.get_code() == None:
                continue
            
            method_decompiling = method.get_class_name() + method.get_name() + method.get_descriptor()

            if method_to_decompile != method_decompiling:
                #debug
                #if not self.quiet:
                #    print method_decompiling
                continue

            if not self.quiet:
                print "About to decompile the following method : "
                print method.get_class_name(), method.get_name(), method.get_descriptor()
                print "[*] Decompilation initated"

            self.smali += [''.join((method.get_class_name(), method.get_name(), method.get_descriptor()))]
            
            ms = decompile.DvMethod(mx)
            
            if not self.quiet:
                print "[*] Processing..."
            try:
                ms.process()
            except:
                return None

            java_source = ms.get_source()

            if not self.quiet:
                print java_source
            
            self.java += [java_source]
Example #22
0
def extractSourceFiles(PREFIX, d, vmx):
    check_dirs(settings.SOURCELOCATION, PREFIX)

    for _class in d.get_classes():
        class_path = convert_descriptor(_class.get_name())
        path = check_path(class_path, PREFIX)
        if not os.path.exists(path):
            if len(path) > 255:
                ext = os.path.basename(path).split(".")[-1]
                newName = os.path.dirname(
                    path) + "/filename_to_long_suspiciousFile-" + id_generator(
                    ) + "." + ext
                source = open(newName, "w")
            else:
                source = open(path, "w")
            for field in _class.get_fields():

                access_flags = field.get_access_flags_string()
                if access_flags == "0x0":
                    access_flags = ""

                source.write(
                    "\t%s %s %s\n" %
                    (access_flags, convert_descriptor(
                        field.get_descriptor()), field.get_name()))

            for method in _class.get_methods():
                try:
                    g = vmx.get_method(method)
                    if method.get_code() is None:
                        continue
                    ms = decompile.DvMethod(g)
                    ms.process()
                    for line in ms.get_source().split("\n"):
                        source.write("\t%s\n" % line)
                except:
                    continue
            source.flush()
            source.close()
Example #23
0
    def run_search_method(apks, x, clz, method, permission):
        """
        Search for API calls and implementation location
        """

        vm = apks.get_vm()
        paths = x.get_tainted_packages().search_methods(clz, method, ".")

        if paths:
            for p in paths:
                for m in apks.get_methods():
                    if m.get_name() == p.get_src(vm.get_class_manager())[1]:
                        if m.get_class_name() == p.get_src(
                                vm.get_class_manager())[0]:

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

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

                            print(m.pretty_show())
                            print(d.get_source())
Example #24
0
def decompile_method_analysis(method_analysis):
    '''
    Decompile the `method_analysis` object
    
    Parameters
    ----------
    method_analysis: androguard.androguard.core.analysis.analysis.MethodAnalysis
        
    Returns
    -------
    str
        The decompiled method
        
    Example
    -------
    >>> decompile_method_analysis(...)
    protected varargs String doInBackground(Void[] p14)
    {
        org.apache.http.client.methods.HttpGet v6_1 = new org.apache.http.client.methods.HttpGet("http://10.10.0.134:8080/index.html");
        v6_1.addHeader("Authorization", new StringBuilder().append("Basic ").append(android.util.Base64.encodeToString(this.CREDENTIALS.getBytes(), 2)).toString());
        try {
            java.io.InputStream v9 = new org.apache.http.impl.client.DefaultHttpClient().execute(v6_1).getEntity().getContent();
            int v7 = de.uni_marburg.ipcinetcallee.InetActivity.inputStream2String(v9);
            v9.close();
        } catch (org.apache.http.client.ClientProtocolException v2) {
            android.util.Log.e("HTTPGetTask", "msg", v2);
            v7 = 0;
        } catch (java.io.IOException v5) {
            android.util.Log.e("HTTPGetTask", "msg", v5);
        }
        return v7;
    }
    '''
    dv_method = decompile.DvMethod(method_analysis)
    dv_method.process()
    return dv_method.get_source()
Example #25
0
    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)))
Example #26
0
    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)))
Example #27
0
    def module_run(self, verbose=False):

        webviews = []
        vulnerable = False
        funcs = [{
            "name": "setJavaScriptEnabled",
            "default": False,
            "description": "Allows the WebView to execute Javascript."
        }, {
            "name":
            "setPluginsEnabled"
            if self.apk.get_min_sdk_version() < 8 else "setPluginState",
            "default":
            True,
            "description":
            "Allow the loading of plugins (ie. Flash)."
        }, {
            "name":
            "setAllowContentAccess",
            "default":
            True,
            "description":
            "WebView has access to content providers on the system."
        }, {
            "name":
            "setAllowFileAccess",
            "default":
            True,
            "description":
            "Allows a WebView to load content from the filesystem using file:// scheme."
        }, {
            "name":
            "setAllowFileAccessFromFileURLS",
            "default":
            True if self.apk.get_min_sdk_version() <= 15 else False,
            "description":
            "Allows the HTML file that was loaded using file:// scheme to access "
            "other files on the system"
        }, {
            "name":
            "setAllowUniversalAccessFromFilesURLS",
            "default":
            True if self.apk.get_min_sdk_version() <= 15 else False,
            "description":
            "Allows the HTML file that was loaded using file:// to "
            "access content from any origin (including other files)."
        }, {
            "name": "setSavePassword",
            "default": True,
            "description": "The WebView will save entered passwords."
        }]

        z = self.apk.vm_analysis.tainted_packages.search_packages("WebView")

        for p in z:
            method = self.apk.dalvik_vm_format.get_method_by_idx(
                p.get_src_idx())
            if method.get_code() is None:
                continue
            if method.get_class_name()[1:-1] not in [
                    x["file"] for x in webviews
            ]:
                webview = {
                    "file": method.get_class_name()[1:-1],
                    "line": method.get_debug().get_line_start()
                }
                mx = self.apk.vm_analysis.get_method(method)
                ms = decompile.DvMethod(mx)

                try:
                    ms.process()
                except AttributeError as e:
                    self.warning(
                        "Error while processing disassembled Dalvik method: %s"
                        % e.message)

                source = ms.get_source()
                for func in funcs:
                    matches = re.findall(r'%s\((.*?)\);' % func["name"],
                                         source)
                    if len(matches) == 1:
                        webview[func["name"]] = True if matches[
                            0] == "1" or matches[0] == "true" else False
                    else:
                        webview[func["name"]] = func["default"]
                webviews.append(webview)

        for webview in webviews:
            if webview["setJavaScriptEnabled"]:
                vulnerable = True

        return {
            "results":
            webviews,
            "logs":
            "",
            "vulnerabilities": [
                framework.Vulnerability(
                    "Explicitly enabled Javascript in WebViews",
                    "The application explicitly enable Javascript for multiple webviews.",
                    framework.Vulnerability.MEDIUM,
                    resources=webviews).__dict__
            ] if vulnerable else []
        }
Example #28
0
 def get_ast_method(self, m):
     mx = self.vmx.get_method(m)
     z = decompile.DvMethod(mx)
     z.process(doAST=True)
     return z.get_ast()
Example #29
0
#!/usr/bin/env python

import sys

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

from androguard.core.bytecodes import dvm
from androguard.core.analysis import analysis
from androguard.decompiler.dad import decompile
from androguard.util import read

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

vm = dvm.DalvikVMFormat(read(TEST, binary=False))
vmx = analysis.VMAnalysis(vm)

# CFG
for method in vm.get_methods():
    mx = vmx.get_method(method)

    if method.get_code() == None:
        continue

    print method.get_class_name(), method.get_name(), method.get_descriptor()

    ms = decompile.DvMethod(mx)
    ms.process()

    print ms.get_source()
Example #30
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)))