示例#1
0
    def addAPK(self, filename, data):
        """
        Add an APK file to the Session and run analysis on it.

        :param filename: (file)name of APK file
        :param data: binary data of the APK file
        :return: a tuple of SHA256 Checksum and APK Object
        """
        digest = hashlib.sha256(data).hexdigest()
        log.debug("add APK:%s" % digest)
        apk = APK(data, True)
        self.analyzed_apk[digest] = [apk]
        self.analyzed_files[filename].append(digest)
        self.analyzed_digest[digest] = filename

        dx = Analysis()
        self.analyzed_vms[digest] = dx

        for dex in apk.get_all_dex():
            # we throw away the output... FIXME?
            self.addDEX(filename, dex, dx, postpone_xref=True)

        # Postponed
        dx.create_xref()

        log.debug("added APK:%s" % digest)
        return digest, apk
示例#2
0
def check(indicators, path, verbose=False):
    """
    Check an APK with given indicators
    Returns True/False, string (explanation of the discovery)
    """
    m = hashlib.sha256()
    with open(path, 'rb') as f:
        data = f.read()
        m.update(data)
    res = search(m.hexdigest(), indicators['sha256'], 'value')
    if verbose:
        print("SHA256: {}".format(m.hexdigest()))
    if res:
        if verbose:
            print("Known Stalkerware hash: {}".format(res))
            return True, "Known Stalkerware hash: {}".format(res)
    else:
        if verbose:
            print("App hash not in the indicator database")

    apk = APK(path)
    res = search(apk.get_package(), indicators['appids'], 'package')
    if verbose:
        print("Package id: {}".format(apk.get_package()))
    if res:
        if verbose:
            print("Known stalkerware package id: {}".format(res))
        return True, "Known stalkerware package id: {}".format(res)
    else:
        if verbose:
            print("Package id not in the indicators")

    if len(apk.get_certificates()) > 0:
        cert = apk.get_certificates()[0]
        sha1 = cert.sha1_fingerprint.replace(' ', '')
        if verbose:
            print("Certificate: {}".format(sha1))
        res = search(sha1, indicators['certificates'], 'certificate')
        if res:
            if verbose:
                print("Known Stalkerware certificate: {}".format(res))
            return True, "Known Stalkerware certificate: {}".format(res)
        else:
            if verbose:
                print("Certificate not in the indicators")
    else:
        if verbose:
            print("No certificate in this APK")
    if 'yara' in indicators:
        for dex in apk.get_all_dex():
            res = indicators['yara'].match(data=dex)
            if len(res) > 0:
                if verbose:
                    print("Matches yara rules {}".format(res[0]))
                return True, "Yara rule {}".format(res[0])
            else:
                if verbose:
                    print("Does not match any yara rules")
    return False, ""
示例#3
0
def AnalyzeAPK(_file, session=None, raw=False):
    """
    Analyze an android application and setup all stuff for a more quickly
    analysis!
    If session is None, no session is used at all. This is the default
    behaviour.
    If you like to continue your work later, it might be a good idea to use a
    session.
    A default session can be created by using :meth:`~get_default_session`.

    :param _file: the filename of the android application or a buffer which represents the application
    :type _file: string (for filename) or bytes (for raw)
    :param session: A session (default: None)
    :param raw: boolean if raw bytes are supplied instead of a filename
    :rtype: return the :class:`~androguard.core.bytecodes.apk.APK`, list of :class:`~androguard.core.bytecodes.dvm.DalvikVMFormat`, and :class:`~androguard.core.analysis.analysis.Analysis` objects
    """
    log.debug("AnalyzeAPK")


    if session:
        log.debug("Using existing session {}".format(session))
        if raw:
            data = _file
            filename = hashlib.md5(_file).hexdigest()
        else:
            with open(_file, "rb") as fd:
                data = fd.read()
                filename = _file

        digest = session.add(filename, data)
        return session.get_objects_apk(filename, digest)
    else:
        log.debug("Analysing without session")
        a = APK(_file, raw=raw)
        # FIXME: probably it is not necessary to keep all DalvikVMFormats, as
        # they are already part of Analysis. But when using sessions, it works
        # this way...
        d = []
        dx = Analysis()
        for dex in a.get_all_dex():
            df = DalvikVMFormat(dex, using_api=a.get_target_sdk_version())
            dx.add(df)
            d.append(df)
            df.set_decompiler(decompiler.DecompilerDAD(d, dx))

        dx.create_xref()

        return a, d, dx
