Log connections to program

Besides for using iptables to log incoming connections..

Is there a way to log established inbound connections to a service that you don't have the source to (suppose the service doesn't log stuff like this on its own)? What I'm wanting to do is gather some information based on who's connecting to be able to tell things like what times of the day the service is being used the most, where in the world the main user base is, etc.

I am aware I can use netstat and just hook it up to a cron script, but that might not be accurate, since the script could only run as frequently as a minute.

Here is what I am thinking right now:

  • Write a program that constantly polls netstat, looking for established connections that didn't appear in the previous poll. This idea seems like such a waste of cpu time though, since there may not be a new connection..
  • Write a wrapper program that accepts inbound connections on whatever port the service runs on, but then I wouldn't know how to pass that connection along to the real service.

Edit: Just occurred to me that this question might be better for stackoverflow, though I am not certain. Sorry if this is the wrong place.


Solution 1:

You can log new connections with iptables thus

iptables -I INPUT -m state --state NEW -j LOG --log-level 1 --log-prefix "New Connection "

This will add a message like this for a new ssh conenction

Oct 6 10:58:23 centos kernel: New Connection IN=eth0 OUT= MAC=00:0c:29:5b:a5:ea:00:0c:29:2d:94:a0:08:00 SRC=192.168.1.72 DST=192.168.254.187 LEN=52 TOS=0x00 PREC=0x00 TTL=126 ID=15498 DF PROTO=TCP SPT=59221 DPT=22 WINDOW=8192 RES=0x00 SYN URGP=0

or like this for a new http connection

Oct 6 11:03:56 centos kernel: New Connection IN=eth0 OUT= MAC=00:0c:29:5b:a5:ea:00:0c:29:d2:2c:38:08:00 SRC=192.168.254.188 DST=192.168.254.187 LEN=60 TOS=0x10 PREC=0x00 TTL=64 ID=10345 DF PROTO=TCP SPT=52488 DPT=80 WINDOW=14600 RES=0x00 SYN URGP=0

and so on for each new connection to your system. The will be logged to wherever your syslog is configured to send kern.warning messages.