Exemplo n.º 1
0
    def testAPK(self):
        a, d, dx = AnalyzeAPK("examples/tests/a2dp.Vol_137.apk")

        self.assertEqual(len(list(dx.get_internal_classes())), 1353)  # checked by reading the dex header
        self.assertEqual(len(dx.get_strings()), 1564)
        self.assertEqual(len(list(dx.get_methods())), 12792)  # according to DEX Header 12795
        self.assertEqual(len(list(dx.get_fields())), 3033)  # According to DEX Header 4005
        self.assertEqual(len(list(dx.get_external_classes())), 388)

        for cls in dx.get_external_classes():
            self.assertEqual(cls.name[0], 'L')
            self.assertEqual(cls.name[-1], ';')

        # Filter all support libraries
        self.assertEqual(len(list(dx.find_classes("^(?!Landroid/support).*;$"))), 512)
        self.assertEqual(len(list(dx.find_classes("^(?!Landroid/support).*;$", no_external=True))), 124)

        # Find all constructors by method name
        self.assertEqual(len(list(dx.find_methods(classname="^(?!Landroid).*;$", methodname="<init>", descriptor=r"^\(.+\).*$"))), 138)
        self.assertEqual(len(list(dx.find_methods(classname="^(?!Landroid).*;$", methodname="<init>", descriptor=r"^\(.+\).*$", no_external=True))), 94)

        # Find url like strings
        self.assertEqual(len(list(dx.find_strings(r".*:\/\/.*"))), 15)

        # find String fields
        self.assertEqual(len(list(dx.find_fields(classname="^(?!Landroid).*;$", fieldtype=r"Ljava\/lang\/String;"))), 63)
def test_intent_writes_init():
    a, d, dx = AnalyzeAPK("../tests/apks/DocViewer_Benign.apk")
    x = get_implicit_intents(apk=a, d=d, dx=dx)
    actions = ["android.intent.action.SEND"]
    for i in actions:
        assert i in [bi.action for bi in x]
    assert len(x) == len(actions)
Exemplo n.º 3
0
def retrieve_source_code(path, subpath):
    """
    retrieve source codes from dataset path and store as files
    :param path: dataset path
    :param subpath: path to single apk
    :return:
    """
    try:
        # analyse apk with androguard
        a, d, _ = AnalyzeAPK(path)
        # do not re-analyse files
        if os.path.isfile(subpath + '/' + a.get_package() + '.txt'):
            # only analyse new apks to save time
            print('file exists')
            return
        with open(subpath + '/' + a.get_package() + '.txt', 'w+') as code_file:
            for dalvik in d:
                for c_name in dalvik.get_classes_names():
                    if c_name.startswith('L' + a.package.replace('.', '/')):
                        # retrieve java code
                        # print(dalvik.get_class(c_name).get_source())
                        for method in dalvik.get_class(c_name).get_methods():
                            # method = m.get_method()
                            code = ""
                            byte_code = method.get_code()
                            if byte_code is not None:
                                byte_code = byte_code.get_bc()
                                for i in byte_code.get_instructions():
                                    code += i.get_name() + ' ' + i.get_output(
                                    ) + '\n'
                            code_file.write(code.encode('utf-8') + '\n')
    except Exception:
        print('ignoring file')
Exemplo n.º 4
0
def main():
    global parser
    options = parser.parse_args()
    log.debug("[+] options: %s'" % options)

    # Log_Level
    try:
        log.setLevel(options.log_level.upper())
    except:
        parser.error("Please specify a valid log level")

    # Input
    print "[+] Loading the APK file..."
    a, d, x = AnalyzeAPK(options.input)
    package_name = grab_application_package_name(a)

    # Analysis
    data = perform_analysis(options.input, a, d, x,
                            options.with_playstore_lookup)

    # Synthesis
    if options.display_report:
        # Brace yourself, a massive dump is coming
        dump_analysis_results(data, sys.stdout)

    generate_report(package_name, data, options.verbose, options.report,
                    options.output)
def test_intent_writes():
    a, d, dx = AnalyzeAPK("../tests/apks/Send_WeatherApp_StaticIntent.apk")
    x = get_implicit_intents(apk=a, d=d, dx=dx)
    actions = ["readcontacts", "stop", "gettasks", "sms", "start"]
    for i in actions:
        assert i in [bi.action for bi in x]
    assert len(x) == len(actions)
