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
    

SSH lockout 60min after 5 brute force attempts in 10min

  1. install fail2ban
    $ sudo apt update
    $ sudo apt install fail2ban
    
  2. edit configuration
    $ sudo vi /etc/fail2ban/jail.conf
    
    [sshd]
    enabled  = true
    port     = ssh
    maxretry = 5    # 5 attempts not permitted
    findtime = 600  # within 10 minutes
    bantime  = 3600 # ban 1 hour
    logpath  = %(sshd_log)s
    backend  = %(sshd_backend)s
    
  3. unban an ip address
    $ sudo fail2ban-client set sshd unbanip IP_ADDRESS
    

PIP upgrade all, python package

$ for package in `pip list --outdated | cut -d ' ' -f 1`
> do
> pip install --upgrade $package
> done