Malicious Shapes In Office — Part 2

Laughing Mantis
9 min readJul 8, 2020

--

Red Team: Abusing EnhMetaFileBits and AddPicture for VBA Malware (VBA-Stendhal)

The Shelf Life-cycle of Office Based Malware

This is a continuation of how MsoShapes objects in Microsoft Office can be abused — if you missed part 1 it is available here.

As I have mentioned on Twitter, Office malware and offensive tools utilizing VBA generally have a limited life-cycle:

  • Attacker Emails Victim Malicious Office Document
  • Victim Opens Document
  • Victim Is Socially Engineered To Enable Content To Execute Macros (Depends on Security Settings)
  • Malicious Office Document Executes VBA Code and compromises Victim
  • Blue Team Finds Malicious Document In Email Box and/or On Victim’s Machine
  • Malicious Document Is Analyzed Using Sandboxes and Other Reverse Engineering Tools
  • Blue Team Discovers What Actions Malicious Document Performed and Mitigate/Remediate

For Red Teams and Malware the last 3 steps of this life cycle is extremely detrimental to the continued usage of their VBA malware. Extending your shelf-life by increasing the cost, time, and effort to analyze your code is the name of the game.

Execute Once (X1) and Controlled Execution (CX)

As I mentioned in a previous entry VBA malware often takes some steps in order to prevent reverse engineering such as using Document.Variables and MsoShapes in Office to have “Execute Once” (X1) or “Controlled Execution” (CX) capabilities.

X1 and CX capabilities are important factors for VBA malware. X1 is like it says, “Execute Once” on the target, putting the sample anywhere else — say a sandbox or manual execution via an analyst would be impossible. Controlled Execution is similar, in the sense that the code executes only under certain conditions in order to achieve the same anti-analysis goal.

VBA, like all script or interpreted languages; contain their full source code embedded in themselves. Meaning once your tool has been identified, it’s capabilities are known and its usage and effectiveness begins to rapidly degrade.

Currently modern tactics to combat reverse engineering (Anti-RE) is to obfuscate code using various built in Methods and functionality in VBA. Some of these methods can be read about on the excellent blog — Evasive VBA — Advanced Maldoc Techniques by Carrie Roberts (@OrOneEqualsOne). I will be talking about other advanced methods on how to obfuscate VBA content in a future post.

Even with time-hindering obfuscation, eventually RE teams and AV analysis will crack your VBA code and discover what it does. X1 and CX capabilities will effectively prevent your code from being fully analyzed and increase the shelf-life of your malicious VBA code.

However the current X1 and CX capabilities in Office malware are greatly flawed. VBA malware and tools still store the entirety of their code within themselves and then delete, obfuscate, re-generate, or stomp their code post execution. Meaning the victim still has an unexecuted copy of the malicious document in their email inbox or on the email server that has the original code without the psuedo-X1 and CX capabilities.

In order for Red Teams to have X1 and/or CX capabilities code needs to have the following features:

  • Modular code is needed, there will be a Husk code and Module code
  • Module Code needs to be remotely accessed and executed on the fly
  • Husk Code needs to accept that it will be discovered, however the discovering and reverse engineering Husk code will never reveal Module Code

A good Blue Team has multiple ways to discover what code does or did in an incident. However by using this above framework a Blue Team without in-depth on system monitoring, post incident would only be able to say:

  • This sample is malicious
  • It connected to X remote resource(s)
  • It downloaded Y content(s)
  • It performed Z actions based on Y content

Again, abusing MsoShapes can handle Y and Z and make it so the information discovered is acceptably vague or too generalized to degrade the usage of your malicious tool immediately.

Abusing AddPictures and EnhMetaFileBits

The first goal of creating adding genuine X1 or CX capabilities is to utilize a method that allows remote file downloading in Microsoft Office.

Malware authors have long used many methods to download and execute code in Office, however all of these used Win32 API, external binaries, COM objects, or other sketchy tricks. All of these methods are already flagged by AV and sandbox systems as suspicious. One of the best ways to avoid these kinds of detection is to abuse valid and existing functionality.

Microsoft Office and VBA offers a plethora of ways to communicate to remote devices (I will lay these out in a future post) however, MsoShapes offer a really unique method of achieving remote file downloading via InlineShapes.AddPicture

InlineShapes.AddPicture Method can be abused to download valid image files to Office documents automagically

The FileName paramenter, like almost all other FileName parameters within VBA will accept URL and remote resources such as UNC paths as well as a few other protocols (depending on the protocol-handlers on the machine).

Additionally the LinkToFile and SaveWithDocument parameter can be specified to include the file into the document, thus physically grabbing a copy of the file and inserting it into the Office Document space. This allows VBA to programmatically interact with the picture as an InlineShape object.

So remotely downloading and insert an image file into an Office document can be effectively achieved using a single line of code.

