emanote/content/Unix/SSH-Filter.md

43 lines
1.0 KiB
Markdown
Raw Permalink Normal View History

2022-08-24 11:55:32 +00:00
To filter incoming SSH-Connections by Country/Login do:
Create a filter-binary (i.e. `/usr/local/bin/sshfilter.sh`) with contents like:
```bash
#!/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](https://wiki.ubuntuusers.de/geoiplookup/)