Malicious macros detection in MS-Office files using “olevba”.

SOCFortress
5 min readJun 15, 2024

--

Intro

Malicious macros in Microsoft Office documents remain a prevalent method for cyber attackers to distribute malware. By understanding the tactics used by various malware campaigns and APT groups, organizations can better defend against these threats. Implementing a combination of user education, technical controls, and detection mechanisms is key to mitigating the risk posed by macro-enabled malware.

Example of a Macro-Based Attack Workflow

  • Initial Email: The victim receives a phishing email with a seemingly legitimate attachment (e.g., invoice.doc).
  • Opening the Document: The victim opens the document, which prompts them to enable macros, often with social engineering tactics such as fake warnings.
  • Macro Execution: Once macros are enabled, the embedded macro executes and typically performs the following:
    — Download Payload: Connects to a remote server to download additional malware.
    — Execute Payload: Executes the downloaded malware, which can be anything from a remote access Trojan (RAT) to ransomware.

Notable Malware Campaigns Using Office Macros

  • Emotet: Well-known banking Trojan that evolved into a modular malware platform. It often uses macro-enabled Word documents to deliver its payload.
  • Dridex: Another banking Trojan that has been widely distributed through phishing emails. It uses Excel and Word macros to deliver its malware.
  • TrickBot: Banking Trojan and information stealer that has been distributed via macro-enabled documents.
    — Tactics: Similar to Emotet and Dridex, TrickBot campaigns often involve phishing emails with attached Word or Excel files. The macros in these files download and install TrickBot.

Olevba

Reference: https://github.com/decalage2/oletools

Olevba is a powerful tool that is part of the `oletools` package, which is used for analyzing Microsoft Office documents. It specifically focuses on identifying and extracting malicious macros embedded in Office files.

Olevba extracts and analyzes VBA Macro source code from MS Office documents (OLE and OpenXML). It can be used to parse OLE and OpenXML files such as MS Office documents (e.g. Word, Excel), to detect VBA Macros, extract their source code in clear text, and detect security-related patterns such as auto-executable macros, suspicious VBA keywords used by malware, anti-sandboxing and anti-virtualization techniques, and potential IOCs (IP addresses, URLs, executable filenames, etc). It also detects and decodes several common obfuscation methods including Hex encoding, StrReverse, Base64, Dridex, VBA expressions, and extracts IOCs from decoded strings. XLM/Excel 4 Macros are also supported in Excel and SLK files.

Here’s a detailed overview of Olevba and its capabilities:

Key Features of Olevba

1. Macro Extraction and Analysis:
— Extraction: Olevba can extract macros from Office files, including both old binary formats (such as .doc, .xls, .ppt) and the newer XML-based formats (such as .docx, .xlsx, .pptx).
— Analysis: It performs static analysis on the extracted macros to identify potentially malicious code or suspicious patterns.

2. Support for Multiple Formats:
— Olevba supports various Microsoft Office file formats, including but not limited to .doc, .docm, .xls, .xlsm, .ppt, .pptm, and their respective template formats.

3. Detection of Indicators of Compromise (IoCs):
— The tool is designed to detect common indicators of compromise, such as AutoOpen macros, suspicious API calls, obfuscated code, and known malware signatures.

4. Reporting:
— Olevba generates detailed reports on the findings, highlighting suspicious elements within the macros. This can be useful for malware analysts and incident responders.

5. Integration with Other Tools:
— Olevba can be integrated with other security tools and workflows, making it a valuable addition to automated malware analysis pipelines.

Usage

Olevba is a command-line tool, and it can be used with various options to customize the analysis process. Here are some common usage examples:

 olevba sample.doc

olevba -a sample.doc

Olevba can be installed as part of the `oletools` package using pip:

pip install oletools

After installation, `olevba` can be run from the command line.

Use Cases

  • Malware Analysis: Security researchers and malware analysts use Olevba to dissect malicious Office documents and understand the behavior of embedded macros.
  • Incident Response: Incident responders use Olevba to quickly analyze suspicious documents encountered during security incidents.
  • Threat Hunting: Olevba can be integrated into threat hunting workflows to automatically scan Office documents for potential threats.

Supported MS-Office formats

  • Word 97–2003 (.doc, .dot), Word 2007+ (.docm, .dotm)
  • Excel 97–2003 (.xls), Excel 2007+ (.xlsm, .xlsb)
  • PowerPoint 97–2003 (.ppt), PowerPoint 2007+ (.pptm, .ppsm)
  • Word/PowerPoint 2007+ XML (aka Flat OPC)
  • Word 2003 XML (.xml)
  • Word/Excel Single File Web Page / MHTML (.mht)
  • Publisher (.pub)
  • SYLK/SLK files (.slk)
  • Text file containing VBA or VBScript source code
  • Password-protected Zip archive containing any of the above

File analysis

Python script to spin up a web server and upload file for analysis:

import os
import subprocess
from flask import Flask, render_template, request, redirect, url_for, flash, send_from_directory

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = {'doc','docx','dot','dotx','docm','dotm','rtf','txt','xml','odt','xls','xlsx','xlsm','xlt','xltx','xltm','xlsb','csv','xml','ods','ppt','pptx','pptm','pot','potx','potm','pps','ppsx','ppsm','odp','mdb','accdb','mde','accde','accdt','accdr','pst','ost','msg','eml','oft','dat','one','onepkg','onetoc2','mpp','mpt','mpx','vsd','vsdx','vsdm','vss','vssx','vssm','vst','vstx','vstm'}
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024 # 10MB

def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']

@app.route('/')
def index():
return render_template('upload_form.html')

@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(filename)
result = execute_script(filename)
return render_template('result.html', result=result)
else:
flash('Invalid file type. Allowed file type is .exe')
return redirect(request.url)

def execute_script(filename):
try:
result = subprocess.check_output(['python', 'scripts/process_file.py', filename], stderr=subprocess.STDOUT, universal_newlines=True)
return result
except subprocess.CalledProcessError as e:
return e.output

if __name__ == '__main__':
app.secret_key = 'supersecretkey'
app.run(debug=True)

Python script “process_file.py”:

import sys
import subprocess
# Define the system script/command you want to execute
olevba_script = "/usr/local/bin/olevba"
if len(sys.argv) != 2:
print("Usage: process_file.py <filename>")
sys.exit(1)

filename = sys.argv[1]
print(f"Processing file: {filename}")
olevba_command = [olevba_script, "-a", filename]
try:
# Use subprocess.run to execute the system script/command
result = subprocess.run(olevba_command, shell=False, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)

print(result.stdout)

# Print the standard error (stderr) of the system script/command
print("Standard Error:")
print(result.stderr)

# Print the return code (exit code) of the system script/command
print("Return Code:", result.returncode)

except subprocess.CalledProcessError as e:
# If the system script/command returns a non-zero exit code, it raises an exception
print(f"Error: {e}")
print("Processing complete.")

Olevba Analysis

Need Help?

The functionality discussed in this post, and so much more, are available via the SOCFortress platform. Let SOCFortress help you and your team keep your infrastructure secure.

Website: https://www.socfortress.co/

Contact Us: https://www.socfortress.co/contact_form.html

--

--

SOCFortress

SOCFortress is a SaaS company that unifies Observability, Security Monitoring, Threat Intelligence and Security Orchestration, Automation, and Response (SOAR).