Bash – IPtables SSH root logins protection.

Please be aware. This script was created for excersice reasons only. Using this script in a production/home system can lead to problems if the attacker is smart enough. This is NOT a sophisticated tool to protect your system.

The script captures IPs from log files where a root SSH connection has been attempted. It then blacklists those IPs by creating a firewall for them. All the blacklisted IPs are inserted into a master file. The master file is being updated with new unique IPs each time the script is run. There are tools that already do this type of tasks in a much more elaborate manner….but hey…I like scripting 🙂

 

#!/bin/bash
#The script captures data from /var/log/secure.
#It creates a ban list of IPs where a root and only root SSH connection has been attempted

IPT=/sbin/iptables

#Flush all iptable rules.
$IPT -F

#This is the file that stores the IP addresses and then does a comparison of IPs with the master file
#Any duplicate IPs are not entered in the master file. Only new IPs
>ips_1

#Checks to see if the master IP file is empty. If it is, it populates it.
#The master IP file is empty when the script has been run for the first time.
#Or if somebody has tampered with it. An email needs to be sent if the file is empty.
#If the master file is not empty then the ips_1 file is compared with the master IP file
#and only new IPs are enntered in the master ip file.
if [ \! -s master_banned_ip_list ]
    then
            grep 'root' /var/log/secure | awk '{print $11}' | egrep ^[0-9] | sort -u >> master_banned_ip_list;

    else
            grep 'root' /var/log/secure | awk '{print $11}' | egrep ^[0-9] | sort -u >> ips_1;
            grep -v -x -f  master_banned_ip_list ips_1 >> master_banned_ip_list

fi

#UMBRELLA RULES
#ALWAYS PUT THESE RULES ON. THEY ARE A "DENY BY DEFAULT"
#HOWEVER, THE SECOND RULE WILL ALLOW OUTGOING TRAFFIC.
$IPT -P INPUT DROP
$IPT -P OUTPUT ACCEPT
$IPT -P FORWARD DROP

#For loop that will build the new IP table rules with all the IPs.
for list_of_ips in `cat master_banned_ip_list`;
do
$IPT -A INPUT -p tcp -s $list_of_ips --in-interface  eth0 -j DROP
done;

#SSH RELATED - From what IPs SSH is allowed.
#-From Home external IP
$IPT -A INPUT -p tcp -s xx.xx.xx.xx --in-interface eth0 --dport 22 -j ACCEPT
#-From Work external IP
$IPT -A INPUT -p tcp -s xx.xx.xx.xx --in-interface eth0 --dport 22 -j ACCEPT
#------------------------------------
#ALLOW ICPM RESPONSES
$IPT -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPT -P INPUT DROP
Share Button

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload the CAPTCHA.