本文整理汇总了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)))
示例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
示例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
示例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
示例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
示例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.")
示例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
示例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
示例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)
示例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
示例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)
示例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
示例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")
示例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
示例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