Captain Hook:Pirating AVS to Bypass Exploit Mitigations

WHO?
Udi Yavo CTO and Co-Founder, enSilo
 Former CTO, Rafael Cyber Security Division
 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 Hooking In a Nutshell Scope of Research Inline Hooking – Under the hood
- 32-bit function hooking- 64-bit function hooking
 Hooking Engine Injection Techniques The 6 Security Issues of Hooking
 Demo – Bypassing exploit mitigations
 3rd Party Hooking Engines Affected Products
 Research Tools

 SummaryHOOKING IN A NUTSHELL
 Hooking is used to intercept function calls in order to alter oraugment their behavior

 Used in most endpoint security products:• Anti-Exploitation – EMET, Palo-Alto Traps, …
• Anti-Virus – Almost all of them
• Personal Firewalls – Comodo, Zone-Alarm,…
• …
 Also used in non-security products for various purposes:• Application Performance Monitoring (APM)• Application Virtualization (Microsoft App-V)
 Used in Malware:• Man-In-The-Browser (MITB)SCOPE OF RESEARCH Our research encompassed about a dozen security products
 Focused on user-mode inline hooks – The most common hooking
method in real-life products Hooks are commonly set by an injected DLL. We’ll refer to this DLL
as the “Hooking Engine”
 Kernel-To-User DLL injection techniques• Used by most vendors to inject their hooking engine• Complex and leads security issues

Inline Hooking

INLINE HOOKING – 32-BIT FUNCTION HOOKING
Straight forward most of the time:

Disassemble
Prolog

Allocate
Code Stub

Copy Prolog
Instructions

Patch theProlog with aJMPINLINE HOOKING – 32-BIT FUNCTION HOOKING
InternetConnectW before the hook is set:

InternetConnectW After the hook is set:

INLINE HOOKING – 32-BIT FUNCTION HOOKING
The hooking function (0x178940)

The Copied Instructions

Original Function CodeINLINE HOOKING – 32-BIT FUNCTION HOOKING Other Techniques:• One Byte Patching (Malware) - Patch with an illegal instruction and catch inthe exception handler• Microsoft Hot Patching – Only 2 bytes function prolog overwrite

Hooking Function

 Some Possible Complications:• Relative jmp/call in the prolog• Very short functions/short prolog• jmp/jxx to the middle of the prolog’s instruction• …

INLINE HOOKING – 64-BIT FUNCTION HOOKING• More complex• 5 bytes jmp instruction might not be enough (limited to a 2GB range)

Disassemble
Prolog

Allocate
Trampoline

Allocate
Code Stub

Write
Trampoline

MOV RAX, <Hooking Function>
JMP RAX

Copy Prolog
Instructions

Patch theProlog with aJMPINLINE HOOKING – 64-BIT FUNCTION HOOKING• InternetConnectA before the hook is set:

• InternetConnectA after the hook is set:

• Trampoline code:INLINE HOOKING – 64-BIT FUNCTION HOOKING
If we follow the hooking function we get:Original Function CodeINLINE HOOKING – 64-BIT FUNCTION HOOKING Other Techniques: 6 Bytes patching (requires hooks’ code stub to be in 32-bit address)

 Double Push (Nikolay Igotti) – Preserves all registers
Jumps to 0x7ffc00030000

 …
 Possible Complications: Similar to 32-bit hooks
 More instruction pointer relative instructions:
MOV RAX, QWORD [RIP+0x15020]

INLINE HOOKING – RECAP Inline hooking is the most common hooking technique in real-life products Rather intrusive – modifies the code of the of hooking function
 Used by most endpoint security products More on hooking:• Binary Hooking Problems - By Gil Dabah• Trampolines in X64 - By Gil Dabah• Powerful x86/x64 Mini Hook-Engine - Daniel Pistelli• Inline Hooking for Programmers - Malware Tech
• …

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

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

INJECTION METHODS – USER APC
Basic Steps (There are several variations):

1. Register load image callback using PsSetLoadImageNotifyRoutine
2. Write payload that injects a dll using LdrLoadDll(Other variations use LoadLibrary)

3. Insert User APC using KeInsertQueueApc

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

INJECTION METHODS – ENTRY POINT PATCHING• Register load image callback using PsSetLoadImageNotifyRoutine
and wait for main module to loadKernel SpaceNtoskrnl.exe

EvilDriver.sys

KiStartUserThread

Callback Routine

Application
User Space

RtlUserThreadStart
Process ImageINJECTION METHODS – ENTRY POINT PATCHING• Write the payload to the process address space

Kernel Space

Ntoskrnl.exe

EvilDriver.sys

KiStartUserThread

Callback Routine

Application
User Space

RtlUserThreadStart
Process Image
PayloadINJECTION METHODS – ENTRY POINT PATCHING• Replace the image entry point with JMP to the new code

