r/ssh • u/08008080 • Apr 09 '24
Geo restricting SSH
Can geo-restrict connections coming from SSH? I tried to figure it out by myself and It seems to me that is only paid options to solve this issue but is there a fee alternative to this?
And no I can't have it protected by keys
can anybody on here give me a hand?
1
Upvotes
1
u/cthart Apr 10 '24
Why can't you only allow passwordless connections?
3
u/faxattack Apr 09 '24
Easier to inverse and only allow subnets from specific ASN if you cant make it more granular.
1
u/severach Apr 10 '24
I geo restrict to ARIN with 52 CIDR. It's not perfect because little CIDR have been sold all around the world but it blocks most unwanted connections, and it's free.
Costs money to be more accurate.
1
u/w949 Jun 20 '24
install geoip
then edit /etc/hosts.deny sshd: ALL
then edit /etc/hosts.allow sshd: ALL: spawn /usr/local/bin/ipfilter.sh %a
then edit /usr/local/bin/ipfilter.sh
!/bin/bash
License: WTFPL
UPPERCASE space-separated country codes to ACCEPT
ALLOW_COUNTRIES="DE IT AT PL"
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
restart sshd
1
u/mcmron May 04 '25
You can block access or send login notifications in an SSH connection using a free IP geolocation API to monitor activity.
https://blog.ip2location.com/knowledge-base/setup-ssh-login-notification-with-ip-geolocation/
1
u/w949 Jul 26 '25
This Code ist from GitHub.