This document discusses techniques for injecting code into processes without directly writing code to the target process's memory. It introduces a technique called "Trap Frame Injection" which hijacks the CPU's user mode state that is stored in trap frames during system calls. It also presents a "Codeless Code Injection" technique which builds ROP chains on the user stack and manipulates the stack pointer to trigger execution without direct code writes. Challenges with this approach like getting return values and avoiding deadlocks are also outlined along with solutions like using a device handle callback or creating a dedicated thread.
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
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
…
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