def Get_APK_Words(apkfile):
    a = apk.APK(apkfile, False, 'r', None, 2)
    d = dvm.DalvikVMFormat(a.get_dex())
    vmx = analysis.Analysis(d)
    dp = decompiler.DecompilerDAD(d, vmx)  # DAD是androguard内部的decompiler
    a1, d1, dx = AnalyzeAPK(apkfile)
    CFG = nx.DiGraph()
    class_code_dic, is_amd_class_code_dic = Build_APK_Corpus(apkfile)
    for k in d.get_classes():  # 用于遍历每一个class
        all_orig_methods = []  # 用于统计一个class里面的所有的method
        # print(type(k))
        print('class_name+super_name::' + k.get_name() + ':' +
              k.get_superclassname())
        for m in dx.find_methods(
                classname=k.get_name()):  # 用于将一个class里面所有的原始方法提取到
            orig_method = m.get_method()
            if isinstance(orig_method, ExternalMethod):
                is_this_external = True
            else:
                is_this_external = False
            CFG.add_node(orig_method, external=is_this_external)
            if not isinstance(orig_method, ExternalMethod):
                all_orig_methods.append(orig_method)  # 用于得到所有的原始方法
        for m in dx.find_methods(
                classname=k.get_name()):  # 用于遍历一个class里面的所有的方法
            orig_method = m.get_method()
            if not isinstance(orig_method, ExternalMethod):
                if (orig_method.get_name() in all_callback) or (
                        orig_method.get_name()
                        in APK_Method_Key_Words.key_registers):
                    print('method_name+method_descriptor::' +
                          orig_method.get_name() +
                          orig_method.get_descriptor())
                    print(class_code_dic[k.get_name()][
                        orig_method.get_name() + orig_method.get_descriptor()])
Exemplo n.º 7
0
def main():
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(help='Plugins')

    # Init plugins
    plugins = init_plugins()
    for p in sorted(plugins.keys()):
        sp = subparsers.add_parser(plugins[p].name,
                                   help=plugins[p].description)
        plugins[p].add_arguments(sp)
        sp.add_argument('APK', help='an APK file')
        sp.set_defaults(plugin=p)

    args = parser.parse_args()
    if hasattr(args, 'plugin'):
        if not os.path.isfile(args.APK):
            print("File not found")
            sys.exit(1)

        ret_type = androconf.is_android(args.APK)
        if ret_type != "APK":
            print("Not an APK file")
            sys.exit(1)

        a, d, dx = AnalyzeAPK(args.APK)
        plugins[args.plugin].run(args, a, d, dx)
    else:
        parser.print_help()
Exemplo n.º 8
0
def main():
    global parser
    options = parser.parse_args()
    log.debug("[+] options: %s'" % options)

    # Log_Level
    try:
        log.setLevel(options.log_level.upper())
    except:
        parser.error("Please specify a valid log level")

    # Input
    print("[+] Loading the APK file...")
    a, d, x = AnalyzeAPK(options.input)
    package_name = grab_application_package_name(a)

    # Get Application Detail
    app_detail = grab_application_detail(package_name)

    # Analysis
    data = perform_analysis(options.input, a, d, x,
                            options.with_playstore_lookup)

    # Synthesis
    # if options.display_report:
    #     Brace yourself, a massive dump is coming
    #     dump_analysis_results(data,sys.stdout)
    #
    remain_permission = check_permissions(app_detail, data)

    data[3]['androidmanifest.xml'][2] = ('permissions', remain_permission)

    generate_report(package_name, data, options.verbose, options.report,
                    options.output)
