Hooking
   HOME

TheInfoList



OR:

In
computer programming Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as ana ...
, the term hooking covers a range of techniques used to alter or augment the behaviour of an
operating system An operating system (OS) is system software that manages computer hardware, software resources, and provides common services for computer programs. Time-sharing operating systems schedule tasks for efficient use of the system and may also in ...
, of
applications Application may refer to: Mathematics and computing * Application software, computer software designed to help the user to perform specific tasks ** Application layer, an abstraction layer that specifies protocols and interface methods used in a c ...
, or of other software components by intercepting function calls or messages or
events Event may refer to: Gatherings of people * Ceremony, an event of ritual significance, performed on a special occasion * Convention (meeting), a gathering of individuals engaged in some common interest * Event management, the organization of ev ...
passed between
software components Component-based software engineering (CBSE), also called component-based development (CBD), is a branch of software engineering that emphasizes the separation of concerns with respect to the wide-ranging functionality available throughout a give ...
. Code that handles such intercepted function calls, events or messages is called a hook. Hooking is used for many purposes, including
debugging In computer programming and software development, debugging is the process of finding and resolving '' bugs'' (defects or problems that prevent correct operation) within computer programs, software, or systems. Debugging tactics can involve in ...
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 or other component. It is also widely used in benchmarking programs, for example
frame rate Frame rate (expressed in or FPS) is the frequency (rate) at which consecutive images (frames) are captured or displayed. The term applies equally to film and video cameras, computer graphics, and motion capture systems. Frame rate may also be ca ...
measuring in 3D games, where the output and input is done through hooking. Hooking can also be used by malicious code. For example,
rootkit A rootkit is a collection of computer software, typically malicious, designed to enable access to a computer or an area of its software that is not otherwise allowed (for example, to an unauthorized user) and often masks its existence or the exis ...
s, pieces of software that try to make themselves invisible by faking the output of
API An application programming interface (API) is a way for two or more computer programs to communicate with each other. It is a type of software interface, offering a service to other pieces of software. A document or standard that describes how ...
calls that would otherwise reveal their existence, often use hooking techniques.


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.


Source modification

Hooking can be achieved by modifying the source of the
executable In computing, executable code, an executable file, or an executable program, sometimes simply referred to as an executable or binary, causes a computer "to perform indicated tasks according to encoded instruction (computer science), instructi ...
or
library A library is a collection of materials, books or media that are accessible for use and not just for display purposes. A library provides physical (hard copies) or digital access (soft copies) materials, and may be a physical location or a vir ...
before an application is running, through techniques of
reverse engineering Reverse engineering (also known as backwards engineering or back engineering) is a process or method through which one attempts to understand through deductive reasoning how a previously made device, process, system, or piece of software accompli ...
. This is typically used to intercept function calls to either monitor or replace them entirely. For example, by using a
disassembler A disassembler is a computer program that translates machine language into assembly languageā€”the inverse operation to that of an assembler. A disassembler differs from a decompiler, which targets a high-level language rather than an assembly lan ...
, the
entry point In computer programming, an entry point is the place in a program where the execution of a program begins, and where the program has access to command line arguments. To start a program's execution, the loader or operating system passes contro ...
of a
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-oriente ...
within a
module Module, modular and modularity may refer to the concept of modularity. They may also refer to: Computing and engineering * Modular design, the engineering discipline of designing complex devices using separately designed sub-components * Mo ...
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 alternative method for achieving function hooking is by intercepting function calls through a
wrapper library Wrapper libraries (or library wrappers) consist of a thin layer of code (a "shim") which translates a library's existing interface into a compatible interface. This is done for several reasons: * To refine a poorly designed or complicated interfac ...
. A wrapper is a version of a library that an application loads, with all the same functionality 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 replace it with an entirely new set of logic.


Runtime modification

