Hooking
From Wikipedia, the free encyclopedia
In computer programming, the term hooking covers a range of techniques used to alter or augment the behavior of an operating system, of applications, or of other software components by intercepting function calls or messages or events passed between software components. Code that handles such intercepted function calls, events or messages is called a "hook".
Hooking is used for many purposes, including debugging and extending functionality. Examples might include intercepting keyboard or mouse event messages before they reach an application, or intercepting operating system calls in order to monitor behavior or modify the function of an application of other component.
Hooking can also be used by malicious code. For example, rootkits, pieces of software that try to make themselves invisible by faking the output of API calls that would otherwise reveal their existence, often use hooking techniques. A wallhack is another example of malicious behavior that can stem from hooking techniques. It is done by intercepting function calls and altering what is shown to the player.
Contents |
[edit] Methods
Typically hooks are inserted while software is already running, but hooking is a tactic that can also be employed prior to the application being started. Both these techniques are described in greater detail below.
[edit] Physical modification
By physically modifying an executable or library before an application is running through techniques of reverse engineering you can also achieve hooking. This is typically used to intercept function calls to either monitor or replace them entirely.
For example by using a disassembler the entry point of a function within a module can be found. It can then be altered to instead dynamically load some other library module and then have it execute desired methods within that loaded library. If applicable another related approach by which hooking can be achieved is by altering the import table of an executable. This table can be modified to load any additional library modules as well as changing what external code is invoked when a function is called by the application.
An alternate method for achieving function hooking is by intercepting function calls through a wrapper library. When creating a wrapper you make your own version of a library that an application loads, with all the same functionally of the original library that it will replace. That is all the functions that are accessible are essentially the same between the original and the replacement. This wrapper library can be designed to call any of the functionality from the original library, or have it replace it with an entirely new set of logic.
[edit] Runtime modification
Operating systems and software may provide the means to easily insert event hooks at runtime. It is available provided that the process inserting the hook is granted enough permission to do so. Windows for example, allows you to insert hooks that can be used to process or modify system events and application events for dialogs, scrollbars, and menus as well as other items. It also allows a hook to insert, remove, process or modify keyboard and mouse events. Linux, provides another example where hooks can be used in a similar manner to process network events within the kernel through NetFilter.
When such functionality is not provided, a special form of hooking employs intercepting the library functions calls made by a process. Function hooking is implemented by changing the very first few code instructions of the target function to jump to an injected code. Alternatively on systems using the shared library concept, the interrupt vector table or the import descriptor table can be modified in memory. Essentially these tactics employ the same ideas as those of physical modification, but instead altering instructions and structures located in the memory of a process once it is already running.
[edit] Sample code
[edit] C# keyboard event hook
The following example will hook into keyboard events in Microsoft Windows using the Microsoft .NET Framework.
using System; using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; namespace Hooks { public class KeyHook { #region Member variables protected static int hook; protected static LowLevelKeyboardDelegate delegate; protected static readonly object Lock = new object(); protected static bool isRegistered = false; #endregion #region Dll Imports [DllImport("user32")] private static extern Int32 SetWindowsHookEx(Int32 idHook, LowLevelKeyboardDelegate lpfn, Int32 hmod, Int32 dwThreadId); [DllImport("user32")] private static extern Int32 CallNextHookEx(Int32 hHook, Int32 nCode, Int32 wParam, KBDLLHOOKSTRUCT lParam); [DllImport("user32")] private static extern Int32 UnhookWindowsHookEx(Int32 hHook); #endregion #region Type Definitions & Constants protected delegate Int32 LowLevelKeyboardDelegate(Int32 nCode, Int32 wParam, ref KBDLLHOOKSTRUCT lParam); private const Int32 HC_ACTION = 0; private const Int32 WM_KEYDOWN = 0x0100; private const Int32 WM_KEYUP = 0x0101; private const Int32 WH_KEYBOARD_LL = 13; #endregion [StructLayout(LayoutKind.Sequential)] public struct KBDLLHOOKSTRUCT { public int vkCode; public int scanCode; public int flags; public int time; public int dwExtraInfo; } #endregion static private Int32 LowLevelKeyboardHandler(Int32 nCode, Int32 wParam, ref KBDLLHOOKSTRUCT lParam) { if (nCode == HC_ACTION) { if (wParam == WM_KEYDOWN) System.Console.Out.WriteLine("Key Down: " + lParam.vkCode); else if (wParam == WM_KEYUP) System.Console.Out.WriteLine("Key Up: " + lParam.vkCode); } return CallNextHookEx(hook, nCode, wParam, lParam); } public static bool RegisterHook() { lock(Lock) { if(isRegistered) return true; delegate = new LowLevelKeyboardDelegate(LowLevelKeyboardHandler); hook = SetWindowsHookEx(WH_KEYBOARD_LL, delegate, Marshal.GetHINSTANCE(System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0]).ToInt32(),0); if(hook != 0) return isRegistered = true; else { delegate = null; return false; } } } public static bool UnregisterHook() { lock(Lock) { return isRegistered = (UnhookWindowsHookEx(hook) != 0); } } } }
[edit] Hooking Direct3D
The following is an example of hooking Direct3D function calls on Windows. This utilizes a hooking free library called APIHijack. The source is compiled into a DLL. An additional application that will invoke InstallHook() is also required. For more information see [1]
#include <windows.h> #include <shlwapi.h> #include <ddraw.h> #include "testdll.h" #include "..\apihijack.h" char temp[256]; HINSTANCE hDLL; // type defs typedef HRESULT (WINAPI *DirectDrawCreateEx_Type)( GUID FAR *lpGUID, LPVOID *lplpDD, REFIID iid, IUnknown FAR *pUnkOuter ); // function prototypes HRESULT WINAPI MyDirectDrawCreateEx( GUID FAR * lpGuid, LPVOID *lplpDD, REFIID iid,IUnknown FAR *pUnkOuter ); // hook structure enum { D3DFN_DirectDrawCreateEx = 0 }; SDLLHook D3DHook = { "DDRAW.DLL", false, NULL, { { "DirectDrawCreateEx", MyDirectDrawCreateEx }, { NULL, NULL } } }; // Hook function. HRESULT WINAPI MyDirectDrawCreateEx(GUID FAR* lpGuid, LPVOID *lplpDD, REFIID iid,IUnknown FAR *pUnkOuter ) { DirectDrawCreateEx_Type OldFn = (DirectDrawCreateEx_Type)D3DHook.Functions[D3DFN_DirectDrawCreateEx].OrigFn; return OldFn( lpGuid, lplpDD, iid, pUnkOuter ); } // CBT Hook-style injection. BOOL APIENTRY DllMain( HINSTANCE hModule, DWORD fdwReason, LPVOID lpReserved ) { if ( fdwReason == DLL_PROCESS_ATTACH ) // When initializing.... { hDLL = hModule; // Only hook the APIs if this is the fsim proess. GetModuleFileName(GetModuleHandle(NULL), temp, sizeof(temp)); PathStripPath(temp); if(stricmp(temp, "fsim.exe" ) == 0) HookAPICalls( &D3DHook ); } return TRUE; } // This segment must be defined as SHARED in the .DEF #pragma data_seg (".HookSection") // Shared instance for all processes. HHOOK hHook = NULL; #pragma data_seg () TESTDLL_API LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam) { return CallNextHookEx( hHook, nCode, wParam, lParam); } TESTDLL_API void InstallHook() { hHook = SetWindowsHookEx(WH_CBT, HookProc, hDLL, 0); } TESTDLL_API void RemoveHook() { UnhookWindowsHookEx( hHook ); }
[edit] Netfilter hook
This example shows how to use hook to alter network traffic in the Linux kernel using Netfilter.
#define __KERNEL__ #define MODULE #include <linux/module.h> #include <linux/kernel.h> #include <linux/skbuff.h> #include <linux/ip.h> #include <linux/tcp.h> #include <linux/in.h> #include <linux/netfilter.h> #include <linux/netfilter_ipv4.h> // Used to register our hook function static struct nf_hook_ops nfho; // Port we want to drop packets on unsigned char *port = "\x00\x19"; // port 25 // This is the hook function itself unsigned int hook_func(unsigned int hooknum, struct sk_buff **skb, const struct net_device *in, const struct net_device *out, int (*okfn)(struct sk_buff *)) { struct sk_buff *sb = *skb; struct tcphdr *thead; /// Make sure sb is not null and that this is a TCP packet first if (sb && sb->nh.iph && sb->nh.iph->protocol == IPPROTO_TCP) { thead = (struct tcphdr *)(sb->data + (sb->nh.iph->ihl * 4)); // .. do stuff .. // Now check the destination port */ if ((thead->dest) == *(unsigned short *)port) return NF_DROP; } return NF_ACCEPT; } int init_module() { // Fill in our hook structure nfho.hook = hook_func; nfho.hooknum = NF_IP_PRE_ROUTING; nfho.pf = PF_INET; nfho.priority = NF_IP_PRI_FIRST; nf_register_hook(&nfho); return 0; } void cleanup_module() { nf_unregister_hook(&nfho); }
[edit] External links
[edit] Windows
- Information on Import Address Table function hooking.
- information from Microsoft on hooking
- APISpy32 is an application used to hook win32 API.
- Spy Studio API Spy lets you hook windows API and watch and modify the parameters of the calls.
- Detours is a general purpose function hooking library created by Microsoft Research which works in C / C++.
- Deviare API Hook Library is implemented as a group of COM objects and can be used in VB, .NET, Delphi, C / C++ and Python.
- [2] Three ways to inject code into another process.
- [3] Additional API Hooking techniques in Windows.
[edit] Linux
- [4] A student research project that utilizes hooking.
- [5] Functionality that allows a piece of software to observe and control the execution of another process.
[edit] Emacs
- Emacs Hooks Hooks are an important mechanism for customization of Emacs. A hook is a Lisp variable which holds a list of functions, to be called on some well-defined occasion. (This is called running the hook.)
[edit] See also
[edit] References
- Binh Nguyen (2004-08-16). "Hacking-Lexicon / Linux Dictionary V 0.16". http://www.tldp.org/LDP/Linux-Dictionary/html/. Retrieved on 2008-02-23. "Hook"
- Author: Holy Father (2002-06-10). "Hooking Windows API - Technics of hooking API functions on Windows 1.1 english". http://www.codebreakers-journal.com/downloads/cbj/2004/CBJ_1_2_2004_HolyFather_Hooking_Windows_API.pdf. Retrieved on 2008-02-21.

