A Quick Guide Using ss and fail2ban

In today's interconnected world, server security is paramount. Hackers and malicious bots are constantly probing for vulnerabilities, making it crucial for system administrators to stay vigilant and proactive in safeguarding their systems. In this post, we'll explore a quick and effective method to enhance server security using the ss command and fail2ban.

Analyzing Established Connections

First, let's gain insight into established connections on our server's ports 80 and 443 using the ss command:

$ ss -tan state established | grep ":80\|:443" | awk '{print $4}' | cut -d':' -f1 | sort -n | uniq -c | sort -n

This command sequence provides a breakdown of established connections, sorted by IP address and counting the occurrences. By monitoring these connections, administrators can identify suspicious activities and potential threats in real-time.

Let me break down what each command does:

  1. ss -tan state established: This command lists all TCP connections in the "established" state.
  2. grep ":80\|:443": This filters the output to only include connections on ports 80 and 443.
  3. awk '{print $4}': This extracts the fourth column, which contains the local address and port.
  4. cut -d':' -f1: This uses ":" as the delimiter and extracts the IP address part.
  5. sort -n: This sorts the IP addresses numerically.
  6. uniq -c: This removes duplicate IP addresses and counts the occurrences.
  7. sort -n: This sorts the unique IP addresses by their occurrence count.

Instant IP Blocking with fail2ban

Next, let's leverage fail2ban, a powerful intrusion prevention tool, to automatically ban malicious IP addresses. Here's how we can ban an example IP address, 60.185.XXX.XXX, associated with suspicious activity:

$ fail2ban-client -vvv set apache-badbot banip 60.185.XXX.XXX 

By executing this command, fail2ban will blacklist the specified IP address for a predefined duration, effectively thwarting potential attacks from this source.

These measures are temporary, serving as precautionary measures against immediate threats, and should be supplemented with comprehensive security protocols for sustained protection