LIMIT SSH ACCESS BY COUNTRY






This is useful when being attack of constant login brute-force attempts mainly from countries like China and Russia.


Install GeoLite2 Country Database

    $ sudo apt-get install geoip-bin



Make sure that geoiplookup is working before implementing the script below.

    $ geoiplookup 8.8.8.8



Create bash script that will filter ssh access by country.

    $ sudo nano /usr/local/bin/sshfilter.sh


    #!/bin/bash

    # UPPERCASE space-separated country codes to ACCEPT
    ALLOW_COUNTRIES="PH"

    if [ $# -ne 1 ]; then
      echo "Usage:  `basename $0` <ip>" 1>&2
      exit 0 # return true in case of config issue
    fi

    COUNTRY=`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



Make the script executable:

    $ sudo chmod +x /usr/local/bin/sshfilter.sh


Now apply SSH restrictions using TCP wrappers.

    $ sudo nano /etc/hosts.allow

        sshd: ALL: aclexec /usr/local/bin/sshfilter.sh %a


    $ sudo nano /etc/hosts.deny

        sshd: ALL

Restart ssh service to take effect

     $ sudo service ssh restart 

Check log to see countries being blocked

    $ sudo tail -f /var/log/syslog




Comments