Search code examples
c++cunixelfabi

How to hook send() / recv() functions on Linux?


I'm trying to hook recv() and send() functions in C++ on Linux.

I know how to hook functions (github: zeek/subhook). But I would like some help to learn how to find recv() or send() functions' addresses (at runtime, or with a version independent solution).

I'm open to any kind of documentation or advice that could help me to understand mechanisms involved here.


[EDIT] A clarification: I don't wanna use LD_PRELOAD= because I inject my shared library with this tool : linux-inject.


Solution

  • If the target program was not designed for injection

    One venue is to inject via gdb. It's not trivial, though. But you've already got that covered.

    As for finding the addresses at runtime, you should check out how gdb does it. You might find some libraries that have encapsulated this exact behaviour.

    If you can design the target program for hooking

    There are simpler ways of achieving this, like the LD_PRELOAD trick and other shared library tricks, and probably countless others. But to get the addresses of recv and send, you could do something along the lines of

    #include <stdio.h>
    #include <sys/socket.h>
    #include <unistd.h>
    
    int main()
    {
      printf("pid %d\n", getpid());
      printf("Address of recv: %p\n", recv);
      printf("Address of send: %p\n", send);
    
      for (;;) {
        sleep(1);
      }
    }
    

    Running it on my system,

    $ ./a.out
    pid 21266
    Address of recv: 0x7fff86abedf3
    Address of send: 0x7fff86abee03
    

    Double-checking with gdb,

    $ gdb -p 21266
    (gdb) p (void*)recv
    $4 = (void *) 0x7fff86abedf3 <recv>