emanote/content/Unix/SSH-Filter.md

1.0 KiB

To filter incoming SSH-Connections by Country/Login do:

Create a filter-binary (i.e. /usr/local/bin/sshfilter.sh) with contents like:

#!/bin/bash

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

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

COUNTRY=`/usr/bin/geoiplookup $1 | awk -F ": " '{ print $2 }' | awk -F "," '{ print $1 }' | head -n 1`

if [[ $COUNTRY == "IP Address not found" || $ALLOW_COUNTRIES =~ $COUNTRY ]]; then
    RESPONSE="ALLOW"
else
    RESPONSE="DENY"
fi

#root-user is denied directly - no matter from where
#can be used to also auto-ban ip in $1
if [[ $2 == "root" ]]; then
    RESPONSE="DENY"
fi

#allow few users from everywhere
if [[ $2 == "juser" ]]; then
    RESPONSE="ALLOW"
fi

if [[ $RESPONSE == "ALLOW" ]]; then
  exit 0
else
  logger "$RESPONSE sshd connection for $2 from $1 ($COUNTRY)"
  exit 1
fi

Installation of geoiplookup from ubuntuwiki