Exemple #1
0
    def insert(self, specific_name, mod_count=1):
        '''Insert an hardware based on 'specfic_name' into manifest.xml file'''
        if not isinstance(specific_name, str) and not os.path.isdir(
                self.disassembly_root):
            raise TypeError("Type error:")

        if mod_count < 0:
            raise ValueError(
                "The amount of insertion cannot be smaller than 0.")

        manifest_tree = xu.get_xmltree_by_ET(
            os.path.join(self.disassembly_root, droid_modification.MANIFEST))

        info, flag, new_manifest_tree = xu.insert_perm_manifest(
            manifest_tree, self.comp_type, specific_name, mod_count)

        xu.dump_xml(
            os.path.join(self.disassembly_root, droid_modification.MANIFEST),
            new_manifest_tree)

        if self.verbose:
            if flag:
                logger.info(info)
                logger.info(
                    'Hardware insertion: Successfully insert \'{}\' into \'{}/androidmanifest.xml\''
                    .format(specific_name,
                            os.path.basename(self.disassembly_root)))
            else:
                logger.warn(info)
Exemple #2
0
    def insert(self, specific_name, mod_count=1):
        """
        Insert an component based on 'specfic_name' into manifest.xml file
        """
        if not isinstance(specific_name, str) and not os.path.isdir(
                self.disassembly_root):
            raise ValueError("Value error: require str type of variables.")

        manifest_tree = xu.get_xmltree_by_ET(
            os.path.join(self.disassembly_root, droid_modification.MANIFEST))

        info, flag, new_manifest_tree = xu.insert_comp_manifest(
            manifest_tree, self.comp_type, specific_name, mod_count)

        xu.dump_xml(
            os.path.join(self.disassembly_root, droid_modification.MANIFEST),
            new_manifest_tree)

        if self.verbose:
            if flag:
                logger.info(info)
                logger.info(
                    "'{}' insertion: Successfully insert activity '{}' into '{}'/androidmanifest.xml"
                    .format(self.comp_type, specific_name,
                            os.path.basename(self.disassembly_root)))
            else:
                logger.warn(info)
                raise e.ModifyFileException(info)
Exemple #3
0
    def remove(self, specific_name, mod_count=-1):
        """
        change the denoted component name to a random string
        mod_count = -1 indicates that all the corresponding elements will be changed
        """

        # step 1: modify the corresponding name in AndroidManifest.xml

        if not isinstance(specific_name, str) and not os.path.exists(
                self.disassembly_root):
            raise ValueError("Value error:")

        # mod_count = -1 change name of all the specified components

        manifest_tree = xu.get_xmltree_by_ET(
            os.path.join(self.disassembly_root, droid_modification.MANIFEST))

        info, flag, new_comp_name, new_manifest_tree = xu.rename_comp_manifest(
            manifest_tree, self.comp_type, specific_name)
        xu.dump_xml(
            os.path.join(self.disassembly_root, droid_modification.MANIFEST),
            new_manifest_tree)

        if self.verbose:
            if flag:
                logger.info(info)
                logger.info(
                    "'{}' name changing: Successfully change name '{}' to '{}' of '{}'/androidmanifest.xml"
                    .format(self.comp_type, specific_name, new_comp_name,
                            os.path.basename(self.disassembly_root)))
            else:
                logger.warn(info + ": {}/androidmanifest.xml".format(
                    os.path.basename(self.disassembly_root)))
                return

        # step 2: modify .smali files accordingly
        package_name = manifest_tree.getroot().get('package')
        smali_paths = du.get_smali_paths(self.disassembly_root)
        related_smali_paths = set(
            du.find_smali_w_name(smali_paths, specific_name))
        du.change_source_name(related_smali_paths, specific_name,
                              new_comp_name)
        changed_class_names = set(
            du.change_class_name(related_smali_paths, specific_name,
                                 new_comp_name, package_name))

        # Change class instantiation
        if len(changed_class_names) > 0:
            du.change_instantition_name(smali_paths, changed_class_names,
                                        specific_name, new_comp_name,
                                        package_name)

        if self.verbose:
            logger.info(
                "'{}' name changing: Successfully change '{}' name in smali files"
                .format(self.comp_type, specific_name))

        # step 3: modify all .xml files accordingly
        if len(changed_class_names) > 0:
            xml_paths = xu.get_xml_paths(self.disassembly_root)
            # todo: change asset xml
            # xu.change_xml(xml_paths, changed_class_names,
            #              specific_name, new_comp_name, package_name)

        if self.verbose:
            logger.info(
                "'{}' name changing: Successfully change '{}' name in xml files"
                .format(self.comp_type, specific_name))

        # step 4: modify folder and file names
        self._rename_files(smali_paths, specific_name, new_comp_name)
