04 - ELF Hooking¶

The objective of this tutorial is to hook a library function

Scripts and materials are available here: materials

By Romain Thomas - @rh0main

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);
exit(-1);
}

int a = atoi(argv);
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

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

dynamic_entry

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: lief.ELF.Binary, segment: LIEF::ELF::Segment, base: int = 0) -> LIEF::ELF::Segment

Add a segment in the binary

1. add(self: lief.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")