Skip to content

Instantly share code, notes, and snippets.

@fishi0x01
Last active March 21, 2020 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fishi0x01/68b24bc542f5cb09331e to your computer and use it in GitHub Desktop.
Save fishi0x01/68b24bc542f5cb09331e to your computer and use it in GitHub Desktop.
Examples on hooking the standard C socket library. Code for blog post https://fishi.devtail.io/weblog/2015/01/25/intercepting-hooking-function-calls-shared-c-libraries/
/*
* A simple client that opens a socket.
*/
#include <stdio.h>
#include <sys/socket.h>
int main(int argc, char *argv[])
{
int sockfd;
// Create socket and check for error
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("Error : Could not create socket\n");
return 1;
}
else
{
printf("Socket successfully created\n");
}
return 0;
}
/*
* A simple socket hook which calls the original socket library.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <sys/socket.h>
#include <dlfcn.h>
int (*o_socket)(int,int,int);
int socket(int domain, int type, int protocol)
{
// find the next occurrence of the socket() function
o_socket = dlsym(RTLD_NEXT, "socket");
if(o_socket == NULL)
{
printf("Could not find next socket() function occurrence");
return -1;
}
printf("socket() call intercepted\n");
// return the result of the call to the original C socket() function
return o_socket(domain,type,protocol);
}
/*
* A trivial socket hook.
*/
#include <stdio.h>
int socket(int domain, int type, int protocol)
{
printf("socket() call intercepted");
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment