Find and Block Abusive IP Addresses on Ubuntu Server

The Issue

Your server has an extremely high workload in comparison to the usual CPU load, it generally feels less- or even unresponsive and if you have any intrusion detection configured, then it is sending alerts of failed login attempts.

The Cause

Having your server constantly bombarded by SQL Injection Attacks or Randomized PHP Login attempts can easily fry your hardware, if you are not cautious enough and let the attacker do its’ thing a few thousand times per second – and for the record, most attackers do have the bandwidth to do so. At any rate, let’s assume you have some kind of an alert planned on your host, which informs you of the failed login attempts. What to do next?

The Solution

Given the fact that you know your usual workload and possible connection pool, the fastest way to respond to this attack (if it is not done automatically via Fail2ban, for instance) is to ban the IP address from which the attack is originating from.

First, let’s get a list from all the connected IP addresses along with the number of connections they have to your host. Issue the following command in your Terminal, logged in to your server:

netstat -anp | grep 'tcp\|udp' | sed -n -e '/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}/p' | awk '{print $5}' | sed 's/::ffff://' | cut -d: -f1 | sort | uniq -c | sort -n

This will produce the following list:

<number_of_connections> <ip_address>

Check for any suspicious addresses in the list – usually the culprit is hiding in one of the higher connection numbered addresses. After you have identified it (or at least have a decent idea which one could be it) it is time to ban it for good (for example: 1.2.3.4):

iptables -I INPUT -s 1.2.3.4 -j DROP

Monitor your load, preferably using the uptime command as it puts less strain on the CPU.

Source is reblogged from here.

About the author

Gábor Hargitai

View all posts