SlideShare ist ein Scribd-Unternehmen logo
1 von 54
Who?
• Udi Yavo
• CTO and Co-Founder, enSilo
• Former CTO, Rafael Cyber Security Division
• Low Level Researcher
• Author on BreakingMalware
• Tomer Bitton
• VP Research and Co-Founder, enSilo
• Low Level Researcher, Rafael Advanced Defense Systems
• Malware Researcher
• Author on BreakingMalware
Agenda
• User-Mode Injections
Classic Code Injection Methods
Advanced Injections - PowerLoader
PowerLoaderEx
PowerLoaderEx64
• Kernel-Mode Injections
Common Injection Methods
Introducing Trap Frame Injection
Codeless Code Injection
Demo
• Summary
User-Mode Code Injections
Classic Code Injection Methods
• Vanila Injection - OpenProcess/ VirtualAllocEx/CreateRemoteThread/LoadLibrary
• GetThreadContext / SetThreadContext
• SetWindowsHookEx
• AppInit_DLLs and APPCERTDLLs
• ShimEng (InjectDll Tag)
• SetWindowLong
• QueueUserApc
• Replace Dependency DLL
• …
PowerLoader – POP/POP/INJECT
• Loader used in many different dropper families (Gapz / Redyms / Carberp / Vabushky ...)
• Technique was leaked with Carberp source code leak.
• First injection technique via Return Oriented Programming technique (ROP).
• “explorer.exe” is injected using Shell_TrayWnd / NtQueueApcThread (32bit / 64bit)
• Successfully bypassed most HIPSs solutions
1. http://www.welivesecurity.com/2013/03/19/gapz-and-redyms-droppers-based-on-power-loader-code/
2. http://www.slideshare.net/matrosov/advanced-evasion-techniques-by-win32gapz
3. https://www.virusbtn.com/virusbulletin/archive/2012/10/vb201210-code-injection
4. http://www.malwaretech.com/2013/08/powerloader-injection-something-truly.html
 Samples and valuable info - http://www.kernelmode.info/forum/
