Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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
def vba2graph_from_vba_object(filepath):
""" vba2graph as library
Args:
filepath (string): path to file
"""
logger.info("Extracting macros from file")
if HAVE_OLETOOLS:
try:
vba = VBA_Parser(filepath)
except Exception as e:
return False
full_vba_code = ""
for (subfilename, stream_path, vba_filename, vba_code) in vba.extract_macros():
full_vba_code += 'VBA MACRO %s \n' % vba_filename
full_vba_code += '- '*39 + '\n'
full_vba_code += vba_code
vba.close()
if full_vba_code:
input_vba_content = handle_olevba_input(full_vba_code)
return input_vba_content
return False
def _ole_analysis(full_targ_path):
# This function calls a number of tools / scripts to run against document samples containing OLE data and extracts data and/or performs analysis as needed.
try:
vba_parse_Obj = VBA_Parser(full_targ_path)
except AttributeError:
return("ERROR_PARSING", "ERROR_PARSING", "ERROR_PARSING", "ERROR_PARSING")
macro_analysis_over = []
macro_analysis_info = []
if vba_parse_Obj.detect_vba_macros():
vba_macro = "Present"
# Utilizing oletools to perform analysis.
# Grabbing info from each macro.
MA_CNT = 1
for (file_name, ole_stream, vba_filename, vba_code) in vba_parse_Obj.extract_macros():
macro_analysis_over.append(str(MA_CNT)+':'+str(full_targ_path))
macro_analysis_over.append(str(MA_CNT)+":Filename :"+file_name)
macro_analysis_over.append(str(MA_CNT)+":OLE Stream :"+ole_stream)
macro_analysis_over.append(str(MA_CNT)+":VBA Filename :"+vba_filename)
macro_analysis_over.append(str(MA_CNT)+':'+vba_code)
"""
#TODO: replace print by writing to a provided output file (sys.stdout by default)
if container:
display_filename = '%s in %s' % (filename, container)
else:
display_filename = filename
safe_print('='*79)
safe_print('FILE: ' + str(display_filename))
all_code = ''
try:
#TODO: handle olefile errors, when an OLE file is malformed
import oletools
oletools.olevba.enable_logging()
if (log.getEffectiveLevel() == logging.DEBUG):
log.debug('opening {}'.format(filename))
vba = VBA_Parser(filename, data, relaxed=True)
if vba.detect_vba_macros():
# Read in document metadata.
ole = olefile.OleFileIO(filename)
try:
vm.set_metadata(ole.get_metadata())
except Exception as e:
log.warning("Reading in metadata failed. Trying fallback. " + str(e))
vm.set_metadata(meta.get_metadata_exif(orig_filename))
#print 'Contains VBA Macros:'
for (subfilename, stream_path, vba_filename, vba_code) in vba.extract_macros():
# hide attribute lines:
#TODO: option to disable attribute filtering
vba_code = filter_vba(vba_code)
safe_print('-'*79)
def doc_parsing(self, filename, filecontent):
'''
Function to parse the given data in mail content
'''
mil_attach = '' # reset var
# send data to vba parser
vbaparser = VBA_Parser(filename, data=filecontent)
# if a macro is detected
if vbaparser.detect_vba_macros():
results = vbaparser.analyze_macros()
nr = 1
self.log("VBA Macros found")
# generate report for log file
for kw_type, keyword, description in results:
if kw_type == 'Suspicious':
mil_attach += 'Macro Number %i:\n Type: %s\n Keyword: %s\n Description: %s\n' % (nr, kw_type, keyword, description)
nr += 1
mil_attach += '\nSummery:\nAutoExec keywords: %d\n' % vbaparser.nb_autoexec
mil_attach += 'Suspicious keywords: %d\n' % vbaparser.nb_suspicious
mil_attach += 'IOCs: %d\n' % vbaparser.nb_iocs
mil_attach += 'Hex obfuscated strings: %d\n' % vbaparser.nb_hexstrings
mil_attach += 'Base64 obfuscated strings: %d\n' % vbaparser.nb_base64strings
mil_attach += 'Dridex obfuscated strings: %d\n' % vbaparser.nb_dridexstrings
def get_macros():
extracted_macros = []
macro_analysis = []
tags = []
try:
vbaparser = VBA_Parser('/sample')
vbaparser.detect_vba_macros()
for (filename, stream_path, vba_filename, vba_code) in vbaparser.extract_macros():
extracted_macros.append({
"stream_path": stream_path,
"vba_filename": vba_filename,
"vba_code": vba_code
})
try:
for kw_type, keyword, description in vbaparser.analyze_macros():
macro_analysis.append({
"kw_type": kw_type,
"keyword": keyword,
"description": description
})
def check_vba(self, file_message):
filename = file_message.get_filename()
file_content = file_message.get_file_content()
vba_types = ['AutoExec', 'Suspicious', 'IOC',
'Hex String','Base64 String', 'Dridex String',
'VBA obfuscated Strings'
]
vba_suspicious_type = vba_types
vbaparser = VBA_Parser(filename, file_content)
if not vbaparser.detect_vba_macros():
return False
results = vbaparser.analyze_macros()
result = False
message = ""
for kw_type, keyword, description in results:
if kw_type in vba_suspicious_type:
result |= True
message += "\t%s : %s : %s\n" % (kw_type, keyword, description)
vbaparser.close()
return result, message
def run(self, obj, config):
username = self.current_task.user
filename = obj.filename
filedata = obj.filedata.read()
try:
vbaparser = VBA_Parser(filename, data=filedata)
except Exception, e:
self._error("Cannot parse file: %s" % str(e))
return
if vbaparser.detect_vba_macros():
for (filename, stream_path, vba_filename, vba_code) in vbaparser.extract_macros():
d = {
'OLE stream': stream_path,
'VBA filename': vba_filename,
'Length': len(vba_code)
}
result = handle_raw_data_file(
vba_code,
obj.source,
user=username,
description="VBA Macro source code for %s" % vba_filename,
title=vba_filename,