示例#4
0
文件: misc.py 项目: lantaoxu/dcc-1
def AnalyzeAPK(_file, session=None, raw=False):
    """
    Analyze an android application and setup all stuff for a more quickly
    analysis!
    If session is None, no session is used at all. This is the default
    behaviour.
    If you like to continue your work later, it might be a good idea to use a
    session.
    A default session can be created by using :meth:`~get_default_session`.

    :param _file: the filename of the android application or a buffer which represents the application
    :type _file: string (for filename) or bytes (for raw)
    :param session: A session (default: None)
    :param raw: boolean if raw bytes are supplied instead of a filename
    :rtype: return the :class:`~androguard.core.bytecodes.apk.APK`, list of :class:`~androguard.core.bytecodes.dvm.DalvikVMFormat`, and :class:`~androguard.core.analysis.analysis.Analysis` objects
    """
    log.debug("AnalyzeAPK")

    if session:
        log.debug("Using existing session {}".format(session))
        if raw:
            data = _file
            filename = hashlib.md5(_file).hexdigest()
        else:
            with open(_file, "rb") as fd:
                data = fd.read()
                filename = _file

        digest = session.add(filename, data)
        return session.get_objects_apk(filename, digest)
    else:
        log.debug("Analysing without session")
        a = APK(_file, raw=raw)
        # FIXME: probably it is not necessary to keep all DalvikVMFormats, as
        # they are already part of Analysis. But when using sessions, it works
        # this way...
        d = []
        dx = Analysis()
        for dex in a.get_all_dex():
            df = DalvikVMFormat(dex, using_api=a.get_target_sdk_version())
            dx.add(df)
            d.append(df)
            df.set_decompiler(decompiler.DecompilerDAD(d, dx))

        dx.create_xref()

        return a, d, dx
示例#5
0
    def addAPK(self, filename, data):
        """
        Add an APK file to the Session and run analysis on it.

        :param filename: (file)name of APK file
        :param data: binary data of the APK file
        :return: a tuple of SHA256 Checksum and APK Object
        """
        digest = hashlib.sha256(data).hexdigest()
        log.debug("add APK:%s" % digest)
        apk = APK(data, True)
        self.analyzed_apk[digest] = [apk]
        self.analyzed_files[filename].append(digest)
        self.analyzed_digest[digest] = filename

        dx = Analysis()
        self.analyzed_vms[digest] = dx

        for dex in apk.get_all_dex():
            # we throw away the output... FIXME?
            self.addDEX(filename, dex, dx)

        log.debug("added APK:%s" % digest)
        return digest, apk
示例#6
0
def main():
    for path in samples():
        print(path)
        logging.error("Processing" + path)

        tests_apk = [
            "is_valid_APK", "get_filename", "get_app_name", "get_app_icon",
            "get_package", "get_androidversion_code",
            "get_androidversion_name", "get_files", "get_files_types",
            "get_files_crc32", "get_files_information", "get_raw", "get_dex",
            "get_all_dex", "get_main_activity", "get_activities",
            "get_services", "get_receivers", "get_providers",
            "get_permissions", "get_details_permissions",
            "get_requested_aosp_permissions",
            "get_requested_aosp_permissions_details",
            "get_requested_third_party_permissions",
            "get_declared_permissions", "get_declared_permissions_details",
            "get_max_sdk_version", "get_min_sdk_version",
            "get_target_sdk_version", "get_libraries",
            "get_android_manifest_axml", "get_android_manifest_xml",
            "get_android_resources", "get_signature_name",
            "get_signature_names", "get_signature", "get_signatures"
        ]

        tests_dex = [
            "get_api_version",
            "get_classes_def_item",
            "get_methods_id_item",
            "get_fields_id_item",
            "get_codes_item",
            "get_string_data_item",
            "get_debug_info_item",
            "get_header_item",
            "get_class_manager",
            "show",
            # "save",  # FIXME broken
            "get_classes_names",
            "get_classes",
            "get_all_fields",
            "get_fields",
            "get_methods",
            "get_len_methods",
            "get_strings",
            "get_format_type",
            "create_python_export",
            "get_BRANCH_DVM_OPCODES",
            "get_determineNext",
            "get_determineException",
            "print_classes_hierarchy",
            "list_classes_hierarchy",
            "get_format"
        ]

        try:
            # Testing APK
            a = APK(path)
            for t in tests_apk:
                print(t)
                x = getattr(a, t)
                try:
                    x()
                except Exception as aaa:
                    print(aaa)
                    traceback.print_exc()
                    print(path, aaa, file=sys.stderr)
                    logging.exception("{} .. {}".format(path, t))

            # Testing DEX
            dx = Analysis()
            for dex in a.get_all_dex():
                d = DalvikVMFormat(dex)
                dx.add(d)

                # Test decompilation
                for c in d.get_classes():
                    for m in c.get_methods():
                        mx = dx.get_method(m)
                        ms = DvMethod(mx)
                        try:
                            ms.process(doAST=True)
                        except Exception as aaa:
                            print(aaa)
                            traceback.print_exc()
                            print(path, aaa, file=sys.stderr)
                            logging.exception("{} .. {} .. {}".format(
                                path, c.get_name(), m.get_name()))
                        ms2 = DvMethod(mx)
                        try:
                            ms2.process(doAST=False)
                        except Exception as aaa:
                            print(aaa)
                            traceback.print_exc()
                            print(path, aaa, file=sys.stderr)
                            logging.exception("{} .. {} .. {}".format(
                                path, c.get_name(), m.get_name()))

                # DEX tests
                for t in tests_dex:
                    print(t)
                    x = getattr(d, t)
                    try:
                        x()
                    except Exception as aaa:
                        print(aaa)
                        traceback.print_exc()
                        print(path, aaa, file=sys.stderr)
                        logging.exception("{} .. {}".format(path, t))

            # Analysis Tests
            try:
                dx.create_xref()
            except Exception as aaa:
                print(aaa)
                traceback.print_exc()
                print(path, aaa, file=sys.stderr)
                logging.exception("{} .. {} at Analysis".format(path, t))

            # MethodAnalysis tests
            for m in dx.methods.values():
                for bb in m.get_basic_blocks():
                    try:
                        list(bb.get_instructions())
                    except Exception as aaa:
                        print(aaa)
                        traceback.print_exc()
                        print(path, aaa, file=sys.stderr)
                        logging.exception("{} .. {} at BasicBlock {}".format(
                            path, t, m))

        except KeyboardInterrupt:
            raise
        except FileNotFoundError:
            pass
        except Exception as e:
            print(e)
            traceback.print_exc()
            print(path, e, file=sys.stderr)
            logging.exception(path)