Exemplo n.º 9
0
    def testPermissions(self):
        """Test the get_permissions and get_permission_usage methods"""
        a, _, dx = AnalyzeAPK("examples/android/TestsAndroguard/bin/TestActivity.apk")

        api_level = a.get_effective_target_sdk_version()
        used_permissions = ['android.permission.BROADCAST_STICKY', 'android.permission.ACCESS_NETWORK_STATE']
        sticky_meths = ['onMenuItemSelected', 'navigateUpTo']
        network_meths = ['getNetworkInfo', 'getActiveNetworkInfo', 'isActiveNetworkMetered']

        for _, perm in dx.get_permissions(api_level):
            for p in perm:
                self.assertIn(p, used_permissions)
        meths = [x.name for x in dx.get_permission_usage('android.permission.BROADCAST_STICKY', api_level)]
        self.assertListEqual(sorted(meths), sorted(sticky_meths))
        meths = [x.name for x in dx.get_permission_usage('android.permission.ACCESS_NETWORK_STATE', api_level)]
        self.assertListEqual(sorted(meths), sorted(network_meths))

        # Should give same result if no API level is given
        for _, perm in dx.get_permissions():
            for p in perm:
                self.assertIn(p, used_permissions)
        meths = [x.name for x in dx.get_permission_usage('android.permission.BROADCAST_STICKY')]
        self.assertListEqual(sorted(meths), sorted(sticky_meths))
        meths = [x.name for x in dx.get_permission_usage('android.permission.ACCESS_NETWORK_STATE')]
        self.assertListEqual(sorted(meths), sorted(network_meths))
Exemplo n.º 10
0
def list_calls_with_permissions(file, permission_map_file):
    """ List all API calls which require a permissions in file (according the
        mapping from Felt et al. CSS 2011 in APICalls.txt).
    """

    df = DataFrame.from_csv(permission_map_file, sep='\t')
    a, d, dx = AnalyzeAPK(file)
    for method in d.get_methods():
        for i in method.get_instructions():
            if i.get_name()[:6] == "invoke":
                # get method desc
                call = i.get_output(0).split(',')[-1].strip()
                # remove return value
                call = call[:call.index(')') + 1]
                # split in class and method
                call = call.split('->')
                method_class = type(call[0])
                ins_method, params = call[1].split('(')
                params = ','.join(parse_parameters(params.replace(')', '')))
                apicall = "{0}.{1}({2})".format(method_class, ins_method,
                                                params)
                try:
                    print(df.ix[apicall]["Permission(s)"])
                    print(apicall)
                except:
                    pass
Exemplo n.º 11
0
    def testMultidex(self):
        a, d, dx = AnalyzeAPK("examples/tests/multidex/multidex.apk")

        cls = list(map(lambda x: x.get_vm_class().get_name(),
                       dx.get_classes()))
        self.assertIn('Lcom/foobar/foo/Foobar;', cls)
        self.assertIn('Lcom/blafoo/bar/Blafoo;', cls)
Exemplo n.º 12
0
def extract_prcs(apk):
    """Analyzes the apk and extracts permission-requiring code segments"""

    a, _, dx = AnalyzeAPK(apk)
    app = APK(a, dx)
    prcs_list = app.prcs

    path_to_apk = Path(apk)
    dir_to_apk = path_to_apk.parent
    app_name = app.get_app_name()

    app_dir = dir_to_apk / app_name
    os.makedirs(app_dir)

    for i, el in enumerate(prcs_list):
        filepath = app_dir / f"PRCS_{str(i)}.java"

        with open(filepath, 'w') as f:
            header = f"class PRCS_{str(i)} {{\n"
            footer = "\n}"
            try:
                f.write(header)
                if type(el) == tuple:
                    for each_hop in el:
                        src_code = each_hop.get_source_code()
                        f.write(src_code)
                else:
                    src_code = el.get_source_code()
                    f.write(src_code)
                f.write(footer)
            except Exception as e:
                print(f"Exception {e} occurred at index {i}")
Exemplo n.º 13
0
def main():
    global parser
    options = parser.parse_args()
    log.debug("[+] options: %s'" % options)
    # CJCS: next two lines were used for debugging purposes!!!
    print("[+] options: %s'" % options)
    print("FILENAME -> " + options.input)

    # Log_Level
    try:
        log.setLevel(options.log_level.upper())
    except:
        parser.error("Please specify a valid log level")

    # Input
    print("[+] Loading the APK file...")
    a, d, x = AnalyzeAPK(options.input)
    package_name = grab_application_package_name(a)

    # Analysis
    data = perform_analysis(options.input, a, d, x,
                            options.with_playstore_lookup)

    # Synthesis
    if options.display_report:
        # Brace yourself, a massive dump is coming
        dump_analysis_results(data, sys.stdout)

    #CJCS: get the filename, not the package name
    filename = os.path.basename(options.input)
    #generate_report(package_name, data, options.verbose, options.report, options.output)
    generate_report(filename, data, options.verbose, options.report,
                    options.output)
