Self Assessment

Living off the Land : The Mechanics of Remote Template Injection Attack

Published On : 2025-01-04
Share :
Living off the Land : The Mechanics of Remote Template Injection Attack

EXECUTIVE SUMMARY

At CYFIRMA, our mission is to keep you informed about the latest cyber threats and the tactics employed by malicious actors to exploit vulnerabilities. From time to time, we also dive deep into both common and emerging techniques used by threat actors at various stages of an attack. This report examines the Remote Template Injection attack technique, offering a thorough understanding of its purpose, how threat actors leverage it, its execution process, and the potential risks it poses. We also explore the broader implications of these attacks and provide actionable recommendations to help mitigate the threat.

Remote Template Injection is a sophisticated attack vector leveraging Microsoft Word’s template functionality to deliver malicious payloads. Threat actors utilize this method to bypass traditional security controls, such as email gateways and endpoint detection solutions. This technique has been observed in various campaigns attributed to prominent threat actors, underlining its effectiveness and persistence in the wild. This article provides an in-depth examination of the attack method and mitigation strategies. By staying informed and proactive, you can safeguard yourself against this pervasive threat and mitigate its detrimental effects.

INTRODUCTION

Remote Template Injection is a technique used by attackers to exploit Microsoft Word’s ability to load templates from remote locations. By embedding a link to a malicious template, attackers can execute code on a victim’s system without the decoy document itself being flagged as malicious. This attack is especially effective in spear-phishing campaigns, where attackers exploit trust to secretly execute malicious macros.

With the introduction of Office Open XML (OOXML) formats, Microsoft Office introduced the capability to embed resources within documents. This is facilitated through a mechanism called “Relationships,” which defines links between a source component and a target resource within an XML file. These relationships are stored in .rels XML files within the document package. Adversaries have exploited this feature to execute attacks. By injecting a malicious URL hosting a harmful template into the .rels XML file, attackers can weaponize Office documents to execute their malicious payloads.

KEY POINTS

  • Exploitation of Trust: Leverages Word’s legitimate template functionality.
  • Bypass Traditional Defenses: The decoy document is clean, enabling it to bypass security mechanisms.
  • Malicious Payload Execution: Executes payloads hosted on remote servers upon opening the document.
  • Attribution: Observed in campaigns by advanced persistent threats (APTs) like FIN7 and others.

Background Information

Microsoft Office documents, despite being non-binary files, should be thoroughly analysed, as they often serve as the initial stage in an attack leading to malware execution. These documents are a popular choice for threat actors due to their widespread use and familiarity. Typically, a malicious Office file is attached to an email designed to appear as legitimate communication. By leveraging social engineering techniques, attackers manipulate victims into opening the attachment, setting the stage for malware delivery and execution.

The OLE2 format was commonly used in Microsoft Office 97–2003 documents. Familiar file extensions such as .doc, .xls, and .ppt are based on the OLE format. Another format Office Open XML format (OOXML) introduced with Microsoft Office 2007 is a zipped, XML-based format developed by Microsoft and is now used for all modern Office files. Common extensions associated with this format include .docx, .xlsx, and .pptx. While OOXML files share similarities with OLE files in structure, there are notable differences:

  • Each directory within an OOXML file contains an .xml file.
  • A mandatory file named [Content_Types].xml must reside in the root directory of the archive.
  • OOXML files cannot natively contain VBA macros.
  • These files can include various objects, such as images, OLE objects, PE files, media files, and more.
  • The relationships between objects are managed and defined in files with the .rels extension.

Documents can be weaponized in multiple ways to deliver malware and launch attacks. One common method is through Office Macros. Macros, written in Visual Basic for Applications (VBA) or recorded directly in Microsoft Office, are designed to automate tasks but can also be exploited by attackers. These scripts provide access to local system resources, enabling malicious activities, such as modifying files or executing further attack stages.

Challenges faced by malicious actors with Macros:

  • File Types with Macros: OOXML files like .docx, .xlsx, and .pptx cannot store macros. Macro-enabled files (e.g., .dotm, .docm, .xlsm) use the letter m in their extensions for easier identification and to mitigate risk.
  • Security Measures: Microsoft includes protections like disabling macros by default, manual enablement with restrictions, and opening files in Protected View, which prevents the execution of commands.

