Introduction To AMSI Bypasses and Sandbox Evasion

Download as pdf or txt
Download as pdf or txt
You are on page 1of 109

AN THON Y ROSE

JACOB KRASNOV
VIN C EN T ROSE

@bcsecurity1
1
Legal Stuff…So we don’t go to jail
Training is for informational and research
purposes only. We believe that ethical hacking,
information security and cyber security should be
familiar subjects to anyone using digital
information and computers. We believe that it is
impossible to defend yourself from hackers
without knowing how hacking is done. The
information provided by us is only for those who
are interested to learn about Ethical Hacking,
Security, Penetration Testing and malware
analysis.

Introduction 2
whoami
ANTHONY ROSE JACOB KRASNOV VINCENT ROSE
C01И HUBBLE HALCYON
◦ Co-founder, BC Security ◦ Co-founder, BC Security ◦ Security Researcher, BC Security
◦ Lead Researcher, Merculite Security ◦ BS in Astronautical Engineering, MBA ◦ BS in Computer Science
◦ MS in Electrical Engineering ◦ Red Team Lead ◦ Software Engineer
◦ Lockpicking Hobbyist ◦ Currently focused on embedded
system security
◦ Bluetooth & Wireless Security
Enthusiast

Introduction 3
Why are we here?
◦ How to mask your malware to avoid AMSI and Sandboxes

Introduction 4
Overview
◦ Antimalware Scan Interface (AMSI)
◦ Malware Triggering
◦ Empire
◦ Obfuscation Techniques
◦ Invoke-Obfuscation
◦ AMSI Bypasses
◦ Sandbox Evasion
◦ Put it all together

Introduction 5
Goals
◦ Introduce Microsoft’s Antimalware Scan
Interface (AMSI) and explain its importance
◦ Learn to analyze malware scripts before and
after execution
◦ Understand how obfuscate code to avoid AMSI
and Windows Defender
◦ Detect and avoid sandbox environments

Introduction 6
Expectations
We will teach you to…
◦ operate Empire
◦ obfuscate Powershell
◦ avoid AMSI and Sandboxes

We are not going to teach you…


◦ how to be a “leet hacker”

Introduction 7
-h What is Malware?

8
Overview of the Evolution of Malware Obfuscation
◦ Obfuscation is the main means by which Malware
achieves survival You can’t find me…

◦ Defeat signature-based Antivirus


◦ Makes analysis more difficult

I’m Obfuscated

What is Malware 9
The Early Days
The first virus to obfuscate itself was the Brain Virus in 1986
◦ Would display unchanged data from a different disk sector instead of the one it
had modified

The first virus to use encryption was the


Cascade Virus and also appeared in 1986
◦ Used simple XOR encryption

First commercial AV products came out in 1987


◦ This included heuristic based AV products!

What is Malware 10
Coming into Its Own
The Malware Arms Race continued
and by 1992 polymorphic virus
engines had been released
◦ Could be attached to non-
polymorphic viruses to make them
more effective

What is Malware 11
Coming into Its Own
AV wasn’t far behind and soon started
to include emulation code to sandbox
the malware
◦ There were evasion techniques but
we will talk about this later
By the 2000s malware had moved on
to so called metamorphic viruses
◦ Polymorphic viruses only change
their decryptor while metamorphic
change the code body as well

What is Malware 12
Going Fileless
Not really completely Fileless
◦ Usually requires some kind of initial script/executable to kick off infection
◦ Persistence methods may leave traces in places like the registry (e.g.,
Poweliks)
This created a big problem for AV as it has traditionally relied on
scanning files/executables

All of this leads into…

What is Malware 13
Antimalware Scan
Interface (AMSI)

14
What Is AMSI?
The Windows Antimalware Scan
Interface (AMSI) is a versatile interface
standard that allows your applications
and services to integrate with any
antimalware product that's present on
a machine. AMSI provides enhanced
malware protection for your end-users
and their data, applications, and
workloads.