Exemplo n.º 14
0
def get_graph_and_nodes_ins_for_apk(apk_file, bc, draw_graph=False):
    a, d, dx = AnalyzeAPK(apk_file)
    CFG = dx.get_call_graph()

    delete_external_and_xref0_nodes(CFG)
    delete_init_method(CFG, dx)
    delete_external_and_xref0_nodes(CFG)

    ins_seqs, nodes = {}, CFG.nodes
    for orig_method in nodes:
        m_a = dx.get_method(orig_method)
        ins_seq = get_instruction_seq_for_func(m_a, [str(n) for n in nodes])
        ins_seqs[orig_method] = bc.encode([ins_seq])

    if draw_graph:
        pos = nx.spring_layout(CFG)
        nx.draw_networkx_nodes(CFG, pos=pos, node_color='b', nodelist=nodes)
        nx.draw_networkx_edges(CFG, pos, arrow=True)
        nx.draw_networkx_labels(
            CFG, pos=pos, labels={x: "{}".format(ins_seqs[x])
                                  for x in nodes})
        plt.draw()
        plt.show()
    methods = list(ins_seqs.keys())
    adj_dict, L = CFG.adj, len(methods)
    adj = [(i, 1, j) for i in range(L) for j in range(L)
           if methods[j] in adj_dict[methods[i]].keys()]
    node_feature = {}
    for i in range(L):
        if methods[i] in ins_seqs:
            node_feature[i] = ins_seqs[methods[i]]
    return adj, node_feature
Exemplo n.º 15
0
def write_one_apk_source(apkfile):
    a = apk.APK(apkfile, False, 'r', None, 2)
    d = dvm.DalvikVMFormat(a.get_dex())
    vmx = analysis.Analysis(d)
    dp = decompiler.DecompilerDAD(d, vmx)  # DAD是androguard内部的decompiler
    a1, d1, dx = AnalyzeAPK(apkfile)
    CFG = nx.DiGraph()
    with open(
            'F:\\2018年第一学年科研\\APK科研\\数据集\\Word2vec_ao_yuliaoku\\test\\successed_1.txt',
            'w') as txtData:
        for k in d.get_classes():
            print('class_name:' + k.get_name())
            txtData.writelines(dp.get_source_class(k))
            for m in dx.find_methods(classname=k.get_name()):
                orig_method = m.get_method()
                if isinstance(orig_method, ExternalMethod):
                    is_this_external = True
                else:
                    is_this_external = False
                CFG.add_node(orig_method, external=is_this_external)
                if is_this_external == False:  # 用于获取一个class里面的所有方法
                    print('orig::' + orig_method.get_name())
                else:
                    print('orig+external::' + orig_method.get_name())
                for other_class, callee, offset in m.get_xref_to():
                    if isinstance(callee, ExternalMethod):
                        is_external = True
                    else:
                        is_external = False
                    if callee not in CFG.node:
                        CFG.add_node(callee, external=is_external)
                        if is_external == False:
                            print('external+callee::' + callee.get_name())
                        else:
                            print('callee:' + callee.get_name())
Exemplo n.º 16
0
def Deal_one_apk_new(apkfile):
    a = apk.APK(apkfile, False, 'r', None, 2)
    d = dvm.DalvikVMFormat(a.get_dex())
    vmx = analysis.Analysis(d)
    dp = decompiler.DecompilerDAD(d, vmx)  # DAD是androguard内部的decompiler
    a1, d1, dx = AnalyzeAPK(apkfile)
    CFG = nx.DiGraph()
    apk_word = []
    for k in d.get_classes():
        print('class_name:' + k.get_name())
        # print(dp.get_source_class(k))
        for m in dx.find_methods(classname=k.get_name()):
            orig_method = m.get_method()
            # print(type(orig_method))
            if isinstance(orig_method, ExternalMethod):
                is_this_external = True
            else:
                is_this_external = False
            CFG.add_node(orig_method, external=is_this_external)
            if is_this_external == False:  # 用于获取一个class里面的所有方法
                print('orig::' + orig_method.get_name())
            else:
                print('orig+externalmethod::' + orig_method.get_name())
            for other_class, callee, offset in m.get_xref_to():
                if isinstance(callee, ExternalMethod):
                    is_external = True
                else:
                    is_external = False
                if callee not in CFG.node:
                    CFG.add_node(callee, external=is_external)
                    if is_external == False:
                        print('external+callee::' + callee.get_name())
                    else:
                        print('callee:' + callee.get_name())