def main():
    for path in samples():
        print(path)
        logging.error("Processing" + path)

        tests_apk = ["is_valid_APK", "get_filename", "get_app_name", "get_app_icon",
                 "get_package", "get_androidversion_code", "get_androidversion_name",
                 "get_files", "get_files_types", "get_files_crc32", "get_files_information",
                 "get_raw", "get_dex", "get_all_dex", "get_main_activity",
                 "get_activities", "get_services", "get_receivers", "get_providers",
                 "get_permissions", "get_details_permissions", "get_requested_aosp_permissions",
                 "get_requested_aosp_permissions_details", "get_requested_third_party_permissions",
                 "get_declared_permissions", "get_declared_permissions_details", "get_max_sdk_version",
                 "get_min_sdk_version", "get_target_sdk_version", "get_libraries", "get_android_manifest_axml",
                 "get_android_manifest_xml", "get_android_resources", "get_signature_name", "get_signature_names",
                 "get_signature", "get_signatures"]

        tests_dex = ["get_api_version", "get_classes_def_item", "get_methods_id_item", "get_fields_id_item",
                     "get_codes_item", "get_string_data_item",
                     "get_debug_info_item", "get_header_item", "get_class_manager", "show",
                     "save", "get_classes_names", "get_classes",
                     "get_all_fields", "get_fields", "get_methods", "get_len_methods",
                     "get_strings", "get_format_type", "create_python_export",
                     "get_BRANCH_DVM_OPCODES", "get_determineNext",
                     "get_determineException", "print_classes_hierarchy",
                     "list_classes_hierarchy", "get_format"]

        try:
            # Testing APK
            a = APK(path)
            for t in tests_apk:
                print(t)
                x = getattr(a, t)
                try:
                    x()
                except Exception as aaa:
                    print(aaa)
                    traceback.print_exc()
                    print(path, aaa, file=sys.stderr)
                    logging.exception("{} .. {}".format(path, t))


            # Testing DEX
            for dex in a.get_all_dex():
                d = DalvikVMFormat(dex)
                dx = Analysis(d)
                d.set_vmanalysis(dx)

                # Test decompilation
                for c in d.get_classes():
                    for m in c.get_methods():
                        mx = dx.get_method(m)
                        ms = DvMethod(mx)
                        try:
                            ms.process(doAST=True)
                        except Exception as aaa:
                            print(aaa)
                            traceback.print_exc()
                            print(path, aaa, file=sys.stderr)
                            logging.exception("{} .. {} .. {}".format(path, c.get_name(), m.get_name()))
                        ms2 = DvMethod(mx)
                        try:
                            ms2.process(doAST=False)
                        except Exception as aaa:
                            print(aaa)
                            traceback.print_exc()
                            print(path, aaa, file=sys.stderr)
                            logging.exception("{} .. {} .. {}".format(path, c.get_name(), m.get_name()))

                # Other tests
                for t in tests_dex:
                    print(t)
                    x = getattr(d, t)
                    try:
                        x()
                    except Exception as aaa:
                        print(aaa)
                        traceback.print_exc()
                        print(path, aaa, file=sys.stderr)
                        logging.exception("{} .. {}".format(path, t))

        except KeyboardInterrupt:
            raise
        except FileNotFoundError:
            pass
        except Exception as e:
            print(e)
            traceback.print_exc()
            print(path, e, file=sys.stderr)
            logging.exception(path)