AMSI 15
That’s Great But What Does that Mean?
◦ Evaluates commands at run time
◦ Handles multiple scripting languages (Powershell, JavaScript, VBA)
◦ Provides an API that is AV agnostic
◦ Identify fileless threats

AMSI 16
Data Flow

AMSI 17
One point of clarification (Powershell)
The code is evaluated when it is readable by the scripting engine
This means that:

becomes:

However:

Does not become:

This is what allows us to still be able to obfuscate our code

AMSI 18
Malware Triggering

19
Types of Windows Mitigations
◦ Windows Defender
◦ Antimalware Scan Interface (AMSI)
◦ Control flow guard
◦ Data Execution Prevention (DEP)
◦ Randomized memory allocations
◦ Arbitrary code guard (ACG)
◦ Block child processes
◦ Simulated execution (SimExec)
◦ Valid stack integrity (StackPivot)

Malware Triggering 20
Flagged Malware

Malware Triggering 22
Windows Defender Logs
Get-WinEvent 'Microsoft-Windows-Windows Defender/Operational' -
MaxEvents 10 | Where-Object Id -eq 1116 | Format-List

Detection Source: Real-time


AMSI Protection

Malware Triggering 23
Try Some Code Samples
1. Run Powershell ISE
2. Look in the sample folder
3. Try out samples 1-3

Malware Triggering 24
Building/Customizing
Your Malware

25
Don’t Do Too Much at Once
Prioritize what you want to complete
1. Get working base code first
◦ Empire, Metasploit, Etc
2. Customize Functions
3. Obfuscate Code
4. Test Against AV

Building/Customizing Malware 26
Disabling Windows Defender
New-ItemProperty -Path
"HKLM:\Software\policies\microsoft\windows defender" -name
disableantispyware -value 1 –Force

Restart computer/VM

Run network as “host only” if connected to the internet


Don’t burn your tools in development

Building/Customizing Malware 27
Empire Tutorial

28
What is Empire?
Post-exploitation framework built around Powershell
◦ Merger of Powershell Empire and Python EmPyre projects
◦ Runs on Python 2.6/2.7
◦ Encrypted C2 channel
◦ Adaptable modules
◦ .bat, .vbs, .dll
◦ Released at BSidesLV 2015
◦ No longer maintained as of Aug 2019

Empire 29
Why Go After Powershell?
◦ Full .NET access
◦ Direct access to Win32 API
◦ Operates in memory
◦ Installed by default in Windows
◦ Admins typically leave it enabled

Empire 30
How Empire is Deployed?
Relatively small payload (stager) that calls back to a listener

Empire 31
Empire Tutorial
https://github.com/BC-
SECURITY/Empire
Install our forked version (Do not use
version 2.5)
◦ sudo ./setup/install.sh
◦ sudo ./setup/reset.sh

Empire 32
Empire Tutorial
Splash page
◦Version running
(We are using a modified dev
version)
◦How many modules loaded
◦Active Listeners
◦Active Agents

Empire 33
Empire Tutorial
“Help” lists out all available commands
◦ Agents – Active payloads available
◦ Interact – Control a payload/host
◦ Preobfuscate – Obfuscates Powershell
module (not needed)
◦ Set – Modify payload settings
◦ Usemodule – Select Empire Module
◦ Uselistener – Select Listener
◦ Usestager – Select Empire stager (we will
be using macros)

Empire 34
Empire Tutorial
Setting up your listener

Select “uselistener http”

Empire 35
Empire Tutorial
Use edit to modify Listener info
◦“set Name LISTENERNAME”
◦“set Host YOURIPADDRESS”
◦“set Port PORTNUMBER”
◦“set Launcher powershell -nop
-sta –enc”
◦“execute”

Empire 36
Empire Tutorial
Usestager
◦Tailor the stager to what the target is
◦“Multi/Launcher”
◦ Useful for testing VM setups

Empire 37
Testing the Launcher
Setting the stager and listener

Successful callback to Empire

Empire 38
Enabling Windows Defender

New-ItemProperty -Path
"HKLM:\Software\policies\microsoft\windows defender" -name
disableantispyware -value 0 –Force

Restart computer/VM

Empire 39
Testing the Launcher
Setting the stager and listener

Outputs…

Empire 40
Test your Empire Payload
Build the stager
◦ Select “usestager multi/launcher”
◦ “info” to view settings

Empire 41
Test your Empire Payload
Final check on settings
◦ Obfuscation is False
◦ AMSIBypass is True
◦ Good to Go!
◦ “execute”

Empire 42
Test your Empire Payload
Final check on settings
◦ Obfuscation is False
◦ AMSIBypass is True
◦ Good to Go!
◦ “execute”

Empire 43
Test your Empire Payload

Empire 44
Empire Tutorial
Default Empire will not get past AMSI
◦ Obfuscation or changes are needed
◦ Default Empire will get you caught

Empire 45
Obfuscation Techniques

46
Randomized Capitalization
Powershell ignores capitalization

◦ Create a standard variable

◦ This makes and

◦ The same as…

◦ AMSI ignores capitalization, but changing your hash is a best practice

Obfuscation Techniques 47
Concatenation
AMSI is still heavily dependent upon signatures, simple
concatenation can circumvent most alerts
will be flagged

But, is not flagged

Obfuscation Techniques 48
Variable Insertion
Powershell recognizes $ as a special character in a string and will
fetch the associated variable.

We embedded into

Which gives us

Obfuscation Techniques 49
Format String
Powershell allows for the use of {} inside a string to allow for
variable insertion. This is an implicit reference to the format string
function.
will be flagged

But,
Returns…

Obfuscation Techniques 50
XOR || ⊕
Uses:
◦ Pseudorandom number generation
◦ Error detection
◦ Encryption/Decryption
◦ Reversable function
A B A XOR B
0 0 0
0 1 1
1 0 1
1 1 0

Obfuscation Techniques 51
Obfuscate the Samples
Using Samples 1-3 from the early exercise attempt to obfuscate
them so that they will run

Sample 3 can be difficult to figure out what is causing the issue


Save your modified versions as a different name. We will reuse the
unobfuscated samples latter

Close/Open Powershell ISE between samples

Obfuscation Techniques 52
Hints
◦ Break large sections of code into smaller pieces
◦ Isolate fewer lines to determine what is being flagged
◦ Good place to start is looking for “AMSI”

Obfuscation Techniques 53
The Answers

Obfuscation Techniques 54
Invoke-Obfuscation

55
Invoke-Obfuscation
Install here
◦https://github.com/danielboha
nnon/Invoke-Obfuscation
◦“Start-up.ps1”
◦“Import-Module ./Invoke-
Obfuscation.psd1”
◦Run “Invoke-Obfuscation”

Obfuscation Techniques 56
Invoke-Obfuscation
Type “Tutorial” for high level
directions
◦ Extremely helpful for
learning/remembering the basics

Obfuscation Techniques 57
Invoke-Obfuscation
Example code
◦ Use Sample 4
◦ SET SCRIPTBLOCK…

Obfuscation Techniques 58
Invoke-Obfuscation
Token-layer Obfuscation
◦ Token\Variable (extremely useful for
masking variable names to AMSI)
◦ Token\All (if you are super lazy)
◦ This will get you caught
◦ Typically run whitespace last (2-3
times)

Obfuscation Techniques 59
What is Abstract Syntax Tree (AST)?
Abstract Syntax Tree (AST)

Obfuscation Techniques 60
Invoke-Obfuscation
Abstract Syntax Tree (AST)
◦ Changes structure of AST
◦ AST contains all parsed content in
Powershell code without having to
dive into text parsing (we want to
hide from this)

Obfuscation Techniques 61
Invoke-Obfuscation
Encoding
◦ Used to further mask the payload
by converting the format (e.g., Hex,
Binary, AES, etc)
◦ Beware: running too much encoding
will break the 8,191 character limit