Exemplo n.º 17
0
def static_code_analysis(apk_name):
    a, d, dx = AnalyzeAPK("C:/Users/KK/Desktop/Final Year Project/APK/" +
                          apk_name)
    methods = []
    methods1 = []

    #All methods that an application uses- Internal and External
    for c in dx.get_classes():
        methods1 = (list(map(lambda x: x.name, c.get_methods())))
        methods += methods1
    methods = set(methods)

    #Mapping: {API:List of Permissions}
    mapping = load_permission_mappings(a.get_min_sdk_version())

    print(a.get_min_sdk_version())
    #A dictionary : {External API: list of permissions}
    external_apis_permissions = {}

    for key, value in mapping.items():
        for m in methods:
            if m == key.split('-')[1]:
                external_apis_permissions.update({key: value})

    #If permission_dangerous not in external_apis_permissions
    permissions_from_mapping = []
    for key, value in external_apis_permissions.items():
        for x in value:
            permissions_from_mapping.append(x)
            permissions_from_mapping = list(set(permissions_from_mapping))

    return permissions_from_mapping
Exemplo n.º 18
0
def interact(session=False, apk=None):
    """
    Start an interactive shell
    :param session:
    :param apk:
    :return:
    """
    from androguard.core.androconf import ANDROGUARD_VERSION, CONF
    from IPython.terminal.embed import InteractiveShellEmbed
    from traitlets.config import Config

    from androguard.misc import init_print_colors, AnalyzeAPK
    from androguard.session import Session

    if session:
        CONF["SESSION"] = Session(export_ipython=True)

    if apk:
        print("Loading apk {}...".format(os.path.basename(apk)))
        print("Please be patient, this might take a while.")
        # TODO we can export fancy aliases for those as well...
        a, d, dx = AnalyzeAPK(apk)

    cfg = Config()
    _version_string = "Androguard version {}".format(ANDROGUARD_VERSION)
    ipshell = InteractiveShellEmbed(
        config=cfg, banner1="{} started".format(_version_string))
    init_print_colors()
    ipshell()
Exemplo n.º 19
0
    def __init__(self, apk_path):
        sdk_path = os.path.join(os.path.expanduser("~"),
                                "Android/Sdk/platforms/")
        if not os.path.exists(sdk_path):
            print(
                "cannot run test_apk_loading since there is no Android SDK folder"
            )
            sys.exit(1)

        lifter = Lifter(path_apk, input_format="apk", android_sdk=sdk_path)

        self.p = turi.Project(apk_path,
                              input_format='apk',
                              android_sdk=sdk_path,
                              lifter=lifter)

        self.apk_path = apk_path
        _, _, self.dx = AnalyzeAPK(apk_path)
        self.call_graph = self.dx.get_call_graph()

        self.avg_math_ops = self.get_avg_math_ops()
        self.sweet_spots = []
        self.sweet_objs = []
        self.reran_proc = None
        self.has_dominant = False
        self.entropies = {}
Exemplo n.º 20
0
    def each(self, target):
        self.results = dict()
        self.results['urls'] = []
        try:
            apk, vm, vm_analysis = AnalyzeAPK(target)
        except:
            self.log('error', '[+] AnalyzeAPK failed, running AnalyzeDex')
            apk = None
            vm, vm_analysis = AnalyzeDex(target)
            self.results['dex'] = True

        strings = []
        for v in vm:
            strings.extend(v.get_strings())
        for s in strings:
            for regex_str in r:
                match = re.search(regex_str, s, re.IGNORECASE)
                if match:
                    self.results['urls'].append(match.group(0))
        self.results['urls'] = list(set(self.results['urls']))

        # Add observables
        for url in self.results['urls']:
            self.add_ioc(url)
        return True
