當前位置: 首頁>>代碼示例>>Python>>正文


Python yara.compile方法代碼示例

本文整理匯總了Python中yara.compile方法的典型用法代碼示例。如果您正苦於以下問題:Python yara.compile方法的具體用法?Python yara.compile怎麽用?Python yara.compile使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在yara的用法示例。


在下文中一共展示了yara.compile方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: do_yara

# 需要導入模塊: import yara [as 別名]
# 或者: from yara import compile [as 別名]
def do_yara(self, args):
        """Run YARA rules against the sample

Usage:          yara [<rules_path>]

If no rules file is specified, the default 'malwrsig.yar' is being used.
Those rules are then compiled and checked against the memory dump of the current emulator state (see 'dump' for further
details on this representation)"""
        if not args:
            if not self.rules:
                try:
                    self.rules = yara.compile(filepath=f"{os.path.dirname(unipacker.__file__)}/malwrsig.yar")
                    print("Default rules file used: malwrsig.yar")
                except:
                    print(f"{Fore.LIGHTRED_EX}Error: malwrsig.yar not found!{Fore.RESET}")
        else:
            self.rules = yara.compile(filepath=args)
        self.sample.unpacker.dump(self.engine.uc, self.engine.apicall_handler, self.sample)
        matches = self.rules.match("unpacked.exe")
        print(", ".join(map(str, matches))) 
開發者ID:unipacker,項目名稱:unipacker,代碼行數:22,代碼來源:shell.py

示例2: dotnet_resource_names

# 需要導入模塊: import yara [as 別名]
# 或者: from yara import compile [as 別名]
def dotnet_resource_names(self):
        """
        Read .NET Resources and return a list of resource names
        :return: list
        """
        try:
            rules = yara.compile(source='import "dotnet" rule a { condition: false }')
        except yara.SyntaxError:
            print("Error using Yara DotNet did you enable it?")
        resource_list = []

        def modules_callback(data):
            for i, resource in enumerate(data.get('resources', [])):
                resource_list.append(resource['name'])
            return yara.CALLBACK_CONTINUE

        rules.match(data=self.file_data, modules_callback=modules_callback)
        return resource_list 
開發者ID:kevthehermit,項目名稱:RATDecoders,代碼行數:20,代碼來源:fileparser.py

示例3: dotnet_resource_by_name

# 需要導入模塊: import yara [as 別名]
# 或者: from yara import compile [as 別名]
def dotnet_resource_by_name(self, resource_name):
        """
        Extract a .NET Resource by name
        :param resource_name:
        :return:
        """
        try:
            rules = yara.compile(source='import "dotnet" rule a { condition: false }')
        except yara.SyntaxError:
            print("Error using Yara DotNet did you enable it?")

        def modules_callback(data):
            for i, resource in enumerate(data.get('resources', [])):
                if resource['name'] == resource_name:
                    offset = resource['offset']
                    length = resource['length']
                    self.res_data = self.file_data[offset:offset + length]


            return yara.CALLBACK_CONTINUE

        rules.match(data=self.file_data, modules_callback=modules_callback)
        return self.res_data 
開發者ID:kevthehermit,項目名稱:RATDecoders,代碼行數:25,代碼來源:fileparser.py

示例4: elf_list_sections

# 需要導入模塊: import yara [as 別名]
# 或者: from yara import compile [as 別名]
def elf_list_sections(self):
        """
        Read a list of sections from an elf binary
        :return: list of section names
        """
        try:
            rules = yara.compile(source='import "elf" rule a { condition: false }')
        except yara.SyntaxError:
            print("Error using Yara ELF did you enable it?")
        section_names = []

        def modules_callback(data):
            for i, section in enumerate(data.get('sections', [])):
                section_names.append(section['name'].decode('utf-8'))
            return yara.CALLBACK_CONTINUE

        rules.match(data=self.file_data, modules_callback=modules_callback)

        return section_names 
開發者ID:kevthehermit,項目名稱:RATDecoders,代碼行數:21,代碼來源:fileparser.py

示例5: elf_section_by_name

# 需要導入模塊: import yara [as 別名]
# 或者: from yara import compile [as 別名]
def elf_section_by_name(self, resource_name):
        """
        Extract an elf section by name
        :param resource_name:
        :return:
        """
        try:
            rules = yara.compile(source='import "elf" rule a { condition: false }')
        except yara.SyntaxError:
            print("Error using Yara ELF did you enable it?")

        def modules_callback(data):
            for i, section in enumerate(data.get('sections', [])):
                if section['name'].decode('utf-8') == resource_name:
                    offset = section['offset']
                    length = section['size']
                    self.res_data = self.file_data[offset:offset + length]
            return yara.CALLBACK_CONTINUE

        rules.match(data=self.file_data, modules_callback=modules_callback)
        return self.res_data 
