本文整理汇总了Python中oletools.olevba.VBA_Parser方法的典型用法代码示例。如果您正苦于以下问题:Python olevba.VBA_Parser方法的具体用法?Python olevba.VBA_Parser怎么用?Python olevba.VBA_Parser使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类oletools.olevba
的用法示例。
在下文中一共展示了olevba.VBA_Parser方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: has_office_macros_with_suspicious_keyword
# 需要导入模块: from oletools import olevba [as 别名]
# 或者: from oletools.olevba import VBA_Parser [as 别名]
def has_office_macros_with_suspicious_keyword(self, suspicious_keywords):
"""
Detects macros with supplied suspicious keywords in Microsoft Office documents.
@param suspicious_keywords: List of suspicious keyword regexes.
@return: True if macros with keywords where found, otherwise False.
If VBA_Parser crashes it returns False too.
"""
vba = self.report.get('vba')
if vba is None:
return False
suspicious = False
for word in suspicious_keywords:
if re.search(word, vba):
suspicious = True
break
return suspicious
示例2: getZipFiles
# 需要导入模块: from oletools import olevba [as 别名]
# 或者: from oletools.olevba import VBA_Parser [as 别名]
def getZipFiles(self, attachment, filename):
'''
Checks a zip for parseable files and extracts all macros
'''
log.debug("[%d] Found attachment with archive extension - file name: %s" % (self.id, filename))
vba_code_all_modules = ''
file_object = StringIO.StringIO(attachment)
files_in_zip = self.zipwalk(file_object,0,[])
for zip_name, zip_data in files_in_zip:
# checks if it is a file
zip_mem_data = StringIO.StringIO(zip_data)
name, ext = os.path.splitext(zip_name.filename)
# send to the VBA_Parser
# fallback with extensions - maybe removed in future releases
if olefile.isOleFile(zip_mem_data) or ext in EXTENSIONS:
log.info("[%d] File in zip detected! Name: %s - check for VBA" % (self.id, zip_name.filename))
vba_parser = olevba.VBA_Parser(filename=zip_name.filename, data=zip_data)
for (subfilename, stream_path, vba_filename, vba_code) in vba_parser.extract_all_macros():
vba_code_all_modules += vba_code + '\n'
return vba_code_all_modules
示例3: processFile
# 需要导入模块: from oletools import olevba [as 别名]
# 或者: from oletools.olevba import VBA_Parser [as 别名]
def processFile(fileName, args, output_file=sys.stdout):
# TODO - Handle VBA3 documents
print('Processing file: {}'.format(fileName), file=output_file)
vbaParser = None
try:
vbaParser = VBA_Parser(fileName)
if vbaParser.ole_file is None:
for subFile in vbaParser.ole_subfiles:
processProject(subFile, args, output_file=output_file)
else:
processProject(vbaParser, args, output_file=output_file)
except Exception as e:
print('Error: {}.'.format(e), file=sys.stderr)
if vbaParser:
vbaParser.close()
示例4: has_office_macros
# 需要导入模块: from oletools import olevba [as 别名]
# 或者: from oletools.olevba import VBA_Parser [as 别名]
def has_office_macros(self):
"""
Detects macros in Microsoft Office documents.
@return: True if macros where found, otherwise False.
If VBA_Parser crashes it returns False too.
"""
return self.report.get('has_macros', False)
示例5: EXTRACT_VBA_MACRO
# 需要导入模块: from oletools import olevba [as 别名]
# 或者: from oletools.olevba import VBA_Parser [as 别名]
def EXTRACT_VBA_MACRO(s, buff):
EXTRACT_MACRO = {}
counter = 0
### TODO: REMOVE THIS WORKAROUND ONCE MODULE AUTHOR FIXES CODE ###
### Reference: http://stackoverflow.com/questions/32261679/strange-issue-using-logging-module-in-python/32264445#32264445
### Reference: https://bitbucket.org/decalage/oletools/issues/26/use-of-logger
### /dev/null used instead of NullHandler for 2.6 compatibility
logging.getLogger('workaround').root.addHandler(logging.FileHandler('/dev/null'))
###
vba = VBA_Parser('None', data=buff)
if not vba.detect_vba_macros():
return EXTRACT_MACRO
for (filename, stream_path, vba_filename, vba_code) in vba.extract_macros():
CHILD_MACRO = OrderedDict([('OLE Stream', stream_path),
('VBA Filename', vba_filename.decode('ascii', 'ignore')),
('Scan', scan_macro(vba_code)),
('Buffer', vba_code)])
EXTRACT_MACRO['Object_%s' % counter] = CHILD_MACRO
counter += 1
return EXTRACT_MACRO
示例6: get_vba
# 需要导入模块: from oletools import olevba [as 别名]
# 或者: from oletools.olevba import VBA_Parser [as 别名]
def get_vba(self, myfile, source='filepath'):
"""
Given a file, parses out the stream paths, vba code, and vba filenames for each.
:param myfile: filename
:param source: type of data being passed in. Either "filepath" to indicate we need to read from disk or
"filecontents" meaning that the file contents are being passed as a parameter.
:return: pandas Series that can be used in concert with the pandas DataFrame apply method
"""
if source == 'filepath':
filedata = open(myfile, 'rb').read()
else:
filedata = myfile
try:
vbaparser = VBA_Parser('mmbot', data=filedata)
pathnames = ''
if vbaparser.detect_vba_macros():
filenameslist = []
pathnameslist = []
vbacodelist = []
for (filename, stream_path, filename_vba, extracted_vba) in vbaparser.extract_macros():
vbacodelist.append(return_decoded_value(extracted_vba))
if not pathnames:
pathnameslist.append(return_decoded_value(stream_path))
filenameslist.append(return_decoded_value(filename_vba))
else:
pathnameslist.append(return_decoded_value(stream_path))
filenameslist.append(return_decoded_value(filename_vba))
allcode = "\n\n\n\n".join(vbacodelist)
filenames = ", ".join(filenameslist)
pathnames = ", ".join(pathnameslist)
else:
pathnames = 'No VBA Macros found'
filenames = 'No VBA Macros found'
allcode = 'No VBA Macros found'
except Exception as e:
pathnames = 'Error:' + str(e)
filenames = 'Error:' + str(e)
allcode = 'Error:' + str(e)
return pd.Series({'extracted_vba': allcode, 'stream_path': pathnames, 'filename_vba': filenames})
示例7: parse_vba
# 需要导入模块: from oletools import olevba [as 别名]
# 或者: from oletools.olevba import VBA_Parser [as 别名]
def parse_vba(self, save_path):
save = False
vba = VBA_Parser(__sessions__.current.file.path)
# Check for Macros
if not vba.detect_vba_macros():
self.log('error', "No Macro's Detected")
return
self.log('info', "Macro's Detected")
try:
run_rows = []
word_rows = []
pattern_rows = []
for (filename, stream_path, vba_filename, vba_code) in vba.extract_macros():
self.log('info', "Stream Details")
self.log('item', "OLE Stream: {0}".format(string_clean(stream_path)))
self.log('item', "VBA Filename: {0}".format(string_clean(vba_filename)))
autoexec_keywords = detect_autoexec(vba_code)
if autoexec_keywords:
for keyword, description in autoexec_keywords:
run_rows.append([keyword, description])
# Match Keyword Types
suspicious_keywords = detect_suspicious(vba_code)
if suspicious_keywords:
for keyword, description in suspicious_keywords:
word_rows.append([keyword, description])
# Match IOCs
patterns = detect_patterns(vba_code)
if patterns:
for pattern_type, value in patterns:
pattern_rows.append([pattern_type, value])
# Save the code to external File
if save_path:
try:
with open(save_path, 'a') as out:
out.write(vba_code)
save = True
except:
self.log('Error', "Unable to write to {0}".format(save_path))
return
# Print all Tables together
self.log('info', "AutoRun Macros Found")
self.log('table', dict(header=['KeyWord', 'Description'], rows=run_rows))
self.log('info', "Suspicious Keywords Found")
self.log('table', dict(header=['KeyWord', 'Description'], rows=word_rows))
self.log('info', "Suspicious Patterns Found")
self.log('table', dict(header=['Pattern', 'Value'], rows=pattern_rows))
if save:
self.log('success', "Writing VBA Code to {0}".format(save_path))
except:
self.log('Error', "Unable to Process File")
# Close the file
vba.close()
# Main starts here
示例8: each
# 需要导入模块: from oletools import olevba [as 别名]
# 或者: from oletools.olevba import VBA_Parser [as 别名]
def each(self, target):
self.results = {
'macros': u'',
'analysis': {
'AutoExec': [],
'Suspicious': [],
'IOC': [],
'Hex String': [],
'Base64 String': [],
'Dridex string': [],
'VBA string': [],
'Form String': []
}
}
vba = olevba.VBA_Parser(target)
# code is inspired by 'reveal' method in olevba
analysis = vba.analyze_macros(show_decoded_strings=True)
# extract all macros code
for (_, _, _, vba_code) in vba.extract_all_macros():
self.results['macros'] += vba_code.decode('utf-8', errors='replace') + '\n'
# extract all form strings
for (_, _, form_string) in vba.extract_form_strings():
self.results['analysis']['Form String'].append(form_string.decode('utf-8', errors='replace'))
# extract all analysis
if analysis:
analysis = sorted(analysis, key=lambda type_decoded_encoded: len(type_decoded_encoded[2]), reverse=True)
for kw_type, keyword, description in analysis:
# and replace obfuscated strings
if kw_type in ['VBA string', 'Dridex string', 'Base64 String', 'Hex String']:
if olevba.is_printable(keyword):
keyword = keyword.replace('"', '""')
self.results['macros'] = self.results['macros'].replace(description, '"%s"' % keyword)
self.results['analysis'][kw_type].append((keyword.decode('utf-8', errors='replace'), description.decode('utf-8', errors='replace')))
else:
self.results['analysis'][kw_type].append((keyword, description))
return len(self.results['macros']) > 0
示例9: get_report
# 需要导入模块: from oletools import olevba [as 别名]
# 或者: from oletools.olevba import VBA_Parser [as 别名]
def get_report(self):
""" Return oletools report or create if not already cached. """
if self.sample.oletools_report is not None:
return self.sample.oletools_report
report = {
'autoexec': [],
'suspicious' : [],
}
file_path = self.sample.file_path
try:
vbaparser = VBA_Parser(file_path)
# VBA_Parser reports macros for office documents
report['has_macros'] = vbaparser.detect_vba_macros() or vbaparser.detect_xlm_macros()
try:
report['vba'] = vbaparser.reveal()
except TypeError:
# office document with no macros
pass
all_macros = vbaparser.extract_all_macros()
if (report['has_macros'] and len(all_macros) == 1
and isinstance(all_macros[0], tuple)
and len(all_macros[0]) >= 3
and all_macros[0][2] == file_path):
logger.warning(
"Buggy oletools version detected, result overridden. May "
"lead to false negatives, please update to fixed version")
report['has_macros'] = False
if vbaparser.detect_vba_macros():
vb_code = vbaparser.extract_all_macros()
for (_, _, _, c) in vb_code:
autoexec = detect_autoexec(c)
if len(autoexec) >= 1:
report['autoexec'].append(autoexec[0])
suspicious = detect_suspicious(c)
if len(suspicious) >= 1:
report['suspicious'].append(suspicious[0])
vbaparser.close()
except IOError:
raise
except (TypeError, FileOpenError):
# The given file is not an office document.
pass
except Exception as error:
logger.exception(error)
report = OletoolsReport(report)
self.sample.register_oletools_report(report)
return report