2019-06-26

Allow SSH access based on Country using GeoIP

  1. Install packages
    $ sudo apt install geoip-bin geoip-database
    
  2. Create script
    $ sudo vi /usr/local/bin/sshfilter.sh
    
    
    #!/bin/bash
    
    ALLOWED_COUNTRIES="KR US GB NZ"
    ALLOWED_IP="192.168 127.0.0"
    
    [[ "`echo $1 | grep ':'`" != "" ]] && SUFFIX="6"
    if [[ $ALLOWED_IP =~ ${1:0:7} ]]; then
     logger -p authpriv.notice "SSH ALLOWED $1 LOCALDOMAIN"
     exit 0
    fi
    
    GEORESULT=`/usr/bin/geoiplookup${SUFFIX} "$1"`
    COUNTRY=`echo $GEORESULT | cut -d : -f 2 | xargs | head -1`
    COUNTRYCODE=`echo $COUNTRY | cut -d , -f 1 | xargs`
    [[ $ALLOWED_COUNTRIES =~ $COUNTRYCODE ]] && RESPONSE="ALLOWED" || RESPONSE="DENIED"
    logger -p authpriv.notice "SSH $RESPONSE $1 $COUNTRY"
    [[ $RESPONSE == "ALLOWED" ]] && exit 0 || exit 1
    
  3. edit /etc/hosts.allow and /etc/hosts.deny
    # /etc/hosts.allow
    sshd: ALL: /usr/local/bin/sshfilter.sh %a
    
    # /etc/hosts.deny
    sshd: ALL
    

No comments:

Post a Comment