Operating systems and software may provide the means to easily insert event hooks at runtime. It is available provided that the
process A process is a series or set of activities that interact to produce a result; it may occur once-only or be recurrent or periodic. Things called a process include: Business and management *Business process, activities that produce a specific se ...
inserting the hook is granted enough permission to do so. Microsoft Windows for example, allows users to insert hooks that can be used to process or modify system
events Event may refer to: Gatherings of people * Ceremony, an event of ritual significance, performed on a special occasion * Convention (meeting), a gathering of individuals engaged in some common interest * Event management, the organization of ev ...
and application events for dialogs,
scrollbar A scrollbar is an interaction technique or widget in which continuous text, pictures, or any other content can be scrolled in a predetermined direction (up, down, left, or right) on a computer display, window, or viewport so that all of the con ...
s, and menus as well as other items. It also allows a hook to insert, remove, process or modify
keyboard Keyboard may refer to: Text input * Keyboard, part of a typewriter * Computer keyboard ** Keyboard layout, the software control of computer keyboards and their mapping ** Keyboard technology, computer keyboard hardware and firmware Music * Musi ...
and
mouse A mouse ( : mice) is a small rodent. Characteristically, mice are known to have a pointed snout, small rounded ears, a body-length scaly tail, and a high breeding rate. The best known mouse species is the common house mouse (''Mus musculus' ...
events. Linux provides another example where hooks can be used in a similar manner to process network events within the
kernel Kernel may refer to: Computing * Kernel (operating system), the central component of most operating systems * Kernel (image processing), a matrix used for image convolution * Compute kernel, in GPGPU programming * Kernel method, in machine learnin ...
through
NetFilter Netfilter is a framework provided by the Linux kernel that allows various networking-related operations to be implemented in the form of customized handlers. Netfilter offers various functions and operations for packet filtering, network addre ...
. When such functionality is not provided, a special form of hooking employs intercepting the library function 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 In computer science, a library is a collection of non-volatile resources used by computer programs, often for software development. These may include configuration data, documentation, help data, message templates, pre-written code and subro ...
concept, the
interrupt vector An interrupt vector table (IVT) is a data structure that associates a list of interrupt handlers with a list of interrupt requests in a table of interrupt vectors. Each entry of the interrupt vector table, called an interrupt vector, is the addre ...
table or the import descriptor table can be modified in memory. Essentially these tactics employ the same ideas as those of source modification, but instead altering instructions and structures located in the memory of a process once it is already running.


Sample code


Virtual method table hooking

Whenever a class defines/inherits a
virtual function In object-oriented programming, in languages such as C++, and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated. This concept is an important part o ...
(or method), compilers add a hidden member variable to the class which points to a
virtual method table In computer programming, a virtual method table (VMT), virtual function table, virtual call table, dispatch table, vtable, or vftable is a mechanism used in a programming language to support dynamic dispatch (or run-time method binding). When ...
(VMT or Vtable). Most compilers place the hidden VMT pointer at the first 4 bytes of every instance of the class. A VMT is basically an array of
pointers Pointer may refer to: Places * Pointer, Kentucky * Pointers, New Jersey * Pointers Airport, Wasco County, Oregon, United States * The Pointers, a pair of rocks off Antarctica People with the name * Pointer (surname), a surname (including a l ...
to all the virtual functions that instances of the class may call. At runtime these pointers are set to point to the right functions, because at
compile time In computer science, compile time (or compile-time) describes the time window during which a computer program is compiled. The term is used as an adjective to describe concepts related to the context of program compilation, as opposed to concept ...
, it is not yet known if the base function is to be called or if an overridden version of the function from a derived class is to be called (thereby allowing for polymorphism). Therefore, virtual functions can be hooked by replacing the pointers to them within any VMT that they appear. The code below shows an example of a typical VMT hook in Microsoft Windows, written in C++. #include #include "windows.h" using namespace std; class VirtualClass ; using VirtualFn1_t = void(__thiscall*)(void* thisptr); VirtualFn1_t orig_VirtualFn1; void __fastcall hkVirtualFn1(void* thisptr, int edx) //This is our hook function which we will cause the program to call instead of the original VirtualFn1 function after hooking is done. int main() It is important to note that all virtual functions must be class member functions, and all (non-static) class member functions are called with the __thiscall
calling convention In computer science, a calling convention is an implementation-level (low-level) scheme for how subroutines or functions receive parameters from their caller and how they return a result. When some code calls a function, design choices have been ...
(unless the member function takes a variable number of arguments, in which case it is called with __cdecl). The __thiscall calling convention passes a pointer to the calling class instance (commonly referred to as a "this" pointer) via the ECX register (on the x86 architecture). Therefore, in order for a hook function to properly intercept the "this" pointer that is passed and take it as an argument, it must look into the ECX register. In the above example, this is done by setting the hook function (hkVirtualFn1) to use the __fastcall calling convention, which causes the hook function to look into the ECX register for one of its arguments. Also note that, in the above example, the hook function (hkVirtualFn1) is not a member function itself so it cannot use the __thiscall calling convention. __fastcall has to be used instead because it is the only other calling convention that looks into the ECX register for an argument.


C# keyboard event hook

The following example will hook into keyboard events in Microsoft Windows using the Microsoft .NET Framework. using System.Runtime.InteropServices; namespace Hooks; public class KeyHook


API/function hooking/interception using JMP instruction aka splicing

The following source code is an example of an API/function hooking method which hooks by overwriting the first six bytes of a destination
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-oriente ...
with a JMP instruction to a new function. The code is compiled into a DLL file then loaded into the target process using any method of
DLL injection In computer programming, DLL injection is a technique used for running code within the address space of another process by forcing it to load a dynamic-link library. DLL injection is often used by external programs to influence the behavior of ano ...
. Using a backup of the original function one might then restore the first six bytes again so the call will not be interrupted. In this example the
win32 API The Windows API, informally WinAPI, is Microsoft's core set of application programming interfaces (APIs) available in the Microsoft Windows operating systems. The name Windows API collectively refers to several different platform implementations th ...
function MessageBoxW is hooked.For more information, see http://ntvalk.blogspot.nl/2013/11/hooking-explained-detouring-library.html /* This idea is based on chrom-lib approach, Distributed under GNU LGPL License. Source chrom-lib: https://github.com/linuxexp/chrom-lib Copyright (C) 2011 Raja Jamwal */ #include #define SIZE 6 typedef int (WINAPI *pMessageBoxW)(HWND, LPCWSTR, LPCWSTR, UINT); // Messagebox prototype int WINAPI MyMessageBoxW(HWND, LPCWSTR, LPCWSTR, UINT); // Our detour void BeginRedirect(LPVOID); pMessageBoxW pOrigMBAddress = NULL; // address of original BYTE oldBytes
IZE Oxford spelling (also ''Oxford English Dictionary'' spelling, Oxford style, or Oxford English spelling) is a spelling standard, named after its use by the University of Oxford, that prescribes the use of British spelling in combination with th ...
= ; // backup BYTE JMP
IZE Oxford spelling (also ''Oxford English Dictionary'' spelling, Oxford style, or Oxford English spelling) is a spelling standard, named after its use by the University of Oxford, that prescribes the use of British spelling in combination with th ...
= ; // 6 byte JMP instruction DWORD oldProtect, myProtect = PAGE_EXECUTE_READWRITE; INT APIENTRY DllMain(HMODULE hDLL, DWORD Reason, LPVOID Reserved) void BeginRedirect(LPVOID newFunction) int WINAPI MyMessageBoxW(HWND hWnd, LPCWSTR lpText, LPCWSTR lpCaption, UINT uiType)


Netfilter hook

This example shows how to use hooking to alter
network Network, networking and networked may refer to: Science and technology * Network theory, the study of graphs as a representation of relations between discrete objects * Network science, an academic field that studies complex networks Mathematics ...
traffic in the Linux kernel using
Netfilter Netfilter is a framework provided by the Linux kernel that allows various networking-related operations to be implemented in the form of customized handlers. Netfilter offers various functions and operations for packet filtering, network addre ...
. #include #include #include #include #include #include #include #include /* Port we want to drop packets on */ static const uint16_t port = 25; /* This is the hook function itself */ static unsigned int hook_func(unsigned int hooknum, struct sk_buff **pskb, const struct net_device *in, const struct net_device *out, int (*okfn)(struct sk_buff *)) /* Used to register our hook function */ static struct nf_hook_ops nfho = ; static __init int my_init(void) static __exit void my_exit(void) module_init(my_init); module_exit(my_exit);


Internal IAT hooking

The following code demonstrates how to hook functions that are imported from another module. This can be used to hook functions in a different process from the calling process. For this the code must be compiled into a DLL file then loaded into the target process using any method of
DLL injection In computer programming, DLL injection is a technique used for running code within the address space of another process by forcing it to load a dynamic-link library. DLL injection is often used by external programs to influence the behavior of ano ...
. The advantage of this method is that it is less detectable by
antivirus software Antivirus software (abbreviated to AV software), also known as anti-malware, is a computer program used to prevent, detect, and remove malware. Antivirus software was originally developed to detect and remove computer viruses, hence the nam ...
and/or
anti-cheat software Cheating in online games is the subversion of the rules or mechanics of online video games to gain an unfair advantage over other players, generally with the use of third-party software. What constitutes cheating is dependent on the game in ...
, one might make this into an external hook that doesn't make use of any malicious calls. The
Portable Executable The Portable Executable (PE) format is a file format for executables, object code, DLLs and others used in 32-bit and 64-bit versions of Windows operating systems. The PE format is a data structure that encapsulates the information necessary fo ...
header contains the Import Address Table (IAT), which can be manipulated as shown in the source below. The source below runs under Microsoft Windows. #include typedef int(__stdcall *pMessageBoxA) (HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType); //This is the 'type' of the MessageBoxA call. pMessageBoxA RealMessageBoxA; //This will store a pointer to the original function. void DetourIATptr(const char* function, void* newfunction, HMODULE module); int __stdcall NewMessageBoxA(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType) int main(int argc, CHAR *argv[]) void **IATfind(const char *function, HMODULE module) void DetourIATptr(const char *function, void *newfunction, HMODULE module)


See also

* Callback (computer science) *
Delegation (programming) In computing or computer programming, delegation refers generally to one entity passing something to another entity,Barry Wilkinson, ''Grid Computing: Techniques and Applications'' (2009), p. 164, . and narrowly to various specific forms of relat ...
*
Terminate and stay resident A terminate-and-stay-resident program (commonly TSR) is a computer program running under DOS that uses a system call to return control to DOS as though it has finished, but remains in computer memory so it can be reactivated later. This technique ...
*
User exit A user exit is a subroutine invoked by a software package for a predefined event in the execution of the package. In some cases the exit is specified by the installation when configuring the package while in other cases the users of the package can ...
* WinAPIOverride32


References

* * * 012-06-29: Link appears to be dead'' {{refend


External links


Windows


Information on Import Address Table function hooking.

Information from Microsoft on hooking

Information and various techniques regarding x86 hooking.

APISpy32
is an application used to hook win32 API.
Detours
is a general purpose function hooking library created by Microsoft Research which works in C / C++.
winspy
Three ways to inject code into another process.
HookTool SDK (ACF SDK)
Provides a comprehensive overview on API hooking and code injection. A commercial product available too.

is a commercial x86 and x64 API hooking and DLL injection library for C++ and Delphi.
EasyHook
is an open source hooking engine supporting x86 and x64 in Windows in both user and kernel land.
SpyStudio Application Trace
SpyStudio is an Application tracer which hook calls, displaying the results in a structured way.
rohitab.com API Monitor
is a freeware application that can hook and display 10,000+ Windows APIs and COM Interfaces in 32-bit and 64-bit applications and services.
Deviare API Hook
Deviare is a freeware inter-process hook framework that can be used to intercept other processes' API calls and show full-parameter information or create API monitors.
WinAPIOverride
WinAPIOverride is a freeware for non commercial use. It can hook win32 API, COM, OLE, ActiveX, .NET in 32-bit and 64-bit processes. It includes monitoring post analysis tools.
urmem
C++11 cross-platform library (x86) for working with memory (hooks, patches, pointer's wrapper, signature scanner etc.)


Linux



A student research project that utilizes hooking.

Functionality that allows a piece of software to observe and control the execution of another process.

Use of LD_PRELOAD to hook shared library calls.


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.)


OS X and iOS


Cydia Substrate
is a framework for jailbroken iOS devices allowing developers to hook into any other framework or application.
harpoon
is an OS X library for runtime function hooking.


In Depth API Hooking


x86 API Hooking Demystified
Article on various API Hooking methods, for the x86 architecture. Control flow DLL injection Articles with example code