How to use Kernel Hooks?

Author: Richard J Moore, richardj_moore@uk.ibm.com, 
	Vamsi Krishna S., vamsi_krishna@in.ibm.com,
	Prasanna S Panchamukhi prasanna@in.ibm.com
	Linux Technology Centre, IBM Corp.

(C) Copyright 2000 IBM Corporation
(C) Copyright 2000 IBM UK Ltd


Introduction:
------------

The Kernel Hooks Interface is a generalised facility for placing hooks in 
arbitrary kernel locations. A hook is a location in the kernel
that calls out of the kernel to a kernel module routine - a hook exit routine.
It enables many kernel enhancements, which are otherwise self-contained, to
become loadable kernel modules and retain a substantial degree of independence
from the kernel source. This affords advantages for maintenance and
co-existence with other kernel enhancements. 

Hooks are implemented as fast and slim-line insertions to kernel space code.
When not active that have practically no overhead to the kernel. They are in
essence a conditional jmp to the exit dispatching code. 

There are two hook optimizations employed in gkhi, one of which is optional - the
exclusive hook; the other - the arch-hook - is dependent on the IA32 architecture
and always used in that environment.

The exclusive hook eliminates some of the generalised processing associated with
dispatching multiple exits. This can be used where it is known that only one 
exit would ever register to use a hook. Exclusive hooks are coded as 
EXCLUSIVE_HOOK, EXCLUSIVE_HOOK_RET etc. You have to use the macro
DECLARE_EXCLUSIVE_HOOK to declare the exclusive hook.

The arch-hook optimization uses architecturally dependent features. We have 
provided an implementation for IA32, though could be ported to other 
architectures without difficulty. The code for the IA32 implementation may 
be found in include/asm-i386/hook.h. This optimization is always used under IA32. 
It is implemented by:
 
  1. moving the hook exit dispatching code to a separate section to minimise the
     icache footprint of the hook code. (This should be applicable
     to all architectures.)
  2. changing the test for the conditional jmp to be dependent on a register variable
     which set by moving a literal constant into the register.
  3. modifying the literal value in the MOV instruction to activate and deactivate the
     hook.
 
These actions both minimise the cache hit and the number of instructions required to
test for an inactive hook.

There is another type of hooks: generic hooks. These are slower than the
arch-optimized hooks, but they generate no symbols at hook locations and
could be used to place hooks even in inline functions. Use the macros
DECLARE_GENERIC_HOOK and GENERIC_HOOK etc. to define generic hooks.

The hook interface allows multiple kernel modules to register their exits for
a given hook, in order to receive control at that given hook location. Multiple
hooks may be defined within the kernel and a single kernel module may register
exits to use multiple hooks.

When hook exits register they may specify co-existence criteria, that is
whether they can co-exist with other exist for the same hook and their
dispatching priority.

Hooks may be placed in kernel modules as well as the kernel itself.

A hook exit receives control as if called from the code in which the hook is
placed. Parameters may be passed to a hook exit and may be modified by an
exit (subject to being declared for that purpose). The exit may return a
non-zero result to stop other exits from being dispatched.

There are two type of hook:

	normal.
	conditional return.

With normal hooks, control returns to the hooked code after any exits are
dispatched.

With conditional return hooks, an exit may optionally specify that the routine
in which the hook is coded must return when the exit returns.

Exits are made callable in a two-stage process:

1) Registration - this is used to make the exit known to the hook interface
and to perform some validation. 

2) Arming - this is used to make a set of exits callable. The arming operation
is atomic as far as kernel processing is concerned.

These operations may be reversed using disarming and de-registration functions.

Hook interface is implemented in kernel/hook.c which can be compiled into the
kernel or as a module based on the kernel compilation option specified in
the "Kernel Hacking" section of the build configuration.

Hooks are defined by coding a DECLARE_HOOK macro to define a hook-head 
structure. Modules defining hooks may load before or after hook.o when it is 
compiled as a module, however they have to identify to the hook interface module 
the existence of a hook before an exit can be register and arm itself.

Hooks are identified by name, which should avoid problems of uniqueness. The
name specified is used to generate labels for the hook-head structure and the
hook location.


Installation:
-------------

Apply this patch to the kernel source and say 'Y' or 'M' to "Kernel Hooks 
Interface" in the "Kernel Hacking" section of the build configuration. Build 
the kernel and boot with it. If you build the hook interface as a module,
build and install the module.

-------------------------------------------------------------------------------
If you want to see a working example then compile khook.c and kexit.c using 
the following command:

echo "obj-m := khook.o kexit.o" > Makefile   
make -C /usr/src/linux/ SUBDIRS=$PWD modules

insmod khook.ko
insmod kexit.ko

khook.c shows how hooks are coded.
kexit.c shows how hook exits register and arm themselves.

The procedure for defining and using hooks involves the following steps:
	- add hooks to the kernel/kernel module source
	- register hook exits
	- arm hook exits
and when we are done using the hooks, undo the above:
	- disarm hook exits
	- deregister hook exits

-------------------------------------------------------------------------------

Adding Hooks to the Kernel
--------------------------

Let's say we want to place a hook named hook_trap1_entry in the beginning of the
trap1 handler then edit arch/i386/traps.c, locate routine do_debug. This is the
trap1 exception handler. The code begins as follows:

asmlinkage void do_debug(struct pt_regs * regs, long error_code)
{
	unsigned int condition;
	struct task_struct *tsk = current;

	if (regs->eflags & VM_MASK)
		goto debug_vm86;

	__asm__ __volatile__("movl %%db6,%0" : "=r" (condition));

Suppose we want a hook before the if statement. We add to traps.c:

#include <linux/hook.h>
#define HOOK_TRAP1_ENTRY hook_trap1_entry /* just a convenient define */
DECLARE_HOOK(HOOK_TRAP1_ENTRY);

then in do_debug we insert the hook definition:
asmlinkage void do_debug(struct pt_regs * regs, long error_code)
{
	unsigned int condition;
	struct task_struct *tsk = current;

	HOOK(HOOK_TRAP1_ENTRY);

	if (regs->eflags & VM_MASK)
		goto debug_vm86;

	__asm__ __volatile__("movl %%db6,%0" : "=r" (condition));

Now recompile the kernel.

For example to pass "condition" from do_debug to a hook exit:

    HOOK(HOOK_TRAP1_ENTRY, condition);

If you want to code a conditional-return hook the use for exmaple:

    HOOK_RET(HOOK_TRAP1_ENTRY, condition);

The kernel now has a dormant hook at the beginning of the trap1 exception
handler.

Adding Hooks to a Kernel Module
-------------------------------
Adding hooks to a kernel module is very similar to adding hooks to kernel.
In the module that is to have a hook defined code the DECLARE_HOOK macro 
before the first routine is defined - in other words where external static 
variables would be defined. For example suppose we wish to define my_hook,
then code:

#include <linux/hook.h>
DECLARE_HOOK(my_hook);

Next you'll need to define the hook by coding a HOOK macro in the code path 
where the hook is to be placed. In this example:

	HOOK(my_hook);

would be coded. This defines a public symbol for the hook location using the
name my_hook.

Using Hooks - registering and arming hook exits:
------------------------------------------------

To use this hook from your kernel module you need to perform 3 actions:

1) If hook interface hook.o is built as a module, insert it using:
	insmod hook.o
you might need the -f switch if you've changed kernel  versions after
compiling hook.o

2) You need to register the entry point (the hook exit) in your kernel module
that will receive control from hook.

You do this by calling hook_exit_register passing a pointer to hook structure 
(in this example hook_trap1_entry) and a pointer to a hook record structure 
(defined in hook.h as struct hook_rec). You will need to include linux/hook.h
into your module's source. Refer to this file for the definition of struct 
hook_rec, struct hook  and the relavent flags.

Allocate an instance of this structure for each hook exit you wish to
register. The hook.o interface will use these structures for as long as your
exits remain registered so allocate them from persistent memory e.g. the
kernel heap or global memory in you module. Don't allocate them as local
variables!

You set up your hook record as follows:

1) initialise the entire structure to NULLs.

2) set hook_exit to the address of your hook routine.

3) set the pointer hook_exit_name to the name of exit routine.

4) optionally set hook_flags to one of the following:


#define HOOK_PRIORITY_FIRST	0x00000004
#define HOOK_PRIORITY_LAST	0x00000008
#define HOOK_QUEUE_LIFO		0x00000010

HOOK_PRIORITY_FIRST inserts your exit at the head of the queue of exits to be 
dispatched for the particular hook. If another exit has already registered with
HOOK_PRIORITY_FIRST, then your registration fails.

HOOK_PRIORITY_LAST inserts your exit at the tail of the dispatching
queue. If another exit has already registered with this priority, then your 
registration fails.

Set HOOK_QUEUE_LIFO if you want to be inserted at the head of those exits that
can happily co-exist, but after a HOOK_PRIORITY_FIRST exit if one exists. 

If you leave hook_flag to NULL you'll be inserted at the tail, but above a 
HOOK_PRIORITY_LAST exit if it exists.

You now call hook_exit_register. If you get a NO_ERROR result then your exit has
been successfully registered. Note: registration does not cause your exit to be
called - that only happens after arming you exit. The reason for making this
distinction is to allow a group of exits to be simultaneously armed, once
successfully registered.

On successful registration you hook record will have hook_index indicating the
current position of this exit in the list of all exits registered for this 
hook, i.e., its dispatching priority (1 being first). Note that it will be 
updated as more exits register or deregister.

To get a group of exits callable from the hook you need to arm them. 
Arming is done by calling hook_exit_arm.

Once this is done your exits will be called whenever the kernel executes a
HOOK statement - unless a higher priority exit set a non-zero return value.

Hook Exit Parameters and Return Values.
--------------------------------------
A hook exit receives a variable length parameter list defined as follows:

For normal (unconditional return) hooks:

parm 0: pointer to the hook structure. This is useful if you have the
	same exit routine registered for multiple hooks, in which case this
	can be used to determine which hook has caused the exit routine to be
	called. 
parm 1 to (n+1): parameters coded on the HOOK macros.

For conditional-return hooks:

parm 0: pointer to the hook structure. This is useful if you have the
	same exit routine registered for multiple hooks, in which case this
	can be used to determine which hook has caused the exit routine to be
	called. 
parm 1: pointer to the return code (int *) to be set if a forced return of the
	hooked routine is requested by the exit routine. 
parm 2 to (n+2): parameters coded on the HOOK macros.

If the exit function's prototype does not match the expected prototype, then
the kernel could oops.

A hook exit may itself return with the following return values:

HOOK_CONTINUE - allows dispatching of other exits.
HOOK_TERMINATE - stops further exit dispatching and returns to the hooked code.
HOOK_RETURN - stops further exit dispatching and for conditional return hooks
forces the hooked routine to return using parm2 as a return value.

It is possible to write a hook exit function that takes variable number of
arguments, see kexit.c for an example.

Deregistering and disarming exits
---------------------------------

Exits may be disarmed and re-armed as often as like. Disarming may be done two
ways:

1) by calling hook_exit_disarm and passing a pointer to a hook record structure. 

2) by turning off HOOK_ARMED in hook_flags (&=~HOOK_ARMED) from the hook exit.

Exits may be de-registered by calling hook_exit_deregister and passing a 
pointer to a hook record structure. De-registration will force disarming.

WARNING!!! A kernel module must deregister its exits from its module_cleanup
routine if that have not already been deregistered. 

/proc interface
---------------
When Generalized Kernel Hooks is initialized, a /proc/hooks directory is 
created. Whenever a hook exit is registered for new hook, a /proc/hooks/<hook_id> 
subdirectory is created. Whenever a new hook exit is registered, a 
/proc/hooks/<hook_id>/<hook_exit_name> file is created. This file is writable 
if hook_exit_register is called with the proc_writable set to 1, otherwise, 
it is read-only. The file name is taken from hook_exit_name if set in the 
hook_rec_t structure. If not set, the file name is the exit's memory location. 
This file contains a boolean value of '1' or '0' to indicate whether the exit 
is armed or not. It may be written to independently of GKHI to arm or disarm 
a hook exit, provided that proc_writable flag is set on registration.

Reporting Problems and Discussing GKHI
--------------------------------------
email: dprobes@oss.software.ibm.com
vist: http://oss.software.ibm.com/developerworks/linux

For further information read the USENIX 2000 Annual Linux Showcase paper, and
the UKUUG Linux2001 Generalised Kernel Hooks paper which may be found at
http://oss.software.ibm.com/developerworks/linux

License
-------
Copyright (C) 2001 IBM Corporation

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA.

Change History
--------------
0.6	8th November 2000	First public drop
1.0	14th February 2001	SMP Enablement. Slim-line hooks implemented
				Thanks to Andrea Arcangeli for suggestions for
				improvement.
1.1	12th April 2001		Hooks initialised dynamically.
				Named hooks supported.
				Conditonal return hooks supported.
				Support for hooks in kernel modules added.
1.2 	3rd July 2001		Bug fixes.
				Rewrite to confirm to kernel coding style.
				Make it part of the kernel build process.
				Seperate out arch-dependent and indepedent
				parts. Arch-independent hooks and convenient
				provision to allow arch-specific optimized
				implementation of hooks. Updated documentation
				and simplify the sample modules.
1.3	20th Sept. 2001		/proc interface
				exclusive hooks
1.4	4th Oct. 2001		HOOK macros now take variable number of args
				Bug fix in is_asm_hook()