So, another method devised is remote template file injection, where a .docx file based on OOXML format fetches and executes a malicious template from a remote location. However, the .docx file doesn’t contain macros directly, enabling content triggers malware execution.

Remote Template Injection

Microsoft Word includes a feature that allows users to create documents linked to templates. These templates can be stored locally or retrieved from a remote server whenever the document is accessed. Exploiting this functionality, attackers can host malicious Word Template files (.dotm) on their servers, embedding harmful macros within them. When a victim opens the Word document, it automatically fetches the malicious template from the attacker’s server and executes the embedded code, potentially compromising the victim’s system. The key benefit of this technique is that the decoy Word document reaching the victim’s system appears harmless.

The technique also known as Living off the Land (LotL) technique has transformed the threat landscape by shifting the focus from delivering executable files to exploiting existing files and resources on the target system. This method allows attackers to evade detection by security controls, such as antivirus software, by blending in with legitimate system activity.

Recognizing the risks posed by macro-enabled Office documents, many organizations have implemented measures to block them. However, attackers can bypass these defenses by delivering a seemingly harmless DOCX file, which cannot directly store or execute macros. The threat emerges when the DOCX file references a remote DOTM template. Upon opening the document, any malicious macro embedded in the remote DOTM file is fetched and executed, enabling the attack. A DOTM file serves as both a template and a container for executing macros. By crafting a DOCX file that loads a remote DOTM template containing malicious macros, attackers can achieve code execution while potentially evading security controls.

The templates can be hosted locally or fetched from remote locations. Attackers exploit this functionality by:

  1. Creating a Malicious Template: A .dotm file containing macros that execute a payload.
  2. Hosting the Template Remotely: Placing the malicious template on an attacker-controlled server.
  3. Embedding the Template in a Decoy Document: A .docx file is configured to fetch the malicious template upon opening.
  4. Distributing the Document: The decoy document is sent to targets via phishing emails or other delivery methods.

Upon opening the document and enabling content, Word fetches the remote template, executing the embedded malicious macros. These macros can deliver malware, establish persistence, or exfiltrate data.