Exemplo n.º 21
0
def loadApp(dir, cls):
    files = glob.glob(dir)
    files = sorted(files)
    done = read_log(cls)
    count = 0
    print("\nSearching folder ", dir)
    if set(files).issubset(set(done)):
        print("\nNo new files to extract")
        return
    for f in files:
        done = read_log(cls)
        if f in done:
            continue
        print("\n\nOpening file ", f)
        try:
            a, d, dx = AnalyzeAPK(f)
            name = a.get_package()
        except:
            print("\nError opening ", f)
            done.append(f)
            continue
        yield (name, a, d, dx)
        del a
        del d
        del dx
        print(name, "extracted successfully...")
        print("\n\n", len(done) + 1, "files extracted. \n\n")
        write_log(cls, f)
def test_tainted_shared_preferences_reads():
    a, d, dx = AnalyzeAPK("../tests/apks/Rec_RSS_Reader_SharedPreferences.apk")
    x = get_shared_preferences_reads(apk=a, d=d, dx=dx)
    assert len(x) == 1
    assert x[0].package == 'com.acid.colluding.filemanager'
    assert x[0].preference_file == 'PrefsFile'
    assert x[0].operation == 'read'
Exemplo n.º 23
0
 def __init__(self, apk_path, output_dir):
     self.apk_path = apk_path
     # output directory
     self.output_dir = output_dir + "/"
     self.packed_files = dict()
     self.a, self.d, self.dx = AnalyzeAPK(self.apk_path)
     self.detected_malware = dict()
Exemplo n.º 24
0
    def each(self, target):
        self.results = dict()

        try:
            apk, vm, vm_analysis = AnalyzeAPK(target)

            # First, get basic information about the APK
            self.results['name'] = apk.get_app_name()
            self.results['package'] = apk.get_package()
            self.results['permissions'] = apk.get_permissions()
            self.results['main_activity'] = apk.get_main_activity()
            self.results['receivers'] = apk.get_receivers()
            self.results['services'] = apk.get_services()
            self.results['main_activity_content'] = vm.get_class("L{};".format(
                self.results['main_activity']).replace('.', '/')).get_source()
        except:
            apk = None
            vm, vm_analysis = AnalyzeDex(target)
            self.results['dex'] = True

        # Then, run all the APK Plugins in order to see if this is a known malware
        for plugin in APKPlugin.__subclasses__():
            plugin = plugin(target, apk, vm, vm_analysis)
            plugin.apply(self)

        return True
Exemplo n.º 25
0
    def __init__(self, apk_path, output_dir):
        self.known_packages = ['com.google.services', 'com.android.playup']

        self.known_domains_ips = [
            "cvcws.ponethus.com", "svc.ponethus.com", "www.ponethus.com",
            "webmail.ponethus.com", "nampriknum.net", "www.nampriknum.net",
            "svc.nampriknum.net", "svcws.nampriknum.net", "svc.somtum.today",
            "svcws.somtum.today", "www.somtum.today", "somtum.today",
            "shop.databit.today", "svc.databit.today", "test.databit.today",
            "www.databit.today", "admin.databit.today", "cendata.today",
            "svc.cendata.today", "svcws.cendata.today", "www.cendata.today",
            "47.90.206.185"
        ]  # 47.90.206.185: vpn IP

        self.known_strings = [
            "dumpsys activity | grep \"Run #\" | grep -v ScreenCaptureImageActivity | head -n 1",
            "jp.naver.line.android/.activity.chathistory.ChatHistoryActivity",
            "com.whatsapp/.voipcalling.VoipActivityV2",
            "OrbotVpnThread",
            "OrbotVpn",
            "jp.naver.line.android/com.linecorp.voip.ui.freecall.FreeCallActivity",
            "com.android.playup",
            "/Bots/get_update",
            # endpoints
            "/Commands/comm_getfunction",
            "/Bots/get_update",
            "/Commands/delete_comm",
            "/Filesautosend/upload_file",
            "/Filesautosend/delete_file",
            "/Messages/mess_update",
            "/Transbots/bots_add",
            "/Authen/verify_token"
        ]

        # common wolfRat classes in 3 analyzed versions
        self.known_classes = [
            'Lcom/dao/BotsDao;', 'Lcom/dao/CommandDao;',
            'Lcom/dao/ConnectionSvcws;', 'Lcom/dao/FilesAutoSendDao;',
            'Lcom/dao/FilesDao;', 'Lcom/dao/MessagesDao;',
            'Lcom/dao/TransBotsDao;', 'Lcom/dao/UserDao;',
            'Lcom/daoimp/BotsDaoImpl;', 'Lcom/daoimp/CommandDaoImpl;',
            'Lcom/daoimp/DAOFactory;', 'Lcom/daoimp/FilesAutoSendDaoImpl;',
            'Lcom/daoimp/FilesDaoImpl;', 'Lcom/daoimp/MessagesDaoImpl;',
            'Lcom/daoimp/TransBotsDaoImpl;', 'Lcom/daoimp/UserDaoImpl;',
            'Lcom/model/Bots;', 'Lcom/model/Commands;', 'Lcom/model/Files;',
            'Lcom/model/FilesAutoSend;', 'Lcom/model/Messages;',
            'Lcom/model/SmsBox;', 'Lcom/model/TransBots;', 'Lcom/model/User;',
            'Lcom/utils/CheckCapture;', 'Lcom/utils/CheckNetwork;',
            'Lcom/utils/DataService;', 'Lcom/utils/NetTask;',
            'Lcom/utils/RestClient;'
        ]

        self.apk_path = apk_path
        # output directory
        self.output_dir = output_dir + "/"
        self.packed_files = dict()

        self.a, self.d, self.dx = AnalyzeAPK(self.apk_path)
        self.score = 0