Exemple #4
0
    def insert(self,
               class_name=None,
               method_name=None,
               params=None,
               is_params_smali=False,
               mod_count=1,
               force=True,
               elem_name=None):
        """
        insert samli code based on class name and method
        :param class_name: the class name,
        :param method_name: method belongs to the class
        :param is_smali: Does the params has the smali type, e.g., Landroid/... or I, B, Z etc.
        :param mod_count: the maximum modification number
        :param force: enforce the insertion even that there is no smali code provided
        :param elem_name: negect
        """
        if elem_name:
            raise ValueError(
                " elem_name is neglected, please fill the arguments 'class_name' and 'method_name'."
            )

        mod_count = int(mod_count)
        if mod_count < 0:
            raise ValueError(
                " The amount of insertion cannot be smaller than 0.")

        # get java fashion
        if '/' in class_name:
            class_name = class_name.replace('/', '.')
        if class_name.startswith('L'):
            class_name = class_name.lstrip('L')
        if class_name.endswith(';'):
            class_name = class_name.rstrip(';')

        key = class_name + '+' + method_name
        if key in self.api_smali_mapping_dict.keys():
            smali_block_list = self.api_smali_mapping_dict[key]
        else:
            logger.warning("No such key '{}.{}'".format(
                class_name, method_name))
            if force:
                logger.warning(
                    "Forcing implementation: Trying generic template for public method."
                )
                smali_block_list = [
                    self.generate_generic_smali(class_name, method_name,
                                                params, is_params_smali)
                ]
            else:
                logger.warn("No obfuscated code generated.")
                print("No obfuscated code generated.")
                return 1

        smali_path_selected = []
        if len(self.partial_smali_paths) > 0:
            smali_path_selected = du.select_smali_file(
                self.partial_smali_paths, num=1)[0]

        if len(smali_path_selected) == 0:
            logger.warn("No files provided.")
            print("No files provided.")
            raise e.ModifyFileException(
                "Cannot find an avaiable file to insert string {}".format(
                    elem_name))

        try:
            import random
            random.seed(2345)
            assert isinstance(smali_block_list, list)
            used_random_numbers = []

            for t in range(mod_count):
                block_idx = random.choice(range(len(smali_block_list)))

                rdm_number = random.choice(range(23456))
                count = 0
                while rdm_number in used_random_numbers and count < 10:
                    rdm_number = random.choice(range(23456))
                    count = count + 1
                used_random_numbers.append(rdm_number)
                smali_block_code = du.change_method_name(
                    smali_block_list[block_idx], rdm_number)
                du.insert_dead_code(smali_path_selected, smali_block_code)
                if self.verbose:
                    print("Times:{}/{}".format(t + 1, mod_count))
                    print(
                        "API Insert: Successfully insert the method '{}.{}' in to file '{}'"
                        .format(class_name, method_name, smali_path_selected))

        except Exception as ex:
            raise e.ModifyFileException(
                str(ex) +
                ":Failed to insert method '{}' into file '{}'".format(
                    method_name, smali_path_selected))
        logger.info(
            "API Insert: Successfully insert the method '{}.{}' in to file '{}'"
            .format(class_name, method_name, smali_path_selected))