As an example, refer to our previously published report, “Exploiting Document Templates: Stego-Campaign Deploying Remcos RAT and Agent Tesla” which details the similar technique used by the threat actors. In this case, the attackers employ template injection, manipulating settings to instruct the docx file to access a specific target URL (e.g., “http[:]//someofthelovercantbuyhappinessfromthe@shtu[.]be/5f0848”) when the victim opens the document. This action triggers the download of an RTF file named “mydearcutieireallyloveryoualwaysforgreatthingshappenedinsideofusforloverstogetreadyforthepointounderstandtheupdationforproccess.doc” from “http[:]//107[.]173[.]4[.]15/gbn/mydearcutieireallyloveryoualwaysforgreatthingshappenedinsideofusforloverstogetreadyforthepointounderstandtheupdationforproccess.doc.” The RTF file contains embedded malicious code that exploits the vulnerability on the victim machine, triggering the download of additional payloads as part of the attack chain.

Using a method known as “Relationships,” the connection between a source part and a target resource is defined within an XML file. These relationships are stored in a .rels file, an XML document included in the Office document package. They achieve this by injecting a URL pointing to a malicious template into the .rels XML file, enabling the execution of harmful actions.

The following steps outline the implementation of the attack, intended solely for educational and learning purposes:

Create Malicious Template (.dotm):

  • Develop a VBA macro with payload delivery code.
  • Save the template as a .dotm file.

Step-by-Step Guide to Create the Malicious Template:

Create a New Document

  • Open Microsoft Word and create a new blank document.

Enable the Developer Tab (if not enabled)

  • Go to File > Options.
  • Select Customize Ribbon.
  • Check the box for Developer under Main Tabs and click OK.

Open the VBA Editor

  • On the Developer tab, click Visual Basic, or press Alt + F11.

Insert the Document_Open Macro

  • In the VBA editor, find your document in the left-hand pane under Project (Document1).
  • Double-click ThisDocument to open its code window.
  • Paste the following Macro code, it will open a notepad file on opening the dotm file, we are just creating:

   Private Sub Document_Open()
   Dim NotepadPath As String
   NotepadPath = “notepad.exe”
   Shell NotepadPath, vbNormalFocus
   End Sub

Note: Here we create the macro which is non-malicious; the purpose is only to demonstrate its functionality. Otherwise, a malicious macro could contain code to perform harmful operations on the system, including: Fetching malicious payloads from remote servers and executing them, stealing sensitive information, such as credentials, stored files, or clipboard data, and sending it to an attacker-controlled server, capturing user keystrokes to harvest passwords and other sensitive information, modifying system settings, disabling antivirus software, or making persistent changes to maintain access, etc.

Save the Document as a Macro-Enabled File

  • Go to File > Save As in Word.
  • Select Word Macro-Enabled Template Document (*.dotm) from the “Save as type” dropdown.
  • Provide a file name and save it.

Close and Reopen the Document

  • Close the document and reopen it.
  • The macro should automatically execute and open Notepad when the document is opened.

Enable Macros

  • If Word displays a Security Warning about macros, click Enable Content to allow the macro to run.

1. Host the Template:

  • Upload the .dotm file to a web server.

2. Modify Decoy Document:

  • Create a .docx file.
  • Change the settings.xml.rels file to point to the malicious template’s URL.
  • Repackage the files into a .docx format.

Create Weaponized Benign DOCX File

  • Create a New Document:
    • Open Microsoft Word and create a new document.
    • Save the document as a .docx file.

Locate settings.xml.rels:

  • Navigate to the directory containing your .docx file and use the following commands to access its contents:

cd <document_path>

mv <name>.docx <name>.zip (Renaming the file name and extension)

expand-archive ./<name>.zip (Extract the files)

  • Depending on the Microsoft Word version, the settings.xml.rels file can be found in <name>/word/_rels/settings.xml.rels.

Edit the File:

  • Open settings.xml.rels in a text editor.
  • Modify the Target attribute to point to the URL where the template file is hosted.

Repackage the File:

  • Save your changes and repackage the files using Compress-Archive or a GUI tool like 7-zip.
  • Rename the .zip file back to .docx.

3. Distribute the Document:

  • Use phishing emails or other channels to deliver the decoy document.

Variation in the Attack:

Researchers also observed the use of camouflage techniques to obfuscate URLs in malicious documents. These documents often contain decimal IP addresses or use unconventional URL formats to fetch remotely hosted templates. This approach is significant because it allows threat actors to bypass file-based content inspection engines designed to detect URL patterns.

For example:
IP addresses are typically shown in dotted-decimal format (e.g., 192.0.2.1), but there are other ways to represent the same address, often used to evade detection.

Examples Using 8.8.8.8 (Google Public DNS):

  • Octal: 010.010.010.010 or 010101010.
  • Hexadecimal: 0x8080808 or segmented as 0x8.0x8.0x8.0x8.
  • Decimal: 134744072.
  • Binary: 00001000.00001000.00001000.00001000.
  • Encoded: %38%2E%38%2E%38%2E%38.
  • Mixed: 0x8.010.8.134744072.
  • Zero-Optimized Notation

For 10.0.0.1, variations include:

  • 10.1
  • 10.0000000001.

These representations are often accepted by browsers, allowing adversaries to hide malicious IPs and bypass detection systems.

Similarly, URL formats present significant challenges to content inspection systems. One common tactic involves using the @ character in URIs, creating deceptive URLs that lead to semantic attacks. For instance:

  • Simple Example: https://[email protected] resolves to bing.com, ignoring the “fake” part.
  • Multiple Iterations: https://fake@fake@fake@[email protected] also resolves to bing.com.

This method works with IP address variations as well:

  • Hexadecimal: https://test@0x2afac78e
  • Decimal: https://@721078158
  • Mixed: https://192.168.1@0x2afac78e
  • Camouflage Techniques

Attackers may mask malicious URLs behind seemingly benign ones:

These methods exploit browser-supported formats, bypassing content inspection by disguising malicious intent. Although such attacks have been known for years, their effectiveness continues to pose a challenge.

ETLM ATTRIBUTION

From an External Threat Landscape Management perspective, Remote Template Injection represents a persistent and evolving threat in the cybersecurity domain. Threat actors, particularly Advanced Persistent Threat (APT) groups, are increasingly adopting this sophisticated technique to bypass traditional security measures.

Advanced Persistent Threats and the Use of Remote Template Injection:
Remote Template Injection has become a preferred method for cybercriminals and Advanced Persistent Threat (APT) groups due to its effectiveness in bypassing email security solutions. This technique enables attackers to deliver malicious payloads through seemingly legitimate documents, leading to data breaches and financial losses. Notable examples include:

  • FIN7: Leveraged remote template injection to deploy advanced malware targeting financial institutions.
  • APT28: Used Microsoft Word documents with malicious remote templates to retrieve and execute harmful macros.
  • TA505: Employed this technique to distribute ransomware as an initial attack vector.
  • APT40: Deployed weaponized RTF attachments exploiting template injection for malicious purposes.
  • DoNot Team: Conducted targeted attacks on South Asian government departments using RTF template injection.
  • Charming Kitten: Delivered Microsoft Word document droppers that used remote template injection to obtain and execute malicious macros.
  • Gamaredon APT: Delivered phishing emails containing Office documents with remote templates and malicious VBScript macros, while also injecting malicious content into pre-existing documents on compromised systems.

The primary challenge is the ability of these attacks to exploit Microsoft Word’s legitimate functionality, allowing malicious payloads to be delivered through seemingly harmless documents. Given the prevalence of phishing campaigns leveraging this method, organizations must incorporate threat intelligence to identify and mitigate these evolving techniques by continuously monitoring known APT groups and their tactics. Proactive measures, such as blocking remote template loading and educating users on the dangers of spear-phishing, are vital to reducing the impact of this attack method.

CONCLUSION

The Remote Template Injection technique demonstrates the innovative and adaptive strategies employed by threat actors to bypass traditional security mechanisms. By exploiting Microsoft Word’s legitimate functionalities, attackers can deliver malicious payloads through seemingly benign documents, making this method highly effective, particularly in spear-phishing campaigns. Advanced Persistent Threat (APT) groups and cybercriminals have increasingly adopted this approach due to its ability to evade detection and execute malicious macros after downloading the template from a remote location to the victim’s machine.

Organizations must recognize the evolving nature of such threats and implement robust security measures, including disabling remote template loading, enhancing email security filters, and educating employees on phishing risks. Furthermore, leveraging threat intelligence to monitor the tactics of APT groups can provide critical insights for mitigating these sophisticated attacks. By adopting a proactive defense strategy, organizations can better safeguard against the risks posed by Remote Template Injection and its broader implications for cybersecurity.

RECOMMENDATIONS

Recommendations to mitigate Remote Template Injection Attacks:

  • Restrict Remote Template Loading:
    • Configure Microsoft Office Group Policy settings to block documents from loading templates from remote locations.
    • Disable automatic updates for external templates in Office settings.
  • Implement Strong Email Security:
    • Deploy advanced email security solutions that can analyze document contents and detect suspicious links embedded in .rels files.
    • Enable sandboxing to examine document behavior before delivery to the end user.
  • Train Users on Phishing Awareness:
    • Conduct regular security training sessions to educate users about the risks of enabling macros and the dangers of opening unsolicited attachments.
    • Teach users to identify spear-phishing emails that often deliver such weaponized documents.
  • Monitor and Analyze Network Activity:
    • Implement network monitoring tools to detect and block malicious outbound connections to attacker-controlled servers.
    • Use intrusion detection and prevention systems (IDS/IPS) to flag abnormal activity.
  • Regularly Update Security Tools:
    • Keep endpoint protection solutions, antivirus software, and threat detection tools up to date with the latest signatures and behavioral detection capabilities.
  • Enable Macro Security Settings:
    • Set Office applications to disable macros by default and only allow digitally signed macros from trusted sources.
    • Use Protected View to open documents from untrusted sources in a read-only mode.
  • Conduct Proactive Threat Intelligence Monitoring:
    • Monitor for indicators of compromise (IOCs) related to known malicious templates and campaigns employing remote template injection techniques.
    • Maintain threat intelligence feeds to stay informed about new variants of the attack.
  • Audit and Harden Organizational Policies:
    • Limit user privileges to prevent unauthorized changes to Office settings and execution of unverified scripts.
    • Enforce strict download policies, restricting access to known malicious or untrusted websites.
  • Inspect and Analyze Office Documents:
    • Use document inspection tools to analyze .rels files within Office documents for malicious URLs or unusual references.
    • Deploy tools that scan and rewrite URLs in email attachments to prevent exploitation.
  • Collaboration and Knowledge Sharing:
    • Participate in industry threat-sharing forums to exchange information about emerging techniques like Remote Template Injection.
    • Work with security vendors to ensure tailored solutions for detecting and mitigating these threats.