Monitor TCP Traffic on specific port

edit: I'm still getting upvotes for this years later. Please don't go for this answer, the answer using iptables here is far superior in my opinion.


tcpdump port 443 and '(tcp-syn|tcp-ack)!=0'

or only tcp-syn, or only tcp-ack (my guess would be that one), depending on what you need.


You can use the iptables support in the Linux kernel for this. The upside is that it doesn't require any extra software to be moderately useful. The downside is that it requires root privileges to set up (but given that you are talking about port 443, which is a privileged port, you probably need root privileges with most solutions).

Add an iptables rule with something like:

sudo iptables -I INPUT -p tcp --dport 443 --syn -j LOG --log-prefix "HTTPS SYN: "

(Adjust the -I INPUT part to suit your taste.)

When the rule is triggered, a syslog entry will be emitted by the kernel. For example, with an input rule, the log entry may look something like:

Dec 5 09:10:56 hostname kernel: [1023963.185332] HTTPS SYN: IN=ifX OUT= MAC=80:80:80:80:80:80:80:80:80:80:80:80:08:00 SRC=A.B.C.D DST=W.X.Y.Z LEN=52 TOS=0x00 PREC=0x20 TTL=119 ID=11901 DF PROTO=TCP SPT=37287 DPT=443 WINDOW=8192 RES=0x00 SYN URGP=0

You can then use any run-of-the-mill log monitoring tool to do something useful with this information. If your syslog implementation supports it, you can even direct these into a separate log file, effectively fulfilling your requirement to write the connection data to a file timestamped to the second with no additional software.

Note that the LOG target is a non-terminating target, which means that any rules following it will still be evaluated, and the packet will not be either rejected or accepted by the LOG rule itself. This makes the LOG target useful also for debugging firewall rules.

To avoid flooding your log, consider using the limit module in conjunction with this. See the iptables(8) man page for details.


Micro-Second Resolution

By default, the tcpdump utility will report time with micro-second resolution. For example:

$ sudo tcpdump -i any port 443

will show output similar to the following:

12:08:14.028945 IP localhost.33255 > localhost.https: Flags [S], seq 1828376761, win 43690, options [mss 65495,sackOK,TS val 108010971 ecr 0,nop,wscale 7], length 0
12:08:14.028959 IP localhost.https > localhost.33255: Flags [R.], seq 0, ack 1828376762, win 0, length 0

See tcpdump(8) for a full list of tcpdump options, and pcap-filter(7) for the complete syntax of the filters you can use.

Tags:

Linux

Bash