Exemplo n.º 26
0
    def each(self, target):
        self.results = dict(name=None,
                            files=[],
                            package=None,
                            permissions=[],
                            declared_permissions=[],
                            main_activity=None,
                            activities=[],
                            receivers=[],
                            services=[],
                            manifest=None,
                            libraries=[],
                            main_activity_content=None,
                            internal_classes=[])

        try:
            apk, vm, vm_analysis = AnalyzeAPK(target)

            # First, get basic information about the APK
            self.results['name'] = apk.get_app_name()
            self.results['files'] = apk.get_files_types()
            self.results['package'] = apk.get_package()
            self.results['permissions'] = apk.get_details_permissions()
            self.results[
                'declared_permissions'] = apk.get_declared_permissions_details(
                )
            self.results['main_activity'] = apk.get_main_activity()
            self.results['activities'] = apk.get_activities()
            self.results['receivers'] = apk.get_receivers()
            self.results['services'] = apk.get_services()
            self.results['manifest'] = apk.get_android_manifest_axml().get_xml(
            )
            self.results['libraries'] = list(apk.get_libraries())
            self.results['main_activity_content'] = None
            self.results['internal_classes'] = []
            try:
                self.results['main_activity_content'] = self.results[
                    'main_activity_content'] = vm[0].get_class(
                        "L{};".format(self.results['main_activity']).replace(
                            '.', '/')).get_source()
            except:
                self.log('error', traceback.print_exc())

            try:
                self.results['internal_classes'] = self._get_internal_classes(
                    vm_analysis)
                self._store_internal_classes()
            except:
                self.log('error', traceback.print_exc())

            # Then, run all the APK Plugins in order to see if this is a known malware
            for plugin in APKPlugin.__subclasses__():
                plugin = plugin(target, apk, vm, vm_analysis)
                plugin.apply(self)

        except:
            self.log('error', traceback.print_exc())

        return True