ActiveDocument.InlineShapes.AddPicture(“https://pbs.twimg.com/profile_images/631923531719151616/IpTXHz_t_400x400.jpg”, False, True)

KMFDM Better than the best, meglomanical and harder than the rest.

Notice how the above example imports the picture as an InlineShape. InlineShapes are slightly different than Shapes in the sense that they often contain a container called a Range object. InlineShapes that are MsoPicture types will have a special property in their Range called EnhMetaFileBits.

EnhMetaFileBits property contains an array of an InlineShape image’s content

This is effectively a read-only byte array containing the content of the InlineShape in the form. This byte array is designed to contain data for creating images and thumbnails of images and content so it can be rendered in other readers and for preview/layout compatibility.

EnhMetaFileBits array of the inserted Image.

Working with the EnhMetaFileBits property is a bit of a pain so I made some functions that will display the array in a hex editor format and to extract the array and save it as a file.

EnhMetaFileBits Stream vs Original JPEG — Note to self change my Copywrite on logo

On the left is the first 512 bytes of the EnhMetaFileBits array contains when importing https://pbs.twimg.com/profile_images/631923531719151616/IpTXHz_t_400x400.jpg while on the right is the original JPEG.

A few of you may notice that the formatting of this binary stream does not include any of the JPEG header or typical JPEG layout, and that is because all data passed within this function is converted to Windows Metafile (EMF) file format — hence the EnhancedMetaFileBits.

As you can see the 2 files don’t line up at all and the conversion makes them drastically different. To be honest, this is what effectively killed my research into this topic months ago.

Overcoming EMF Conversion Issues In Office

I decided to revisit AddPicture and EnhMetaFileBits while playing around with EMF files instead of other formats and I noticed that the conversion was able to keep content of the original file even if they had nothing to do with display data. However even if the original file was in EMF format the content of the file was still altered in the conversion steps. (For the record even if you take original EMF -> Import EMF as InlineShape-> Export new InlineShape EMF as EMF-> Import the InlineShape Generated EMF as new InlineShape EMF it will still be converted and different)

So I made a tool that would do the following:

  • take a EMF file (Base file) and insert unique data (Data Flag) throughout the file and save each of these as a new EMF file (Test Files).
  • It would then import the all the Test Files into Office using the AddPicture method.
  • From there the tool would then search the EnhMetaFileBits array for the Data Flag and report its location.
Tool to Search For Data Flag locations in an EMF file that is imported via AddPicture method

This effectively allows us to abuse this feature in order to store data inside a EMF picture file at predictable and recoverable location even after conversion.

Introducing VBA-Stendhal for Red Teams

In order to abuse all these features effectively in VBA I have developed VBA-Stendhal. This tool can do the following:

  • Automatically Test EMF files to see if they can be used to insert encrypted commands or data for X1 and CX purposes.
  • Generate a Command EMF file and allow it to be uploaded to your C2
  • Download a Command EMF file and extract commands from it
  • Provide a Hex View of EnhMetaFileBits for debugging
  • Provide methods to brute force search a Command EMF file instead of knowing the offset for command execution

Specifically how this allows X1 and CX conditions is as follows:

  • Bad actor uses VBA-Stendhal to insert commands inside a EMF file (Command EMF)
  • Bad actor uploads Command EMF file to C2 server
  • Bad actor delivers malicious document to target via email
  • Target executes malicious document and enables Macros
  • Malicious document uses VBA-Stendhal Husk to download the Command EMF file
  • C2 shuts down or puts up Not Malicious EMF or Anti-RE EMF copy
  • VBA-Stendhal Husk code Executes commands from EMF file and deletes the EMF file
  • VBA-Stendhal saves the document to prevent the EMF from being available

This matches up perfectly with the earlier requirements we set for achieving X1 or CX capabilities:

This sample is malicious

They have the sample, they can see that it added a Shape into the document and then did actions based on the content of the shape.

It connected to X remote resource(s)

Your C2 address and host will be discovered. The use of 3rd party hosts will likely have logs and backup copies of what you uploaded but depending on your risk and goals this may be acceptable.

It downloaded Y content(s)

This is the fun part. You can chose the next course of action. You know your sample should never hit Y resource twice, so any subsequent hits after the initial hit is likely a follow up team.

(Note: unless you are looking at those handy dandy email detontation test servers and email sandboxes — remember to include environment tests for this)

By taking down your C2 you wont be able to identify when your adversary initiated analysis at the risk of leaving forensic data.

By providing a Anti-Analysis Command EMF you can introduce some fun additional checking and headaches to the RE team.

The next version of VBA-Stendhal will include the ability to generate an Anti-Analysis Command EMF that can also includes fake URLs and resources that you can monitor to see if the RE team is on to you.

It performed Z actions based on Y content

This will be entirely dependent on your Husk code and how it interprets the VBA-Stendhal code (again another blog post for another day). Using anti-analysis features it allows

Get VBA-Stendhal

VBA-Stendhal is available on my GitHub — https://github.com/glinares/VBA-Stendhal

Using VBA-Stendhal

I will develop a fully weaponized version of VBA-Stendhal in the future, in the mean time VBA-Stendhal is meant to be used as a testing platform.

Additional Notes:

TestEMFFile (BaseFile as String, DataFlag as String)

This will generate test files by insert DataFlag at every sequential offset available using the BaseFile as the test file. It will then import these into Word and show operator every available location where the DataFlag was discovered in the test file.

Public Sub DumpInlineShape2Hex(objInShape As InlineShape, Optional startOffset As Long = 0, Optional endOffset As Long = -1)

This will create a visible Hex dump of the InlineShape so you can debug issues with VBA-Stendhal and manually verify findings.

VBA-Stendhal is an ongoing module, there are a few bugs (ie offsets are sometimes off by 1 — be aware, I will fix the code in a future release)

In my next entry I will flip sides and discuss how Blue Teams, Microsoft, Sandboxes and AV can detect, mitigate, and counter this issue.

--

--