開發者ID:kevthehermit,項目名稱:RATDecoders,代碼行數:23,代碼來源:fileparser.py

示例6: __init__

# 需要導入模塊: import yara [as 別名]
# 或者: from yara import compile [as 別名]
def __init__(self, *args, **kwargs):
        """Scan using yara signatures."""
        super(YaraScanMixin, self).__init__(*args, **kwargs)

        # Compile the yara rules in advance.
        if self.plugin_args.yara_expression:
            self.rules_source = self.plugin_args.yara_expression
            self.rules = yara.compile(source=self.rules_source)

        elif self.plugin_args.binary_string:
            self.compile_rule(
                'rule r1 {strings: $a = {%s} condition: $a}' %
                self.plugin_args.binary_string)

        elif self.plugin_args.string:
            self.compile_rule(
                'rule r1 {strings: $a = "%s" condition: $a}' %
                self.plugin_args.string)

        elif self.plugin_args.yara_file:
            self.compile_rule(open(self.plugin_args.yara_file).read())

        elif not self.ignore_required:
            raise plugin.PluginError("You must specify a yara rule file or "
                                     "string to match.") 
開發者ID:google,項目名稱:rekall,代碼行數:27,代碼來源:yarascanner.py

示例7: calculate

# 需要導入模塊: import yara [as 別名]
# 或者: from yara import compile [as 別名]
def calculate(self):

        ## we need this module imported
        if not has_yara:
            debug.error("Please install Yara from https://plusvic.github.io/yara/")

        linux_common.set_plugin_members(self)
        tasks = linux_pslist.linux_pslist.calculate(self)

        for task in tasks:
            if str(task.comm) != "truecrypt":
                continue

            space = task.get_process_address_space()
            if not space:
                continue
    
            rules = yara.compile(sources = {
               'n' : 'rule r1 {strings: $a = {40 00 00 00 ?? 00 00 00} condition: $a}'
               })

            scanner = PassphraseScanner(task = task, rules = rules)
            for address, password in scanner.scan():
                yield task, address, password 
開發者ID:virtualrealitysystems,項目名稱:aumfor,代碼行數:26,代碼來源:linux_truecrypt.py

示例8: calculate

# 需要導入模塊: import yara [as 別名]
# 或者: from yara import compile [as 別名]
def calculate(self):

        if not has_yara:
            debug.error("Yara must be installed for this plugin")

        addr_space = utils.load_as(self._config)
        
        if not self.is_valid_profile(addr_space.profile):
            debug.error("This command does not support the selected profile.")
        
        rules = yara.compile(sources = signatures)

        for task in self.filter_tasks(tasks.pslist(addr_space)):
            scanner = malfind.VadYaraScanner(task = task, rules = rules)

            for hit, address in scanner.scan():
                vad_base_addr = self.get_vad_base(task, address)
                if address - vad_base_addr > 0x1000:
                    continue

                yield task, vad_base_addr 
開發者ID:virtualrealitysystems,項目名稱:aumfor,代碼行數:23,代碼來源:poisonivy.py

示例9: YARACompile

# 需要導入模塊: import yara [as 別名]
# 或者: from yara import compile [as 別名]
def YARACompile(ruledata):
    if ruledata.startswith('#'):
        if ruledata.startswith('#h#'):
            rule = binascii.a2b_hex(ruledata[3:])
        elif ruledata.startswith('#b#'):
            rule = binascii.a2b_base64(ruledata[3:])
        elif ruledata.startswith('#s#'):
            rule = 'rule string {strings: $a = "%s" ascii wide nocase condition: $a}' % ruledata[3:]
        elif ruledata.startswith('#q#'):
            rule = ruledata[3:].replace("'", '"')
        else:
            rule = ruledata[1:]
        return yara.compile(source=rule)
    else:
        dFilepaths = {}
        if os.path.isdir(ruledata):
            for root, dirs, files in os.walk(ruledata):
                for file in files:
                    filename = os.path.join(root, file)
                    dFilepaths[filename] = filename
        else:
            for filename in ProcessAt(ruledata):
                dFilepaths[filename] = filename
        return yara.compile(filepaths=dFilepaths) 
開發者ID:IntegralDefense,項目名稱:ACE,代碼行數:26,代碼來源:pdf-parser.py

示例10: test_yara_rule