Exemplo n.º 27
0
def apk_find_api_calls(apk_full_path, quick=False):

    log_tag = apk_full_path.split("/")[-1].replace(".apk", "").rsplit(
        "-", 1)[0][:35].ljust(38)

    def print_function(*args):
        x = tuple([log_tag] + list(args))
        print(*x)

    start_timestamp = datetime.datetime.now()

    #sdk_implicit_edges = AndroidSdkImplicitEdges("ImplicitEdges.txt",
    #                                             "ImplicitEdges.pk",
    #                                             print_func=print_function)
    sdk_implicit_edges = AndroidSdkImplicitEdges("/home/me/ImplicitEdges.txt",
                                                 "/home/me/ImplicitEdges.pk",
                                                 print_func=print_function)

    print_function("-> ", apk_full_path)
    apk, _, analysis = AnalyzeAPK(apk_full_path)
    cfg = analysis.get_call_graph()
    print_function("apk loaded")

    num_edges_1 = len(cfg.edges)
    num_nodes_1 = len(cfg.nodes)

    inh = InheritanceMap(analysis, print_func=print_function)

    if not quick:
        inh.run(cfg)

        num_edges_2 = len(cfg.edges)
        num_nodes_2 = len(cfg.nodes)

        print_function("+%d edges, +%d nodes" %
                       (num_edges_2 - num_edges_1, num_nodes_2 - num_nodes_1))

        adder = CFGImplicitEdgeAdder(sdk_implicit_edges,
                                     cfg,
                                     analysis,
                                     print_func=print_function)
        adder.run()

        num_edges_3 = len(cfg.edges)
        num_nodes_3 = len(cfg.nodes)

        print_function("+%d edges, +%d nodes" %
                       (num_edges_3 - num_edges_2, num_nodes_3 - num_nodes_2))

    apk_analyzer = AppAPICallAnalyzer(apk, analysis, cfg, inh, print_function)
    apk_analyzer.run()

    api_calls_and_count = apk_analyzer.get_api_calls_count()

    print_function(
        "time total: %.1f minutes" %
        ((datetime.datetime.now() - start_timestamp).total_seconds() / 60))

    return api_calls_and_count
Exemplo n.º 28
0
def GetFromInstructions(ApkDirectoryPath, ApkFile, PMap, RequestedPermissionList):
    '''
    Get required permissions, used Apis and HTTP information for an ApkFile.
    Reloaded version of GetPermissions.

    :param String ApkDirectoryPath
    :param String ApkFile
    :param PScoutMapping.PScoutMapping PMap
    :param RequestedPermissionList List([String])
    :return UsedPermissions
    :rtype Set([String])
    :return RestrictedApiSet
    :rtype Set([String])
    :return SuspiciousApiSet
    :rtype Set([String])
    :return URLDomainSet
    :rtype Set([String])
    '''

    UsedPermissions = []
    RestrictedApiList = []
    SuspiciousApiList = []
    URLDomainList = []
    try:
        ApkFile = os.path.abspath(ApkFile)
        a, dd, dx = AnalyzeAPK(ApkFile)
    except Exception as e:
        print(str(e))
        print("Executing Androlyze on " + ApkFile + " Failed.")
        return

    if not isinstance(dd, list):
        dd = [dd]

    for i, d in enumerate(dd):
        for method in d.get_methods():
            g = dx.get_method(method)
            for BasicBlock in g.get_basic_blocks().get():
                Instructions = BasicBlockAttrBuilder.GetBasicBlockDalvikCode(BasicBlock)
                Apis, SuspiciousApis = BasicBlockAttrBuilder.GetInvokedAndroidApis(Instructions)
                Permissions, RestrictedApis = BasicBlockAttrBuilder.GetPermissionsAndApis(Apis, PMap,
                                                                                          RequestedPermissionList,
                                                                                          SuspiciousApiList)
                UsedPermissions.extend(Permissions)
                RestrictedApiList.extend(RestrictedApis)
                SuspiciousApiList.extend(SuspiciousApis)
                for Instruction in Instructions:
                    URLSearch = re.search(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',
                                          Instruction,
                                          re.IGNORECASE)

                    if URLSearch:
                        URL = URLSearch.group()
                        Domain = re.sub(r"(.*://)?([^/?]+).*", "\g<1>\g<2>", URL)
                        URLDomainList.append(Domain)

    # Got Set S6, S5, S7 described in Drebin paper

    return UsedPermissions, RestrictedApiList, SuspiciousApiList, URLDomainList
Exemplo n.º 29
0
def vuln_analysis_retry_worker(app):
    try:
        filename = get_filepath(app.package_name, app.md5)
        (myPackage, d, dx) = AnalyzeAPK(filename)
        vuln_analysis(app, myPackage, d, dx)
    except Exception as poof:
        logging.error("Exception en analisis de vulnerabilidades: " +
                      repr(poof))
def main():
    for apk in apks:
        a, d, dx = AnalyzeAPK(apk)
        d.set_vmanalysis(dx)
        apis=get_api(d)
        insert_apis(apis)
        str=get_apis_as_str(apis)
        print(str)