Obfuscation Techniques 62
Invoke-Obfuscation
String
◦ Obfuscate Powershell code as a
string
◦ Breaks up the code with reversing
techniques and concatenation

Obfuscation Techniques 63
Invoke-Obfuscation
Compress
◦ Can be used in conjunction with
Encoding to reduce the overall
size of the payload.

Obfuscation Techniques 64
Invoke-Obfuscation
Launcher
◦ Not needed since Empire already
includes a launcher

Obfuscation Techniques 65
Invoke-Obfuscation
Order of operations
◦Mix it up to avoid detection
◦Example:
◦Token\String\1,2
◦Whitespace\1
◦Encoding\1
◦Compress\1

Obfuscation Techniques 66
Invoke-Obfuscation in Empire

Obfuscation Techniques 67
AMSI Bypasses

68
Why do we need this?
If our payload is already obfuscated enough to evade AMSI why
bother?
◦ Only the first part of the stager is obfuscated!

AMSI Bypasses 69
Why do we need this?
AMSI bypasses let us
load whatever future modules we
may want without issues
◦ Mimikatz, PSInject, Powerup

AMSI Bypasses 70
AMSI results
◦ AMSI_RESULT_CLEAN = 0
◦ AMSI_RESULT_NOT_DETECTED = 1
◦ AMSI_RESULT_BLOCKED_BY_ADMIN_START = 16384
◦ AMSI_RESULT_BLOCKED_BY_ADMIN_END = 20479
◦ AMSI_RESULT_DETECTED = 32768

AMSI Bypasses 71
Keep It Simple Stupid

AMSI Bypasses 72
Keep It Simple Stupid

AMSI Bypasses 73
Keep It Simple Stupid

AMSI Bypasses 74
Bypass 1: Reflective Bypass
Simplest Bypass that currently works
◦ $Ref=[REF].Assembly.GetType('System.Management.Automation.AmsiUtils');
◦ $Ref.GetField('amsiInitFailed', 'NonPublic, Static').SetValue($NULL, $TRUE);

AMSI Bypasses 75
What Does it Do?
Using reflection we are exposing functions from AMSI
We are setting the AmsiInitField to True which source code shows
causes AMSI to return:
◦ AMSI_SCAN_RESULT_NOT_FOUND

AMSI.dll

AMSI Bypasses 76
Why does this work?
AMSI is loaded into the Powershell process at start up so it has the
same permission levels as the process the malware is in

AMSI Bypasses 77
Bypass 2: Patching AMSI.dll in Memory
More complicated bypass, but still allows AMSI to load

AMSI Bypasses 78
Bypass 2: Patching AMSI.dll in Memory
We use C# to export a few functions from kernel32 that allows to
identify where in memory amsi.dll has been loaded

AMSI Bypasses 79
Bypass 2: Patching AMSI.dll in Memory
We modify the memory permissions to ensure we have access

AMSI Bypasses 80
Bypass 2: Patching AMSI.dll in Memory
Modifies the return function to all always return a value of
RESULT_NOT_DETECTED

AMSI Bypasses 81
Why does this work?
AMSI.dll is loaded into the same memory space as Powershell.
This means that we have unrestricted access to the memory space
that AMSI runs in and can modify it however we please
Tells the function to return a clean result prior to actually scanning

AMSI Bypasses 82
AMSI Bypasses in Empire
Ensure that ObfuscateCommand
and AMSI Bypass both display
values
◦ “set Obfuscate True”
◦ “set ObfuscateCommand Token\String\1,1,2,
Token\Variable\1, Token\Whitespace\1,1,
Compress\1”
◦ “set AMSIBypass True”

AMSI Bypasses 83
Test time!
Re-enable Defender and run your Empire launcher

AMSI Bypasses 84
Sandbox Detection and
Evasion

85
What is a Sandbox?
◦ A software created environment that isolates
and limits the rights and accesses of a
process being executed
◦ An effective way of doing behavioral analysis
for AV

