zack
zack

Reputation: 335

How to passively monitor if a new TCP connection is being made in Linux?

The easiest way is probably to write a loop to monitor /proc/net/tcp or /proc/net/tcp6. However, it is too inefficient since I need to be notified almost immediately. The closest thing I looked at is inotify which can provide callbacks on IO events on any files. The problem is that procfs is not regular file systems and inotify does not appear to support it (at least not for /proc/net/tcp and /proc/net/tcp6).

Further, I do not want the program to have root privilege in order to implement this.

EDIT: I removed the requirement of userspace connection. Also, I'm hoping that there's a built-in kernel support such as inotify that can achieve this. It may even be too intrusive in my case to manipulate the iptables.

Anyone has any idea? Thanks!!

Upvotes: 3

Views: 1828

Answers (3)

MarkR
MarkR

Reputation: 63538

It's certainly possible to monitor outbound traffic using raw sockets. See man page for packet (7) to see how to do that. However, this may not be what you want.

If connection-tracking is enabled, it may be possible to get notifications of new connections from the kernel using netlink. The API for doing these things is awful, so consider looking at the source of a program which does it already. I think the "conntrack" binary may be supplied with some distributions (I'm not sure what it's part of).

Upvotes: 1

Chris Stratton
Chris Stratton

Reputation: 40337

Best thing I can think of is trying to run an on-board proxy and persuade other apps to connect through that. Some have tried to do this by altering the APN settings.

But this is ugly, may not work on all versions, and can probably be circumvented.

Unfortunately, Android just isn't designed to allow end users to install optional improvements to the behavior of the system itself, short of cracking the whole thing open (ie, rooting).

Upvotes: 1

larsks
larsks

Reputation: 311288

You could add a logging rule to your local iptables configuration that would log a message whenever a new connection is initiated, and then make the log file readable by a non-root user. This would get you (a) immediate notification of events (you could use inotify to detect writes to the file) and (b) the detecting process itself does not need root privileges.

Upvotes: 2

Related Questions