Skip to main content

Log traffic by user with iptables

This is a little post explaining how to log the uid and guid of the user who is making a connection in a server:

iptables -N log_traffic
iptables -I OUTPUT 1 -p tcp -m multiport --dports 80,443 -m state --state NEW -j log_traffic
iptables -A log_traffic -j LOG --log-uid --log-prefix  "iptables: "

Explanation:

  1.  Create a new iptables chain log_traffic
  2.  Redirect all traffic from OUTPUT to log_traffic chain if the connection destination port is http or https.
  3.  Log all traffic in log_traffic chain including the user uid/gid.

with rsyslog identify the iptables traffic and put it in a separate log file. Edit /etc/rsyslog.conf and add the following line:

:msg, contains, "iptables: "  -/var/log/iptables.log

You will see traces like this with the uid and gid of the user making the connection:

Oct 22 14:44:54 host4sx56 kernel: [6828668.226415] iptables: IN= OUT=eth355 SRC=192.168.1.2 DST=172.17.16.52 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=11754 DF PROTO=TCP SPT=35734 DPT=80 WINDOW=14600 RES=0x00 SYN URGP=0 UID=3106 GID=3106

How to clear iptables rules

I am using the following script to clear all iptables rules. I use the script when I am debugging my iptables rules.

#!/bin/bash


/sbin/iptables -P INPUT   ACCEPT
/sbin/iptables -P OUTPUT  ACCEPT
/sbin/iptables -P FORWARD ACCEPT
/sbin/iptables -F
/sbin/iptables -X

for table in filter nat mangle; do
    /sbin/iptables -t $table -F
    /sbin/iptables -t $table -X
    /sbin/iptables -t $table -Z
done