Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run code every time a new socket is created on my Linux machine?

I need to call a function every time a new TCP socket is created at my Linux server. The schema code is:

do {
    new_socket = block_until_new_socket_created();
    do_something(new_socket);
} while (true);

The question is, is there any library/tool/function to be notified when a new tcp socket is created at the UNIX/Linux server where the code is being executed?

The programming code is C.

like image 850
tremendows Avatar asked Sep 06 '13 15:09

tremendows


1 Answers

Old question, but there is at least two ways to do this:

1) Use the audit subsystem

You can configure auditd and the Linux audit subsystem to log a message every time any syscall happens. It will include the timestamp and the calling process. Something that hooks 'connect()' and/or 'bind()' should get you what you need for sockets. This is what auditd was designed to do.

2) Use ip_conntrack (netfilter/ip_tables)

Use something like the libnetfilter-conntrack library (which uses the ip_conntrack kernel module) will get you notifications of all new sockets with filtering as desired. However, it will only tell you local and remote address/port and timestamp, not inode. Which means to correlate this back to a pid, you have to first read the notification from conntrack, and then parse the files in /proc/net/{tcp/udp/whatever} files to find the socket and the inode, and then parse all the /proc/$pid/fd/* files to find out which pid owns that inode. At each step, you have to hope the socket hasn't gone away by the time you read the files in that three-step process. Such a system is used by flowtop from the netsniff-ng utils package.

All systems require root, although once auditd is configured by root, the logs can be read by non-root if you want. I'd think you'd want to use auditd whenever possible. The ip_conntrack interface seems a bit nicer at first, but auditd gets you all the information you want, including pid tracking, for free.

like image 111
clemej Avatar answered Nov 11 '22 22:11

clemej