# 需要導入模塊: import yara [as 別名]
# 或者: from yara import compile [as 別名]
def test_yara_rule(rule):
    '''
    try to match the given rule against each segment in the current exectuable.
    raise TestDidntRunError if its not possible to import the YARA library.
    return True if there's at least one match, False otherwise.
    '''
    try:
        import yara
    except ImportError:
        logger.warning("can't test rule: failed to import python-yara")
        raise TestDidntRunError('python-yara not available')

    r = yara.compile(source=rule)

    for segment in get_segments():
        matches = r.match(data=segment.buf)
        if len(matches) > 0:
            logger.info('generated rule matches section: {segment.name}')
            return True
    return False 
開發者ID:williballenthin,項目名稱:idawilli,代碼行數:22,代碼來源:yara_fn.py

示例11: main

# 需要導入模塊: import yara [as 別名]
# 或者: from yara import compile [as 別名]
def main(yara_rules, path_to_scan, output):
    if os.path.isdir(yara_rules):
        yrules = yara.compile(yara_rules)
    else:
        yrules = yara.compile(filepath=yara_rules)

    if os.path.isdir(path_to_scan):
        match_info = process_directory(yrules, path_to_scan)
    else:
        match_info = process_file(yrules, path_to_scan)

    columns = ['rule_name', 'hit_value', 'hit_offset', 'file_name',
               'rule_string', 'rule_tag']

    if output is None:
        write_stdout(columns, match_info)
    else:
        write_csv(output, columns, match_info) 
開發者ID:PacktPublishing,項目名稱:Python-Digital-Forensics-Cookbook,代碼行數:20,代碼來源:yara_scanner.py

示例12: test_yara_rule

# 需要導入模塊: import yara [as 別名]
# 或者: from yara import compile [as 別名]
def test_yara_rule(rule):
    '''
    try to match the given rule against each segment in the current exectuable.
    raise TestDidntRunError if its not possible to import the YARA library.
    return True if there's at least one match, False otherwise.
    '''
    try:
        import yara
    except ImportError:
        logger.warning("can't test rule: failed to import python-yara")
        raise TestDidntRunError('python-yara not available')

    r = yara.compile(source=rule)

    for segment in get_segments():
        if segment.buf is not None:
            matches = r.match(data=segment.buf)
            if len(matches) > 0:
                logger.info('generated rule matches section: {:s}'.format(segment.name))
                return True
    return False 
開發者ID:TakahiroHaruyama,項目名稱:ida_haru,代碼行數:23,代碼來源:yara_fn.py

示例13: auto

# 需要導入模塊: import yara [as 別名]
# 或者: from yara import compile [as 別名]
def auto(self):
        if not HAVE_YARA:
            self.log('error', "Missing dependency, install yara (see http://plusvic.github.io/yara/)")
            return

        if not __sessions__.is_set():
            self.log('error', "No session opened")
            return

        rules = yara.compile(os.path.join(CIRTKIT_ROOT, 'data/yara/rats.yara'))
        for match in rules.match(__sessions__.current.file.path):
            if 'family' in match.meta:
                self.log('info', "Automatically detected supported RAT {0}".format(match.rule))
                self.get_config(match.meta['family'])
                return

        self.log('info', "No known RAT detected") 
開發者ID:opensourcesec,項目名稱:CIRTKit,代碼行數:19,代碼來源:rat.py

示例14: is_malware

# 需要導入模塊: import yara [as 別名]
# 或者: from yara import compile [as 別名]
def is_malware(filename):
    if not os.path.exists("rules_compiled/malware"):
        os.mkdir("rules_compiled/malware")
    for n in os.listdir("rules/malware/"):
        if not os.path.isdir("./" + n):
            try:
                rule = yara.compile("rules/malware/" + n)
                rule.save("rules_compiled/malware/" + n)
                rule = yara.load("rules_compiled/malware/" + n)
                m = rule.match(filename)
                if m:
                    return m
            except:
                pass  # internal fatal error or warning
        else:
            pass


# Added by Yang 
開發者ID:secrary,項目名稱:SSMA,代碼行數:21,代碼來源:check.py

示例15: run

# 需要導入模塊: import yara [as 別名]
# 或者: from yara import compile [as 別名]
def run(self):
        results = {'matches': {}}

        all_rules = list_dir(self.rules)

        for r in all_rules:
            rule = yara.compile(r)
            matches = rule.match(data=open(self.artifact['path'], 'rb').read())

            for m in matches:
                if m.rule not in results['matches'].keys():
                    results['matches'][m.rule] = []
                for tag in m.tags:
                    if tag not in results['matches'][m.rule]:
                        results['matches'][m.rule].append(tag)

        self.artifact['data']['yara'] = results 
開發者ID:InQuest,項目名稱:omnibus,代碼行數:19,代碼來源:yara.py


注:本文中的yara.compile方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。