Kernel Space

JMP Payload
User Space

Ntoskrnl.exe

EvilDriver.sys

KiStartUserThread

Callback Routine

ApplicationRtlUserThreadStart
Process Image
PayloadINJECTION METHODS – ENTRY POINT PATCHING• The payload executes, fixes the entry point and jumps to it

Kernel Space

JMP Payload
User Space

Ntoskrnl.exe

EvilDriver.sys

KiStartUserThread

Callback Routine

Application
RtlUserThreadStart
Process Image
PayloadJump to entry point

INJECTION METHODS – ENTRY POINT PATCHING• Internet Explorer patched entrypoint

INJECTION METHODS – IMPORT TABLE PATCHING First published on Codeless-Code-Injections talk (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

INJECTION METHODS – IMPORT TABLE PATCHING
1.

2.

Register load image callback using
PsSetLoadImageNotifyRoutine and wait for main
module to load

Allocate memory for the new import table and copy
old table with a new record for the injected DLL
Before3.

Point the import data directory to the newtable

4.

When the DLL is loaded the original PE
header is restored

AfterInjected DLL Descriptor
PE Header
MZPE Header
MZ

Import Descriptor 1

DOS Stub

DOS StubImport Descriptor 2File Header

File Header…

Optional Header

Optional Header

Data Directories
Imports

Data Directories
Imports…

…

Import Descriptor 1

Import Descriptor 1

Import Descriptor 2

Import Descriptor 2

INJECTION METHODS – IMPORT TABLE PATCHINGInternet Explorer patched import table

INJECTION METHODS – NTDLL.DLL/USER32.DLL PATCHING• Register load image callback using PsSetLoadImageNotifyRoutine
and wait for ntdll.dll module to loadKernel SpaceNtoskrnl.exe

EvilDriver.sys

KiStartUserThread

Callback Routine

ApplicationUser Space

RtlUserThreadStart
LdrLoadDll

INJECTION METHODS – NTDLL.DLL/USER32.DLL PATCHING• Write the payload to the process address space

Kernel Space

Ntoskrnl.exe

EvilDriver.sys

KiStartUserThread

Callback Routine

Application
User Space

RtlUserThreadStart
LdrLoadDll
PayloadINJECTION METHODS – NTDLL.DLL/USER32.DLL PATCHING• Replace the LdrLoadLibrary prolog with JMP (or equivalent) to the payload

Kernel Space

JMP Payload
User Space

Ntoskrnl.exe

EvilDriver.sys

KiStartUserThread

Callback Routine

ApplicationRtlUserThreadStart
LdrLoadDll
PayloadINJECTION METHODS – NTDLL.DLL/USER32.DLL PATCHING• The payload loads a dll, fixes LdrLoadDll and jumps to it

Kernel Space

JMP Payload
User Space

Ntoskrnl.exe

EvilDriver.sys

KiStartUserThread

Callback Routine

Application
RtlUserThreadStart
LdrLoadDll
PayloadJump to LdrLoadDll

INJECTION METHODS – QUICK SUMMARY• Kernel-To-User Injections are extensively used by bothmalware and security/software products• Kernel injections are mainly used to inject a DLL totarget processes• In security products the injected DLL is commonly thehooking engine• Prone to mistakes – due to its relative complexity

The 6 security issues of hooking

#1 – UNSAFE INJECTION
Severity: Very High
Affected Systems: All Windows Versions

Occurs due to bad DLL injection implementation
 We found 2 types of unsafe injections:• LoadLibrary from a relative path – vulnerableto DLL Hijacking• Unprotected injected DLL file – placed in%appdata%\Local\Vendor
Can easily be replaced by the attacker

#2 – PREDICTABLE RWX CODE STUBSSeverity: Very High
Affected Systems: All Windows Versions

The Kernel-To-User DLL injection allocates RWX code in a
predictable location

Functions pointers in constant addresses

RWX Permissions• Implications:• ASLR Bypass – The code stubs normally contains
addresses of critical OS functions• Great for shellcode – Allows writing malicious code
to the allocated code-stub#3 – PREDICTABLE R-X CODE STUBS
Severity: Very High
Affected Systems: All Windows Versions

The Kernel-To-User DLL injection or hooking engine
allocates R-X code in a predictable location
Implications:• ASLR Bypass – The code stubs contain the addressesof critical OS functions• Hooks Bypass – Calling the hook code stubeffectively bypasses the hook
• Code Reuse – The code can also be useful for ROP

#4 – PREDICTABLE RWX CODE STUBS 2Severity: High
Affected Systems: Windows 7 and Below

The Kernel-To-User DLL injection allocates RWX code
without specifying exact address
Implications:• Similar to the first predictable RWX Code issue

#5 –RWX CODE STUBS
Severity: Medium
Affected Systems: All Windows Versions

The most common issue: most hooking engines leave theirhook code stubs as RWXThe implication - possible CFG bypass:• Get arbitrary read/write in the target process• Find the hook’s stub (R)• Overwrite it (W)• Trigger the execution of the hooked function (X)* Note: Attacker with arbitrary read/write will probably succeed anyway

#6 –RWX HOOKED MODULES
Severity: Medium
Affected Systems: All Windows Versions

Some hooking engines leave the code of the hooked
modules as RWX
The implication - possible CFG bypass

LdrLoadDll Hook

RWX Permissions

SECURITY ISSUES OF HOOKING - RECAP

DemoBypassing Exploit Mitigations

3rd Party Hooking Engines

3RD PARTY HOOKING ENGINES
 Developing a hooking engine is not an easy task
 Using open-source* or commercial hooking engines has many advantages:• Easy API to work with• Supports many platforms• Saves development effort• Saves testing effort
 3rd party hooking engines are also integrated into non-security products
 A security issue in a hooking engine results in many patches…

* We really like Gil Dabah’s distormx

EASYHOOK – OPEN-SOURCE HOOKING ENGINE Used by many open-source projects
 Also used by a few security vendors. For example, VeraFeatures:
 Kernel Hooking support
 Thread Deadlock Barrier
 RIP-relative address relocation for 64-bit
 …
Security Issues:
 RWX Hook Code Stubs
 RWX Hooked Modules
Bad Practice: Uses Non-Executable heap and changes parts of it to code

DEVIARE2 - OPEN-SOURCE HOOKING ENGINE Dual License – Commercial or GPL for open-source Fixed the issues quickly
 From their web site:“Several Fortune 500 companies are using Deviare technology for application
virtualization, packaging, and troubleshooting, and for computer security.”

Features: Defer Hook –Set a hook only when and if a module is loaded
 .NET Function hooking

 Interface for many languages: (C++, VB, Python, C#,…) …
Security Issues:
 RWX Hook Code Stubs

MADCODEHOOK – POWERFUL COMMERCIAL HOOKING Used by a lot for security vendors (75% of its users) Used by emsisoft Fixed the issues quicklyFeatures: Injection Driver – Used to perform kernel-injection into processes
 IPC API –Used to easily communicate with some main process
 IAT Hooking

 …
Security Issues:
 RWX Hook Code Stubs

MICROSOFT DETOURS The most popular hooking engine in the world
 Microsoft’s App-V uses Detours which is integrated into Office We were surprised to find out that it has problems too…
Features: ARM support
 …
Security Issues:• Predictable RX (Universal).

* Details won’t be revealed until the patch is released (September)

MICROSOFT DETOURS VULNERABILITY - IMPLICATIONS Microsoft’s hooking engine Detours – via Microsoft.com:“Under commercial release for over 10 years, Detours is licensed by over 100 ISVs and usedwithin nearly every product team at Microsoft.” Could potentially affect millions of users
 Also used in security products Hard to patch - In most cases fixing this issue requires recompilation ofeach product individually which makes patching cumbersomeAffected Products

UnSafe
Injection

Predictable
RWX(Universal)

Predictable
RX(Universal)

Predictable
RWX

Symantec

X

McAfeeX
X

Trend Micro

X (Initial Fix)
X

Kaspersky
AVG

RWX Hook
code stubs

90
X

90

X

21090

X

30
X

X

AVAST

X

Time To Fix (Days)

X

BitDefender
WebRoot

RWX HookedModulesX

30X29X

30Emsisoft

X

90

Citrix - Xen Desktop

X

WebSense

X

X

Vera

X

X
X(64-bit)

Invincea

22X

30?

XX?

X?

X

X

Fixed Independently

68Anti-Exploitation*
BeyondTrust

90180

X

Microsoft Office*TO TA L SX

7579.9* Patch wasn’t released yet

AFFECTED PRODUCTS

Products/Vendors

HighResearch Tools

RESEARCH TOOLS – AVULNERABILITY• Tool to detect predictable RWX code regions• Can be found at https://github.com/BreakingMalware/AVulnerabilityChecker• Compares memory maps of processes

Affected ProcessMemory Region
Affected Process IDsRESEARCH TOOLS – HOOKS SCAN
• Tool for scanning hooks and checking their code permissions• Compares code “On-Disk” with the code “In-Memory”• Does best-effort to track hooks code stubs

SUMMARY• Code hooking is an important capability for security/software vendors• Similar to other intrusive operations it has security implications• Almost all the vendors we tested were vulnerable to at least one issue• We worked closely with affected vendors to address all these issues –most are already patchedContact Us:Udi, udi@ensilo.com
Tomer, tomer@ensilo.com