==HERE IS THE SCRIPT==
#!/bin/bash
# Purpose: block all foreign IPs come in using ssh
# Modified from the script from http://www.cyberciti.biz/faq/?p=3402 (Author: nixCraft <www.cyberciti.biz> under GPL v.2.0+)
# -------------------------------------------------------------------------------
ISO="tw" #you can allow more regions by editing the list
### Set PATH ###
IPT=/sbin/iptables
WGET=/usr/bin/wget
EGREP=/bin/egrep
### No editing below ###
WHITELIST="countryaccept"
ZONEROOT="/root/iptables"
DLROOT="http://www.ipdeny.com/ipblocks/data/countries"
cleanOldRules(){
$IPT -F
$IPT -X
$IPT -t nat -F
$IPT -t nat -X
$IPT -t mangle -F
$IPT -t mangle -X
$IPT -P INPUT ACCEPT
$IPT -P OUTPUT ACCEPT
$IPT -P FORWARD ACCEPT
}
# create a dir
[ ! -d $ZONEROOT ] && /bin/mkdir -p $ZONEROOT
# clean old rules
cleanOldRules
# create a new iptables list
$IPT -N $WHITELIST
for c in $ISO
do
# local zone file
tDB=$ZONEROOT/$c.zone
# get fresh zone file
$WGET -O $tDB $DLROOT/$c.zone
# country specific log message
SPAMDROPMSG="$c Country Accept"
# allow ssh entry from Taiwanese IPs
ALLOWIPS=$(egrep -v "^#|^$" $tDB)
for ip in $ALLOWIPS
do
$IPT -A $WHITELIST -s $ip -j ACCEPT
done
# deny ssh entry from foreign IPs
$IPT -A INPUT -p tcp --dport ssh -j DROP
# accept www entry
$IPT -A INPUT -p tcp --dport 80 -j ACCEPT
done
$IPT -I INPUT 1 -j $WHITELIST
$IPT -I OUTPUT 1 -j $WHITELIST
$IPT -I FORWARD 1 -j $WHITELIST
#save the rules
iptables-save > /etc/iptables.rules
# call your other iptable script
# /path/to/other/iptables.sh
exit 0
==END==
Run the script in your linux terminal with sh command or sudo sh for execute as administrator. That is everything and here are only three things beginners need to keep in mind:
- you need to modify the countries that you allow IPs coming from. To know the country codes, you can check the website to find the two-character abbreviation of each country.
- the rules are to be reset after your machine reboot. You may need to make your machine restore the rules automatically or manually, and this is why I have a command to save the rules.
- the above code only block IPs that trying to connect with you through SSH. They are still allowed to find you under other internet protocols, like www (port 80).
If you are a scientist, especially if you are not a informacian but just a biologist like me, you probably want to know how the script work.
The script aims on editing the rules in iptables, which is popular in controlling connection from any IP. Briefly, first of all, the script clears the previous rules. Subsequently, it downloads IP list that contains IPs from the country you allow. Then it set the rules and finally save them for backup. The rules are simple and worth your time:
- IPs from countries that I allowed can connect with my machine through SSH
- IPs from other countries want to connect with my machine through SSH should be denied
- IPs from other countries want to connect with my machine through www is allowed