Sandbox Evasion 86
Who is using Sandboxes?

Sandbox Evasion 87
Automated Sandbox Malware analysis
As we talked about earlier, obfuscating
code to break signatures can be
relatively trivial
◦ AV would need an almost unlimited
number of signatures
Heavily obfuscated code can make it
almost impossible for human analysis to
be effective
Instead evaluate behavior

Sandbox Evasion 88
Sandbox Indicators

89
Sandbox Limitations
They use a lot of resources
which can be expensive

End users don't want to wait to


receive their messages

Email scanning requires


thousands of attachments to
be evaluated constantly

Sandbox Indicators 90
Sandbox Limitations
These limitations provide us with several means to try and detect or
evade them
◦ Password Protection
◦ Time Delays
◦ Auto open vs close
◦ Check for limited resources (small amount of ram, single core, etc.)
◦ Look for virtualization processes (sandboxie, VMWare tools)

Sandbox Indicators 91
Embedding Macros

92
Back to Empire
Usestager
◦Tailor the stager to what the target is
◦Our focus is Windows using a Macro (will be used later)
◦“Windows/macro”

Embedding Macros 93
Creating a Payload
◦Set stager and listener
◦Copy macro over to Word

Embedding Macros 94
Turning on Developer Options

Embedding Macros 95
Embedding the Macro
Open Word Document
Select Developer Options
Click on Macros

Embedding Macros 96
Embedding the Macro

Embedding Macros 97
Embedding the Macro
Drag and drop NewMacros from Modules to current Project

Embedding Macros 98
Evasion Techniques

99
When do we want to do this?
Before we do suspicious things such as…
◦ Starting a new process
◦ Reaching out to the internet
The checks could be suspicious themselves
◦ Sandbox Evasion is becoming more
prevalent

Evasion Techniques 100


Password Protection
The sandbox doesn't know the
password and therefore can't open
the file. No results are found so the
file is passed on.
The password is usually sent in the
body of the email with instructions to
use it.
◦ Lower success rate

Evasion Techniques 101


Time Delay
Email filters have a limited amount of time to scan files so delay
until it the scan is completed

This is less practical in a macro as it will keep the document open


until done waiting

Evasion Techniques 102


Checking for Resources
Using WMI Objects you can enumerate the hardware and system
configurations
Some malware looks for things like the presence of a fan
◦ Note: WMI objects are very inconsistently implemented by manufacturers.

Evasion Techniques 103


Checking for Resources
Some Useful WMI Objects
◦ Win32_ComputerSystem
◦ Win32_LogicalDisk
◦ Win32_Fan
◦ Win32_videocontroller

Evasion Techniques 104


Checking for Processes
Most if not all sandboxes result in the addition of management
processes that we can look for
◦ Win32_Process contains all the processes currently running
Some common processes to look for:
◦ Sbiesvc, SbieCtrl
◦ Vmtools
◦ VBoxService

Evasion Techniques 105


There is no one way guaranteed to work
Because of the control many developers have on implementing
WMI objects or naming processes there is no one check that is
guaranteed to work.
◦ Learn as much as possible about the target environment
◦ Use multiple halting conditions
◦ Check places like attack.mitre.org to look for new techniques if old ones fail

Evasion Techniques 106


Evasion Development
Commonality between sandboxes can
be used as a fingerprint
◦ Number of CPU cores
◦ RAM
◦ Disk Size
Not common
◦ IP address
◦ Machine and User names

Evasion Techniques 107


Put it all together
YOUR TURN TO TRY IT ALL

109
Put it all together
1. Build payload in Empire
◦ AMSI Bypass
◦ Obfuscation
2. Embed into Word Doc
◦ Verification
3. Add in Macro Checks to avoid “Sandbox”
4. (Optional) Test on host machine

Put it all together 110


INFO@BC-SECURITY.ORG
@BCSECURITY1
HTTPS://GITHUB.COM/BC-SECURITY/DEFCON27

111

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy