Last active
April 3, 2022 09:39
-
-
Save binhp/6b0795cb1c419cec8ba08be2f8668fbb to your computer and use it in GitHub Desktop.
Secure SSH Server with IP Country Restriction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# License: WTFPL | |
## install geoip first | |
# apt-get install geoip-bin geoip-database | |
## /etc/hosts.allow | |
# sshd: ALL: aclexec /opt/scripts/ip-filter.sh %a | |
## /etc/hosts.deny | |
## sshd: ALL | |
# UPPERCASE space-separated country codes to ACCEPT | |
ALLOW_COUNTRIES="VN" | |
LOGDENY_FACILITY="authpriv.notice" | |
if [ $# -ne 1 ]; then | |
echo "Usage: `basename $0` " 1>&2 | |
exit 0 # return true in case of config issue | |
fi | |
if [[ "`echo $1 | grep ':'`" != "" ]] ; then | |
COUNTRY=`/usr/bin/geoiplookup6 "$1" | awk -F ": " '{ print $2 }' | awk -F "," '{ print $1 }' | head -n 1` | |
else | |
COUNTRY=`/usr/bin/geoiplookup "$1" | awk -F ": " '{ print $2 }' | awk -F "," '{ print $1 }' | head -n 1` | |
fi | |
[[ $COUNTRY = "IP Address not found" || $ALLOW_COUNTRIES =~ $COUNTRY ]] && RESPONSE="ALLOW" || RESPONSE="DENY" | |
if [[ "$RESPONSE" == "ALLOW" ]] ; then | |
logger -p $LOGDENY_FACILITY "$RESPONSE sshd connection from $1 ($COUNTRY)" | |
exit 0 | |
else | |
logger -p $LOGDENY_FACILITY "$RESPONSE sshd connection from $1 ($COUNTRY)" | |
exit 1 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment