04 - ELF HookingΒΆ

The objective of this tutorial is to hook a library function

Scripts and materials are available here: materials

In the previous tutorial we saw how to swap symbols names from a shared library, we will now see the mechanism to hook a function in a shared library.

The targeted library is the standard math library (libm.so) and we will insert a hook on the exp function so that \(exp(x) = x + 1\). The source code of the sample that uses this function is given in the following listing:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(int argc, char **argv) {
  if (argc != 2) {
    printf("Usage: %s <a> \n", argv[0]);

  int a = atoi(argv[1]);
  printf("exp(%d) = %f\n", a, exp(a));
  return 0;

The hooking function is as simple as:

double hook(double x) {
  return x + 1;

Compiled with gcc -Os -nostdlib -nodefaultlibs -fPIC -Wl,-shared hook.c -o hook.

To inject this hook into the library, we use the add() (segment) method

Binary.add(*args, **kwargs)

Overloaded function.

  1. add(self: _pylief.ELF.Binary, arg0: LIEF::ELF::DynamicEntry) -> LIEF::ELF::DynamicEntry


  1. add(self: _pylief.ELF.Binary, section: LIEF::ELF::Section, loaded: bool=True) -> LIEF::ELF::Section

Add the given Section to the binary.

If the section should not be loaded in memory, loaded parameter have to be set to False (default: True)

  1. add(self: _pylief.ELF.Binary, segment: LIEF::ELF::Segment, base: int=0) -> LIEF::ELF::Segment

Add a segment in the binary

  1. add(self: _pylief.ELF.Binary, note: LIEF::ELF::Note) -> LIEF::ELF::Note

Add a new Note in the binary

Once the stub is injected we just have to change the address of the exp symbol:

exp_symbol  = libm.get_symbol("exp")
hook_symbol = hook.get_symbol("hook")

exp_symbol.value = segment_added.virtual_address + hook_symbol.value

To test the patched library:

./do_math.bin 1
exp(1) = 2.718282
LD_LIBRARY_PATH=. ./do_math.bin 1
exp(1) = 2.000000