Tip: How to Use Awk with Netstat

With malicious attacks coming from anywhere targeting our webservers, we, as system administrators, need to know whether the server is under a certain attack, like Denial of Service or most commonly known as DoS attacks.

DoS attack by definition is an attack towards a certain computer, like a webserver, to make it inaccessible to its intended users. If you have a webserver, a DoS attack could be a series of too many connection to your server, coming from a single IP. And since web service is commonly an open port, it usually is a visible port and susceptible to attacks, depending on your firewall rules.

So how do you know if you are under Dos attack on port 80 (http port)?

My first standard procedure with determining if there is one too many connections coming from a single host is by using netstat on the server. Of course using netstat alone could give a lot of raw results like this:

[root@rai01 ~]# netstat -an
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0* LISTEN
tcp 0 0* LISTEN
tcp 0 0* LISTEN
tcp 0 0* LISTEN
tcp 0 0* LISTEN
tcp 0 0* LISTEN
tcp 0 0* LISTEN
tcp 0 0* LISTEN
tcp 0 0* LISTEN
tcp 0 0* LISTEN
tcp 0 0* LISTEN
tcp 1 0 CLOSE_WAIT
tcp 0 0 :::80 :::* LISTEN
tcp 0 0 :::22 :::* LISTEN
tcp 0 0 :::443 :::* LISTEN

So, how do you figure out which is which? Simple. Just filter out the results with grep. Remember that we need to know how many hosts are connected on port 80 so getting this kind of result is still not very promising. So we do it like this:

netstat -an | grep :80
tcp 0 0* LISTEN
tcp 0 0 216.x.x.x:4566 TIME_WAIT
tcp 0 0 216.x.x.x:4564 TIME_WAIT
tcp 0 0 71.x.x.x:50466 TIME_WAIT
tcp 0 0 70.x.x.x:2854 ESTABLISHED
tcp 0 11088 70.x.x.x:2853 ESTABLISHED

Still too much information? Then go ahead and filter more with awk. awk is a Linux command that works like grep. With awk, we can get the list of each host’s ip and exclude other information that we do not need at the moment.

netstat -an | grep :80 | awk ‘{print $5}’*

The $5 represents the column number starting from left.

Now we are getting close to the results we need, aren’t we? At this point, we already have the connections at port 80 and kept only the connected host’s ips. What we need to do next is to count only the unique hosts and we do it like this:

netstat -an | grep :80 | awk ‘{print $5}’ | awk -F: ‘{print $1}’ | sort | uniq

sort is the Linux command which, as the name implies, sorts the results and uniq is the command that displays only the unique results. Pretty much simple, right?

So how do you know if your server under Dos attack on port 80? If you see way too many connections from single host or ip based on the filtered results, then you probably are indeed under DoS attack. What you must do is verify the where the ip address is located by Googling any ip locators that is free to use and block that ip by adding it to your firewall such as iptables.