
There is a real security risk to leaving your shell connection ports exposed to the internet especially if you don’t ever intend on connecting from Zimbabwe as well as other random countries.
This can limit brute force attack exposure and also save valuable resources and bandwidth by rejecting a packets before a tcp handshake.
Install GeoIP
You will need to implement a database that can be queried locally that stores IP ranges to countries.
apt-get install geoip-database geoip-bin
Query GeoIP database
geoiplookup 8.8.8.8
The script
mkdir /scripts
vi /scripts/sshfilter.sh
Past the following in:
#!/bin/bash
ALLOW_COUNTRIES="AU"
if [ $# -ne 1 ];
then
echo "Usage: `basename $0` <ip>" 1>&2
exit 0
fi
COUNTRY=`/usr/bin/geoiplookup $1 | awk -F ": " '{ print $2 }' | awk -F "," '{ print $1 }' | head -n 1`
[[ $COUNTRY = "IP Address not found" || $ALLOW_COUNTRIES =~ $COUNTRY ]] &&; RESPONSE="ALLOW" || RESPONSE="DENY"
if [ $RESPONSE = "ALLOW" ]
then
exit 0
else
logger "$RESPONSE sshd connection from $1 ($COUNTRY)"
exit 1
fi
Enable script
chmod +x /scripts/sshfilter.sh
Lock down SSH
Setup a deny all for the ssh daemon
vi /etc/hosts.deny
Add the following into the deny file
sshd: ALL
Enable the script in the allow ssh file
vi /etc/hosts.allow
Add the following into the allow file
sshd: ALL: aclexec /scripts/sshfilter.sh &a
Testing
Test the script by inputting the script name and then an IP afterwards
/scripts/sshfilter.sh 8.8.8.8
Should output something like the following:
Aug 25 15:23:21 server root: DENY sshd connection from 8.8.8.8 (US)
Update GeoIP
There is only one constant with the world and that is change, IP addresses are no exception.
Create a new file called update_geo.sh in /scripts
vi /scripts/update_geo.sh
Add the following into the file
#!bin/bash
cd /tmp
wget -q https://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
if [ -f GeoIP.data.gz ]
then
gzip -d GeoIP.dat.gz
rm -f /usr/share/GeoIP/GeoIP.dat
mv -f GeoIP.dat /usr/share/GeoIP/GeoIP.dat
else
echo "Cannot download the GeoIP database"
fi
Change the script to execute
chmod +x /scripts/update_geo.sh
Edit the crontab
crontab -e
Paste the following at the bottom of the crontab
* * 20 * * /scripts/update_geo.sh