PowerLoader – Abusing Shared Sections
• Explorer.exe has several shared memory sections it uses:
• By calling NtOpenSection and ZwMapViewOfSection PowerLoader maps one of the shared
sections to its own address space
• PowerLoader finds the address of the shared section in explorer by calling VirtualQueryEx /
ReadProcessMemory / RtlCompareMemory combination
• The shellcode is than written to the shared section. There is no need for VirtualAllocEx /
WriteProcessMemory which is monitored by many HIPS
PowerLoader - Triggering Code Execution
• One of the Windows in Explorer.exe is Shell_TrayWnd
• The Shell_TrayWnd window has a pointer to CTray class object which handles messages to the window
• Once the Shell_TrayWnd window is found PowerLoader uses SetWindowLongPtr to replace the CTray object with a malicious CTray
Object in the shared section
• The shared section is not executable thus ROP is needed
• The virtual table of the malicious CTray object point to KiUserApcDispatcher routine which eventually trigger the ROP execution
• To trigger code execution SendNotifyMessage is called with WM_PAINT message
PowerLoader - ROP n’ Roll
• PowerLoader uses a complex ROP chain
• Basic steps by the ROP chain (High-Level):
• Direction Flag Set
• Copy ROP chain to stack
• Direction Flag Clear
• Use WriteProcessMemory to overwrite ntdll!atan function (this function is probably not used in the
context of explorer.exe)
• Pass control to the overwritten ntdll!atan function
PowerLoader - Quick Summary
• Advanced Injection technique
• Completely bypassed most HIPS at the time
• Using Exploit-Like techniques:
• The first Injection technique to use ROP (to our knowledge)
• Overwrites atan function using WriteProcessMemory
• No similar 64-bit version (to our knowledge)
• Try to run vs EMET and see what happens…
• Very application specific:
• Targets Shell_TrayWnd of explorer.exe
• Uses specific shared sections
• Doesn’t use direct code injections
Introducing PowerLoaderEx
Goals:
• Remove dependency in Explorer.exe shared sections (more generic)
• Make a 64-bit version
• Bonus: Do it without reading memory from the target process
UI Shared Memory - Reminder
• UI Objects are stored in one of three places:
• Session Pool – Allocated per user logon
• Desktop Heap – Stores objects specific to a given Desktop
• Shared Heap – Handle Table and object relevant to all Desktops
• The heaps are visible to user-mode via shared-memory
• Commonly used for exploiting privilege escalation vulnerabilities
• Extensively documented in:
“Windows Hooks Of Death: Kernel Attacks through User-Mode Callbacks” – By Tareji
Mandt
UI Shared Memory
Kernel Space
User Space
Application 1
Desktop
Heap 1
Shared Section
Handle
Table
Shared
Heap
Shared Section
Handle
Table
Shared
Heap
Desktop
Heap 1
Application 2
Desktop
Heap 1
Shared Section
Handle
Table
Shared
Heap
PowerLoaderEx – Desktop Heap as Shared Section
• Desktop Heaps are better as shared section because they are mapped to any
process on a given desktop
• Writing arbitrary data to the Desktop Heap is easy:
• Create a window with enough extra bytes
• Use SetWindowLongPtr to write the payload
• But how do know where it resides in a target process?
Finding Target Process’s Desktop Heap
• Find the Desktop Heap in our process and find its region size
• Enumerate explorer.exe memory regions by calling VirtualQuery.
• The target’s Desktop Heap is found if the region characteristics are:
• State: MEM_COMMIT
• Type: MEM_MAPPED
• Protect: PAGE_READ_ONLY
• RegionSize is equal to the previously obtained heapSize.
Double Check – Avoiding False Positives
• We had NO false positives in finding the shared desktop heap (local process and target process)
• The following check will remove any false-positive:
* Note: using the double check version will require calling NtOpenProcess with QUERY_INFORMATION and PROCESS_VM_OPERATION
Finding The Gadgets
• We do the gadget lookup in our own process
• Load and scan only modules that we know that are always loaded in the target process (i.e. explorer.exe)
• Use only modules that are very likely to have the same base in both processes:
• ntdll.dll
• Kernel32.dll
• Kernelbase.dll
• User32.dll
• Shell32.dll
PowerLoaderEx - Look Ma, No Read!
1. Create a window and find it in the shared desktop heap
2. Find the target process (Explorer.exe) and find where the desktop heap is mapped, requires only PROCESS_QUERY_INFORMATION
privileges
3. Scan for the required gadgets
4. Write the payload to the shared desktop heap using SetWindowLongPtr
5. Continue like normal PowerLoader
* Note: If a different target process has more than one Desktop Heap mapped read will be needed
PowerLoaderEx64 - What About 64-bit?
• Challenges:
• Much harder to find useful gadgets
• No code writing allowed
• No reads allowed
PowerLoaderEx64 – Remember the CTray Object?
The Controlled
Ctray Object
Virtual Calls
CImpWndProc::s_WndProc
PowerLoaderEx64 - Strategy
• Find some function that can be manipulated to call LoadLibrary with controlled first
argument
• Make sure no crashes occur after/during library loading
• To make things simple point 2 of the 3 virtual calls to “Do Nothing” functions (Ret
opcode)
PowerLoaderEx64 – User32 Callbacks To Rescue
The Controlled
Ctray Object
Should be NULL
Pointer to DLL Path
Pointer to LoadLibraryA
PowerLoaderEx64 - Recap
1. Create a window and find it in the shared desktop heap
2. Find the target process (Explorer.exe) and find where the desktop heap is mapped, requires only PROCESS_QUERY_INFORMATION
privileges
3. Write the malicious CTray object to the shared desktop heap using SetWindowLongPtr
4. Replace the Shell_TrayWnd window’s CTray object using SetWindowLongPtr
5. Use SendNotifyMessage to trigger LoadLibrary
PowerLoaderEx64 source code will be on BreakingMalware
http://BreakingMalware.com
Kernel-To-User Code Injections
Introduction - Kernel-To-User Code Injections
• Mainly used for:
• Injecting DLLs
• Sandbox escapes – After exploiting privilege escalation vulnerability
• Injecting to protected processes
• Fewer techniques exist than user-mode
• Less documented than user-mode techniques
• Used by both Malware and Software/Security vendors
Common Injection Methods – User APC
• The most common Kernel-To-User injection method
• Used by lots of malwares:
• TDL
• ZERO ACCESS
• Sandbox escape shellcodes
• …
• Also used by lots of security products:
• AVG
• Kaspersky Home Edition
• Avecto
• …
• Documented:
• Blackout: What Really Happened
• Much more in forums and leaked source codes
Common Injection Methods – User APC
Basic Steps (There are several variations):
1. Register load image callback using PsSetLoadImageNotifyRoutine and wait for
main module to load
2. Write payload that injects a dll using LdrLoadDll
(Other variations use LoadLibrary)
3. Insert User APC using KeInsertQueueApc
Common Injection Methods – Entry Point Patching
• Not really common but worth mentioning
• Used by Duqu
• Fully documented in:
http://binsec.gforge.inria.fr/pdf/Malware2013-Analysis-Diversion-Duqu-paper.pdf
Ntoskrnl.exe
Common Injection Methods – Entry Point Patching
• Register load image callback using PsSetLoadImageNotifyRoutine and wait for main
module to load
Kernel Space
User Space
Application
RtlUserThreadStart
KiStartUserThread
EvilDriver.sys
Callback Routine
Process Image
Ntoskrnl.exe
Common Injection Methods – Entry Point Patching
• Write the payload to the process address space
Kernel Space
User Space
Application
RtlUserThreadStart
KiStartUserThread
EvilDriver.sys
Callback Routine
Payload
Process Image
Ntoskrnl.exe
Common Injection Methods – Entry Point Patching
• Replace the image entry point with JMP to the new code
Kernel Space
User Space
Application
RtlUserThreadStart
KiStartUserThread
EvilDriver.sys
Callback Routine
Payload
Process Image
JMP Payload
Ntoskrnl.exe
Common Injection Methods – Entry Point Patching
• The payload executes, fixes the entry point and jumps to it
Kernel Space
User Space
Application
RtlUserThreadStart
KiStartUserThread
EvilDriver.sys
Callback Routine
Payload
Process Image
Jump to entry point
Common Injection Methods – Import Table Patching
• Undocumented (to our knowledge)
• Never been used by malware (to our knowledge)
• Used by software and security vendors:
• Symantec
• Trusteer
• Microsoft App-V
• Similar method could probably use TLS data directory
Common Injection Methods – Import Table Patching
1. Register load image callback using PsSetLoadImageNotifyRoutine and wait for
main module to load
2. Allocate memory for the new import table and copy old table with a new record
for the injected DLL
3. Point the import data directory to the new table
4. When the DLL is loaded the original PE header is restored
PE Header
MZ Header
DOS Stub
File Header
Optional Header
Data Directories
Imports
…
Import Descriptor 1
Import Descriptor 2
Before
PE Header
MZ Header
DOS Stub
File Header
Optional Header
Data Directories
Imports
…
Import Descriptor 1
Import Descriptor 2
After
Import Descriptor 1
Import Descriptor 2
Injected DLL Descriptor
…
Common Injection Methods – Quick Summary
• Kernel-To-User Injections are extensively used by both malware and
security/software vendors
• Kernel injections are mainly used to inject a DLL to target(or all) processes
• All these methods require injection of some payload to user mode (except for
Import Table Patching)
• All use PsSetLoadImageNotifyRoutine
Introducing Trap Frame Injection
• A new kernel-to-user injection technique
• Trap frames save the CPU user-mode state during exceptions or interrupt handling
• A Trap frame is created each time a system call is made and stored on the kernel
stack
• The kernel structure used for trap frames is _KTRAP_FRAME
• The user-mode state is restored when the system call returns
• Current frame is stored in the TrapFrame field of _KTHREAD
KTRAP_FRAME
32-Bit 64-Bit
Ntoskrnl.exe
The Trivial Injection
• Wait for some callback that runs in context of a system call
(Thread Creation, Registry Access,…)
Kernel Space
User Space
Application
CreateThread
NtCreateThreadEx
EvilDriver.sys
Callback Routine
Ntoskrnl.exe
The Trivial Injection
• Allocate payload in the target application
Kernel Space
User Space
Application
CreateThread
NtCreateThreadEx
EvilDriver.sys
Callback Routine
Payload
Ntoskrnl.exe
The Trivial Injection
• Fix the trap frame’s saved RIP/EIP to the payload
Kernel Space
User Space
Application
CreateThread
NtCreateThreadEx
EvilDriver.sys
Callback Routine
Payload
Ntoskrnl.exe
The Trivial Injection
• The payload runs and restores normal execution
Kernel Space
User Space
Application
CreateThread
NtCreateThreadEx
EvilDriver.sys
Callback Routine
Payload
But We Promised a Codeless Code Injection…
Goals:
• Run code in the context of an arbitrary process:
Force IExplore.exe to send POST
Open remote shell
…
• Easy to write
Limitation:
• No code injections to the process
Ntoskrnl.exe
Codeless Code Injection
• Wait for some callback that runs in context of a system call
(Thread Creation, Registry Access,…)
Kernel Space
User Space
Application
CreateThread
NtCreateThreadEx
EvilDriver.sys
Callback Routine
User Stack
…
NtCreateThreadEx ESP
Ntoskrnl.exe
Codeless Code Injection
• Build ROP Chain on the user stack
Kernel Space
User Space
Application
CreateThread
NtCreateThreadEx
EvilDriver.sys
Callback Routine
User Stack
…
NtCreateThreadEx
“MyLib.dll”
RETN address
LoadLibraryA
ESP
Ntoskrnl.exe
Codeless Code Injection
• Set the stack pointer to the start of the ROP chain
Kernel Space
User Space
Application
CreateThread
NtCreateThreadEx
EvilDriver.sys
Callback Routine
User Stack
…
NtCreateThreadEx
“MyLib.dll”
RETN address
LoadLibraryAESP
Codeless Code Injection - Challenges
• Getting Return Values – how do we get return values back to kernel mode
• Solution 1: Use device handle to get notifications (deep dive coming up)
• Solution 2: Save return value somewhere and trigger some hook-able event (Such as registry
access)
• Deadlocks – if the user mode caller holds a lock that our injected function needs
• Solution: Use a dedicated thread
• Callback – What if we need to a user-mode callback function
• Solution 1: Use a function that always triggers some hook-able event and fix the context
• Solution 2: Just don’t use such functions 
Codeless Code Injection - NtClose as a callback
• Create a device using IoCreateDevice
• Whenever we require a callback, create a handle for the device in the target process
• Build the following ROP chain:
User Stack
…
Device Handle
RETN address
NtClose
MOV [EDX], EAX Gadget
Writable Location
POP EDX Gadget
…
ESP
=
MOV EDX, ADDRESS
MOV [EDX], EAX
NtClose(DeviceHandle)
Codeless Code Injection - NtClose as a callback
• When NtClose(Device Handle) is executed then the IRP_MJ_CLEANUP handler will be
called
• The required data will reside in the target address
* moving EAX to some register is not safe because of WOW64
ESP
User Stack
…
Device Handle
RETN address
NtClose
MOV [EDX], EAX Gadget
Writable Location
POP EDX Gadget
…
Codeless Code Injection – Creating dedicated thread
HANDLE WINAPI CreateThread(
_In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
_In_ SIZE_T dwStackSize,
_In_ LPTHREAD_START_ROUTINE lpStartAddress,
_In_opt_ LPVOID lpParameter,
_In_ DWORD dwCreationFlags,
_Out_opt_ LPDWORD lpThreadId
);
DWORD WINAPI ThreadProc(_In_ LPVOID lpParameter);
NtClose
Device Handle
• Wait for some callback that runs in context of a system call
(Thread Creation, Registry Access,…)
• Build the following ROP Chain
• When Handle cleanup is triggered start injecting ROP chains to the new thread
Codeless Code Injection – Creating a Dedicated Thread
ESP
User Stack
…
0
0
Device Handle
NtClose
0
NULL
RETN address
CreateThread
…
=
CreateThread(NULL,
0,
NtClose,
Device Handle,
0,
0);
Codeless Code Injection – API
ROProgram *CreateProgram(CHAR* TargetName) –
Creates a ROP program that’s to be run in a target process
AddStep(ROProgram* Program, ROProgramStepProc StepProc)–
Adds a step to the program. A Single ROP chain that ends in callback(NtClose)
RunProgram(ROProgram* Program) –
Wait’s for the target process to create a thread and starts a new dedicated thread
UserLibrary OpenUserLibrary(CHAR* LibName)–
Finds a DLL in the target process memory
Call(ROPChain* RopChain, UserLibrary Module, CHAR* Function, u32 NumberOfArgs, ...) –
Add a call to a ROP chain
LoadLibrary(ROPChain* RopChain, char* Name) –
Load a Library into the target process
WriteToUser(ROPChain* RopChain, u8* Buf, u32 BufSize) –
Writes a buffer of data to user-mode
Codeless Code Injection – API Example
ROProgram* Program = CreateProgram("iexplore.exe“);
AddStep(Program, LoadSomeLibrary);
RunProgram(Program);
…
bool LoadSomeLibrary(ROProgram* Program, ROPChain* Chain){
return LoadLibrary(Chain, “MyLibrary.dll”);
}
Load a new library to the target process:
Demo
Reverse Shell from WINLOGON
Summary
• Code injection remains an important capability for both malware and
security/software vendors
• Like exploits, techniques are becoming less generic (PowerLoader)
• New User and Kernel injection techniques are constantly being invented
• We can probably expect new advanced injection methods in the near future
• Slides and Source-code will be available on BreakingMalware in a few days
@enSiloSec Company/enSilo ensilo.com/blog contact@ensilo.comwww.enSilo.com

Weitere ähnliche Inhalte

Was ist angesagt?

Windows Kernel Exploitation : This Time Font hunt you down in 4 bytes
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytesWindows Kernel Exploitation : This Time Font hunt you down in 4 bytes
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytes
Peter Hlavaty
 

Was ist angesagt? (20)

OWASP AppSecCali 2015 - Marshalling Pickles
OWASP AppSecCali 2015 - Marshalling PicklesOWASP AppSecCali 2015 - Marshalling Pickles
OWASP AppSecCali 2015 - Marshalling Pickles
 
Windows Attacks AT is the new black
Windows Attacks   AT is the new blackWindows Attacks   AT is the new black
Windows Attacks AT is the new black
 
BlueHat v17 || Out of the Truman Show: VM Escape in VMware Gracefully
BlueHat v17 || Out of the Truman Show: VM Escape in VMware Gracefully BlueHat v17 || Out of the Truman Show: VM Escape in VMware Gracefully
BlueHat v17 || Out of the Truman Show: VM Escape in VMware Gracefully
 
Android is NOT just 'Java on Linux'
Android is NOT just 'Java on Linux'Android is NOT just 'Java on Linux'
Android is NOT just 'Java on Linux'
 
Hunting for Privilege Escalation in Windows Environment
Hunting for Privilege Escalation in Windows EnvironmentHunting for Privilege Escalation in Windows Environment
Hunting for Privilege Escalation in Windows Environment
 
iOS Application Pentesting
iOS Application PentestingiOS Application Pentesting
iOS Application Pentesting
 
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytes
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytesWindows Kernel Exploitation : This Time Font hunt you down in 4 bytes
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytes
 
PSConfEU - Offensive Active Directory (With PowerShell!)
PSConfEU - Offensive Active Directory (With PowerShell!)PSConfEU - Offensive Active Directory (With PowerShell!)
PSConfEU - Offensive Active Directory (With PowerShell!)
 
Vm escape: case study virtualbox bug hunting and exploitation - Muhammad Alif...
Vm escape: case study virtualbox bug hunting and exploitation - Muhammad Alif...Vm escape: case study virtualbox bug hunting and exploitation - Muhammad Alif...
Vm escape: case study virtualbox bug hunting and exploitation - Muhammad Alif...
 
Hunting for Credentials Dumping in Windows Environment
Hunting for Credentials Dumping in Windows EnvironmentHunting for Credentials Dumping in Windows Environment
Hunting for Credentials Dumping in Windows Environment
 
Android Memory Management
Android Memory ManagementAndroid Memory Management
Android Memory Management
 
Practical Malware Analysis: Ch 10: Kernel Debugging with WinDbg
Practical Malware Analysis: Ch 10: Kernel Debugging with WinDbgPractical Malware Analysis: Ch 10: Kernel Debugging with WinDbg
Practical Malware Analysis: Ch 10: Kernel Debugging with WinDbg
 
iOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for BeginnersiOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for Beginners
 
Windows 10 Nt Heap Exploitation (English version)
Windows 10 Nt Heap Exploitation (English version)Windows 10 Nt Heap Exploitation (English version)
Windows 10 Nt Heap Exploitation (English version)
 
Practical Malware Analysis Ch13
Practical Malware Analysis Ch13Practical Malware Analysis Ch13
Practical Malware Analysis Ch13
 
Bypass_AV-EDR.pdf
Bypass_AV-EDR.pdfBypass_AV-EDR.pdf
Bypass_AV-EDR.pdf
 
Derbycon - The Unintended Risks of Trusting Active Directory
Derbycon - The Unintended Risks of Trusting Active DirectoryDerbycon - The Unintended Risks of Trusting Active Directory
Derbycon - The Unintended Risks of Trusting Active Directory
 
The Android graphics path, in depth
The Android graphics path, in depthThe Android graphics path, in depth
The Android graphics path, in depth
 
Practical Malware Analysis: Ch 2 Malware Analysis in Virtual Machines & 3: Ba...
Practical Malware Analysis: Ch 2 Malware Analysis in Virtual Machines & 3: Ba...Practical Malware Analysis: Ch 2 Malware Analysis in Virtual Machines & 3: Ba...
Practical Malware Analysis: Ch 2 Malware Analysis in Virtual Machines & 3: Ba...
 
Android Internals at Linaro Connect Asia 2013
Android Internals at Linaro Connect Asia 2013Android Internals at Linaro Connect Asia 2013
Android Internals at Linaro Connect Asia 2013
 

Andere mochten auch

Advanced Evasion Techniques by Win32/Gapz
Advanced Evasion Techniques by Win32/GapzAdvanced Evasion Techniques by Win32/Gapz
Advanced Evasion Techniques by Win32/Gapz
Alex Matrosov
 

Andere mochten auch (20)

Process injection - Malware style
Process injection - Malware styleProcess injection - Malware style
Process injection - Malware style
 
Code Injection in Windows
Code Injection in WindowsCode Injection in Windows
Code Injection in Windows
 
Captain Hook: Pirating AVs to Bypass Exploit Mitigations
Captain Hook: Pirating AVs to Bypass Exploit MitigationsCaptain Hook: Pirating AVs to Bypass Exploit Mitigations
Captain Hook: Pirating AVs to Bypass Exploit Mitigations
 
Steelcon 2014 - Process Injection with Python
Steelcon 2014 - Process Injection with PythonSteelcon 2014 - Process Injection with Python
Steelcon 2014 - Process Injection with Python
 
Reversing & malware analysis training part 3 windows pe file format basics
Reversing & malware analysis training part 3   windows pe file format basicsReversing & malware analysis training part 3   windows pe file format basics
Reversing & malware analysis training part 3 windows pe file format basics
 
linux kernel overview 2013
linux kernel overview 2013linux kernel overview 2013
linux kernel overview 2013
 
PenTest Magazine Teaser - Mobile Hacking
PenTest Magazine Teaser - Mobile HackingPenTest Magazine Teaser - Mobile Hacking
PenTest Magazine Teaser - Mobile Hacking
 
Advanced Evasion Techniques by Win32/Gapz
Advanced Evasion Techniques by Win32/GapzAdvanced Evasion Techniques by Win32/Gapz
Advanced Evasion Techniques by Win32/Gapz
 
Network Forensics Intro
Network Forensics IntroNetwork Forensics Intro
Network Forensics Intro
 
Minha doce flauta doce vol 01
Minha doce flauta doce vol 01Minha doce flauta doce vol 01
Minha doce flauta doce vol 01
 
Advanced Malware Analysis Training Session 4 - Anti-Analysis Techniques
Advanced Malware Analysis Training Session 4 - Anti-Analysis TechniquesAdvanced Malware Analysis Training Session 4 - Anti-Analysis Techniques
Advanced Malware Analysis Training Session 4 - Anti-Analysis Techniques
 
Linux kernel architecture
Linux kernel architectureLinux kernel architecture
Linux kernel architecture
 
Bypassing patchguard on Windows 8.1 and Windows 10
Bypassing patchguard on Windows 8.1 and Windows 10Bypassing patchguard on Windows 8.1 and Windows 10
Bypassing patchguard on Windows 8.1 and Windows 10
 
Embedded C programming based on 8051 microcontroller
Embedded C programming based on 8051 microcontrollerEmbedded C programming based on 8051 microcontroller
Embedded C programming based on 8051 microcontroller
 
Manipulating Memory for Fun & Profit
Manipulating Memory for Fun & ProfitManipulating Memory for Fun & Profit
Manipulating Memory for Fun & Profit
 
Spying Internet Explorer 8.0
Spying Internet Explorer 8.0Spying Internet Explorer 8.0
Spying Internet Explorer 8.0
 
Userland Hooking in Windows
Userland Hooking in WindowsUserland Hooking in Windows
Userland Hooking in Windows
 
Inline Hooking in Windows
Inline Hooking in WindowsInline Hooking in Windows
Inline Hooking in Windows
 
Client-side threats - Anatomy of Reverse Trojan attacks
Client-side threats - Anatomy of Reverse Trojan attacksClient-side threats - Anatomy of Reverse Trojan attacks
Client-side threats - Anatomy of Reverse Trojan attacks
 
Defeating Data Execution Prevention and ASLR in Windows
Defeating Data Execution Prevention and ASLR in WindowsDefeating Data Execution Prevention and ASLR in Windows
Defeating Data Execution Prevention and ASLR in Windows
 

Ähnlich wie Injection on Steroids: Codeless code injection and 0-day techniques

Ähnlich wie Injection on Steroids: Codeless code injection and 0-day techniques (20)

Practical Malware Analysis Ch12
Practical Malware Analysis Ch12Practical Malware Analysis Ch12
Practical Malware Analysis Ch12
 
Practical Windows Kernel Exploitation
Practical Windows Kernel ExploitationPractical Windows Kernel Exploitation
Practical Windows Kernel Exploitation
 
how-to-bypass-AM-PPL
how-to-bypass-AM-PPLhow-to-bypass-AM-PPL
how-to-bypass-AM-PPL
 
Metasploit & Windows Kernel Exploitation
Metasploit & Windows Kernel ExploitationMetasploit & Windows Kernel Exploitation
Metasploit & Windows Kernel Exploitation
 
CNIT 126 12: Covert Malware Launching
CNIT 126 12: Covert Malware LaunchingCNIT 126 12: Covert Malware Launching
CNIT 126 12: Covert Malware Launching
 
Offensive Python for Pentesting
Offensive Python for PentestingOffensive Python for Pentesting
Offensive Python for Pentesting
 
Mapping Detection Coverage
Mapping Detection CoverageMapping Detection Coverage
Mapping Detection Coverage
 
CNIT 126: 10: Kernel Debugging with WinDbg
CNIT 126: 10: Kernel Debugging with WinDbgCNIT 126: 10: Kernel Debugging with WinDbg
CNIT 126: 10: Kernel Debugging with WinDbg
 
Piratng Avs to bypass exploit mitigation
Piratng Avs to bypass exploit mitigationPiratng Avs to bypass exploit mitigation
Piratng Avs to bypass exploit mitigation
 
Security research over Windows #defcon china
Security research over Windows #defcon chinaSecurity research over Windows #defcon china
Security research over Windows #defcon china
 
CNIT 126: 10: Kernel Debugging with WinDbg
CNIT 126: 10: Kernel Debugging with WinDbgCNIT 126: 10: Kernel Debugging with WinDbg
CNIT 126: 10: Kernel Debugging with WinDbg
 
Owning computers without shell access 2
Owning computers without shell access 2Owning computers without shell access 2
Owning computers without shell access 2
 
Windows internals
Windows internalsWindows internals
Windows internals
 
Deep hooks
Deep hooksDeep hooks
Deep hooks
 
Typhoon Managed Execution Toolkit
Typhoon Managed Execution ToolkitTyphoon Managed Execution Toolkit
Typhoon Managed Execution Toolkit
 
Docker Security
Docker SecurityDocker Security
Docker Security
 
The State of the Veil Framework
The State of the Veil FrameworkThe State of the Veil Framework
The State of the Veil Framework
 
Tool up your lamp stack
Tool up your lamp stackTool up your lamp stack
Tool up your lamp stack
 
Tool Up Your LAMP Stack
Tool Up Your LAMP StackTool Up Your LAMP Stack
Tool Up Your LAMP Stack
 
Defcon 27 - Writing custom backdoor payloads with C#
Defcon 27 - Writing custom backdoor payloads with C#Defcon 27 - Writing custom backdoor payloads with C#
Defcon 27 - Writing custom backdoor payloads with C#
 

Kürzlich hochgeladen

%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Kürzlich hochgeladen (20)

WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 

Injection on Steroids: Codeless code injection and 0-day techniques

  • 1.
  • 2. Who? • Udi Yavo • CTO and Co-Founder, enSilo • Former CTO, Rafael Cyber Security Division • Low Level Researcher • Author on BreakingMalware • Tomer Bitton • VP Research and Co-Founder, enSilo • Low Level Researcher, Rafael Advanced Defense Systems • Malware Researcher • Author on BreakingMalware
  • 3. Agenda • User-Mode Injections Classic Code Injection Methods Advanced Injections - PowerLoader PowerLoaderEx PowerLoaderEx64 • Kernel-Mode Injections Common Injection Methods Introducing Trap Frame Injection Codeless Code Injection Demo • Summary
  • 5. Classic Code Injection Methods • Vanila Injection - OpenProcess/ VirtualAllocEx/CreateRemoteThread/LoadLibrary • GetThreadContext / SetThreadContext • SetWindowsHookEx • AppInit_DLLs and APPCERTDLLs • ShimEng (InjectDll Tag) • SetWindowLong • QueueUserApc • Replace Dependency DLL • …
  • 6. PowerLoader – POP/POP/INJECT • Loader used in many different dropper families (Gapz / Redyms / Carberp / Vabushky ...) • Technique was leaked with Carberp source code leak. • First injection technique via Return Oriented Programming technique (ROP). • “explorer.exe” is injected using Shell_TrayWnd / NtQueueApcThread (32bit / 64bit) • Successfully bypassed most HIPSs solutions 1. http://www.welivesecurity.com/2013/03/19/gapz-and-redyms-droppers-based-on-power-loader-code/ 2. http://www.slideshare.net/matrosov/advanced-evasion-techniques-by-win32gapz 3. https://www.virusbtn.com/virusbulletin/archive/2012/10/vb201210-code-injection 4. http://www.malwaretech.com/2013/08/powerloader-injection-something-truly.html  Samples and valuable info - http://www.kernelmode.info/forum/
  • 7. PowerLoader – Abusing Shared Sections • Explorer.exe has several shared memory sections it uses: • By calling NtOpenSection and ZwMapViewOfSection PowerLoader maps one of the shared sections to its own address space • PowerLoader finds the address of the shared section in explorer by calling VirtualQueryEx / ReadProcessMemory / RtlCompareMemory combination • The shellcode is than written to the shared section. There is no need for VirtualAllocEx / WriteProcessMemory which is monitored by many HIPS
  • 8. PowerLoader - Triggering Code Execution • One of the Windows in Explorer.exe is Shell_TrayWnd • The Shell_TrayWnd window has a pointer to CTray class object which handles messages to the window • Once the Shell_TrayWnd window is found PowerLoader uses SetWindowLongPtr to replace the CTray object with a malicious CTray Object in the shared section • The shared section is not executable thus ROP is needed • The virtual table of the malicious CTray object point to KiUserApcDispatcher routine which eventually trigger the ROP execution • To trigger code execution SendNotifyMessage is called with WM_PAINT message
  • 9. PowerLoader - ROP n’ Roll • PowerLoader uses a complex ROP chain • Basic steps by the ROP chain (High-Level): • Direction Flag Set • Copy ROP chain to stack • Direction Flag Clear • Use WriteProcessMemory to overwrite ntdll!atan function (this function is probably not used in the context of explorer.exe) • Pass control to the overwritten ntdll!atan function
  • 10. PowerLoader - Quick Summary • Advanced Injection technique • Completely bypassed most HIPS at the time • Using Exploit-Like techniques: • The first Injection technique to use ROP (to our knowledge) • Overwrites atan function using WriteProcessMemory • No similar 64-bit version (to our knowledge) • Try to run vs EMET and see what happens… • Very application specific: • Targets Shell_TrayWnd of explorer.exe • Uses specific shared sections • Doesn’t use direct code injections
  • 11. Introducing PowerLoaderEx Goals: • Remove dependency in Explorer.exe shared sections (more generic) • Make a 64-bit version • Bonus: Do it without reading memory from the target process
  • 12. UI Shared Memory - Reminder • UI Objects are stored in one of three places: • Session Pool – Allocated per user logon • Desktop Heap – Stores objects specific to a given Desktop • Shared Heap – Handle Table and object relevant to all Desktops • The heaps are visible to user-mode via shared-memory • Commonly used for exploiting privilege escalation vulnerabilities • Extensively documented in: “Windows Hooks Of Death: Kernel Attacks through User-Mode Callbacks” – By Tareji Mandt
  • 13. UI Shared Memory Kernel Space User Space Application 1 Desktop Heap 1 Shared Section Handle Table Shared Heap Shared Section Handle Table Shared Heap Desktop Heap 1 Application 2 Desktop Heap 1 Shared Section Handle Table Shared Heap
  • 14. PowerLoaderEx – Desktop Heap as Shared Section • Desktop Heaps are better as shared section because they are mapped to any process on a given desktop • Writing arbitrary data to the Desktop Heap is easy: • Create a window with enough extra bytes • Use SetWindowLongPtr to write the payload • But how do know where it resides in a target process?
  • 15. Finding Target Process’s Desktop Heap • Find the Desktop Heap in our process and find its region size • Enumerate explorer.exe memory regions by calling VirtualQuery. • The target’s Desktop Heap is found if the region characteristics are: • State: MEM_COMMIT • Type: MEM_MAPPED • Protect: PAGE_READ_ONLY • RegionSize is equal to the previously obtained heapSize. Double Check – Avoiding False Positives • We had NO false positives in finding the shared desktop heap (local process and target process) • The following check will remove any false-positive: * Note: using the double check version will require calling NtOpenProcess with QUERY_INFORMATION and PROCESS_VM_OPERATION
  • 16. Finding The Gadgets • We do the gadget lookup in our own process • Load and scan only modules that we know that are always loaded in the target process (i.e. explorer.exe) • Use only modules that are very likely to have the same base in both processes: • ntdll.dll • Kernel32.dll • Kernelbase.dll • User32.dll • Shell32.dll
  • 17. PowerLoaderEx - Look Ma, No Read! 1. Create a window and find it in the shared desktop heap 2. Find the target process (Explorer.exe) and find where the desktop heap is mapped, requires only PROCESS_QUERY_INFORMATION privileges 3. Scan for the required gadgets 4. Write the payload to the shared desktop heap using SetWindowLongPtr 5. Continue like normal PowerLoader * Note: If a different target process has more than one Desktop Heap mapped read will be needed
  • 18. PowerLoaderEx64 - What About 64-bit? • Challenges: • Much harder to find useful gadgets • No code writing allowed • No reads allowed
  • 19. PowerLoaderEx64 – Remember the CTray Object? The Controlled Ctray Object Virtual Calls CImpWndProc::s_WndProc
  • 20. PowerLoaderEx64 - Strategy • Find some function that can be manipulated to call LoadLibrary with controlled first argument • Make sure no crashes occur after/during library loading • To make things simple point 2 of the 3 virtual calls to “Do Nothing” functions (Ret opcode)
  • 21. PowerLoaderEx64 – User32 Callbacks To Rescue The Controlled Ctray Object Should be NULL Pointer to DLL Path Pointer to LoadLibraryA
  • 22. PowerLoaderEx64 - Recap 1. Create a window and find it in the shared desktop heap 2. Find the target process (Explorer.exe) and find where the desktop heap is mapped, requires only PROCESS_QUERY_INFORMATION privileges 3. Write the malicious CTray object to the shared desktop heap using SetWindowLongPtr 4. Replace the Shell_TrayWnd window’s CTray object using SetWindowLongPtr 5. Use SendNotifyMessage to trigger LoadLibrary PowerLoaderEx64 source code will be on BreakingMalware http://BreakingMalware.com
  • 24. Introduction - Kernel-To-User Code Injections • Mainly used for: • Injecting DLLs • Sandbox escapes – After exploiting privilege escalation vulnerability • Injecting to protected processes • Fewer techniques exist than user-mode • Less documented than user-mode techniques • Used by both Malware and Software/Security vendors
  • 25. Common Injection Methods – User APC • The most common Kernel-To-User injection method • Used by lots of malwares: • TDL • ZERO ACCESS • Sandbox escape shellcodes • … • Also used by lots of security products: • AVG • Kaspersky Home Edition • Avecto • … • Documented: • Blackout: What Really Happened • Much more in forums and leaked source codes
  • 26. Common Injection Methods – User APC Basic Steps (There are several variations): 1. Register load image callback using PsSetLoadImageNotifyRoutine and wait for main module to load 2. Write payload that injects a dll using LdrLoadDll (Other variations use LoadLibrary) 3. Insert User APC using KeInsertQueueApc
  • 27. Common Injection Methods – Entry Point Patching • Not really common but worth mentioning • Used by Duqu • Fully documented in: http://binsec.gforge.inria.fr/pdf/Malware2013-Analysis-Diversion-Duqu-paper.pdf
  • 28. Ntoskrnl.exe Common Injection Methods – Entry Point Patching • Register load image callback using PsSetLoadImageNotifyRoutine and wait for main module to load Kernel Space User Space Application RtlUserThreadStart KiStartUserThread EvilDriver.sys Callback Routine Process Image
  • 29. Ntoskrnl.exe Common Injection Methods – Entry Point Patching • Write the payload to the process address space Kernel Space User Space Application RtlUserThreadStart KiStartUserThread EvilDriver.sys Callback Routine Payload Process Image
  • 30. Ntoskrnl.exe Common Injection Methods – Entry Point Patching • Replace the image entry point with JMP to the new code Kernel Space User Space Application RtlUserThreadStart KiStartUserThread EvilDriver.sys Callback Routine Payload Process Image JMP Payload
  • 31. Ntoskrnl.exe Common Injection Methods – Entry Point Patching • The payload executes, fixes the entry point and jumps to it Kernel Space User Space Application RtlUserThreadStart KiStartUserThread EvilDriver.sys Callback Routine Payload Process Image Jump to entry point
  • 32. Common Injection Methods – Import Table Patching • Undocumented (to our knowledge) • Never been used by malware (to our knowledge) • Used by software and security vendors: • Symantec • Trusteer • Microsoft App-V • Similar method could probably use TLS data directory
  • 33. Common Injection Methods – Import Table Patching 1. Register load image callback using PsSetLoadImageNotifyRoutine and wait for main module to load 2. Allocate memory for the new import table and copy old table with a new record for the injected DLL 3. Point the import data directory to the new table 4. When the DLL is loaded the original PE header is restored PE Header MZ Header DOS Stub File Header Optional Header Data Directories Imports … Import Descriptor 1 Import Descriptor 2 Before PE Header MZ Header DOS Stub File Header Optional Header Data Directories Imports … Import Descriptor 1 Import Descriptor 2 After Import Descriptor 1 Import Descriptor 2 Injected DLL Descriptor …
  • 34. Common Injection Methods – Quick Summary • Kernel-To-User Injections are extensively used by both malware and security/software vendors • Kernel injections are mainly used to inject a DLL to target(or all) processes • All these methods require injection of some payload to user mode (except for Import Table Patching) • All use PsSetLoadImageNotifyRoutine
  • 35. Introducing Trap Frame Injection • A new kernel-to-user injection technique • Trap frames save the CPU user-mode state during exceptions or interrupt handling • A Trap frame is created each time a system call is made and stored on the kernel stack • The kernel structure used for trap frames is _KTRAP_FRAME • The user-mode state is restored when the system call returns • Current frame is stored in the TrapFrame field of _KTHREAD
  • 37. Ntoskrnl.exe The Trivial Injection • Wait for some callback that runs in context of a system call (Thread Creation, Registry Access,…) Kernel Space User Space Application CreateThread NtCreateThreadEx EvilDriver.sys Callback Routine
  • 38. Ntoskrnl.exe The Trivial Injection • Allocate payload in the target application Kernel Space User Space Application CreateThread NtCreateThreadEx EvilDriver.sys Callback Routine Payload
  • 39. Ntoskrnl.exe The Trivial Injection • Fix the trap frame’s saved RIP/EIP to the payload Kernel Space User Space Application CreateThread NtCreateThreadEx EvilDriver.sys Callback Routine Payload
  • 40. Ntoskrnl.exe The Trivial Injection • The payload runs and restores normal execution Kernel Space User Space Application CreateThread NtCreateThreadEx EvilDriver.sys Callback Routine Payload
  • 41. But We Promised a Codeless Code Injection… Goals: • Run code in the context of an arbitrary process: Force IExplore.exe to send POST Open remote shell … • Easy to write Limitation: • No code injections to the process
  • 42. Ntoskrnl.exe Codeless Code Injection • Wait for some callback that runs in context of a system call (Thread Creation, Registry Access,…) Kernel Space User Space Application CreateThread NtCreateThreadEx EvilDriver.sys Callback Routine User Stack … NtCreateThreadEx ESP
  • 43. Ntoskrnl.exe Codeless Code Injection • Build ROP Chain on the user stack Kernel Space User Space Application CreateThread NtCreateThreadEx EvilDriver.sys Callback Routine User Stack … NtCreateThreadEx “MyLib.dll” RETN address LoadLibraryA ESP
  • 44. Ntoskrnl.exe Codeless Code Injection • Set the stack pointer to the start of the ROP chain Kernel Space User Space Application CreateThread NtCreateThreadEx EvilDriver.sys Callback Routine User Stack … NtCreateThreadEx “MyLib.dll” RETN address LoadLibraryAESP
  • 45. Codeless Code Injection - Challenges • Getting Return Values – how do we get return values back to kernel mode • Solution 1: Use device handle to get notifications (deep dive coming up) • Solution 2: Save return value somewhere and trigger some hook-able event (Such as registry access) • Deadlocks – if the user mode caller holds a lock that our injected function needs • Solution: Use a dedicated thread • Callback – What if we need to a user-mode callback function • Solution 1: Use a function that always triggers some hook-able event and fix the context • Solution 2: Just don’t use such functions 
  • 46. Codeless Code Injection - NtClose as a callback • Create a device using IoCreateDevice • Whenever we require a callback, create a handle for the device in the target process • Build the following ROP chain: User Stack … Device Handle RETN address NtClose MOV [EDX], EAX Gadget Writable Location POP EDX Gadget … ESP = MOV EDX, ADDRESS MOV [EDX], EAX NtClose(DeviceHandle)
  • 47. Codeless Code Injection - NtClose as a callback • When NtClose(Device Handle) is executed then the IRP_MJ_CLEANUP handler will be called • The required data will reside in the target address * moving EAX to some register is not safe because of WOW64 ESP User Stack … Device Handle RETN address NtClose MOV [EDX], EAX Gadget Writable Location POP EDX Gadget …
  • 48. Codeless Code Injection – Creating dedicated thread HANDLE WINAPI CreateThread( _In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes, _In_ SIZE_T dwStackSize, _In_ LPTHREAD_START_ROUTINE lpStartAddress, _In_opt_ LPVOID lpParameter, _In_ DWORD dwCreationFlags, _Out_opt_ LPDWORD lpThreadId ); DWORD WINAPI ThreadProc(_In_ LPVOID lpParameter); NtClose Device Handle
  • 49. • Wait for some callback that runs in context of a system call (Thread Creation, Registry Access,…) • Build the following ROP Chain • When Handle cleanup is triggered start injecting ROP chains to the new thread Codeless Code Injection – Creating a Dedicated Thread ESP User Stack … 0 0 Device Handle NtClose 0 NULL RETN address CreateThread … = CreateThread(NULL, 0, NtClose, Device Handle, 0, 0);
  • 50. Codeless Code Injection – API ROProgram *CreateProgram(CHAR* TargetName) – Creates a ROP program that’s to be run in a target process AddStep(ROProgram* Program, ROProgramStepProc StepProc)– Adds a step to the program. A Single ROP chain that ends in callback(NtClose) RunProgram(ROProgram* Program) – Wait’s for the target process to create a thread and starts a new dedicated thread UserLibrary OpenUserLibrary(CHAR* LibName)– Finds a DLL in the target process memory Call(ROPChain* RopChain, UserLibrary Module, CHAR* Function, u32 NumberOfArgs, ...) – Add a call to a ROP chain LoadLibrary(ROPChain* RopChain, char* Name) – Load a Library into the target process WriteToUser(ROPChain* RopChain, u8* Buf, u32 BufSize) – Writes a buffer of data to user-mode
  • 51. Codeless Code Injection – API Example ROProgram* Program = CreateProgram("iexplore.exe“); AddStep(Program, LoadSomeLibrary); RunProgram(Program); … bool LoadSomeLibrary(ROProgram* Program, ROPChain* Chain){ return LoadLibrary(Chain, “MyLibrary.dll”); } Load a new library to the target process:
  • 53. Summary • Code injection remains an important capability for both malware and security/software vendors • Like exploits, techniques are becoming less generic (PowerLoader) • New User and Kernel injection techniques are constantly being invented • We can probably expect new advanced injection methods in the near future • Slides and Source-code will be available on BreakingMalware in a few days
  • 54. @enSiloSec Company/enSilo ensilo.com/blog contact@ensilo.comwww.enSilo.com