Skip to content

Instantly share code, notes, and snippets.

@HoracioDos
Forked from jokey2k/sshfilter.sh
Last active August 24, 2018 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HoracioDos/d8f65cc9061d62754b896874deb5f205 to your computer and use it in GitHub Desktop.
Save HoracioDos/d8f65cc9061d62754b896874deb5f205 to your computer and use it in GitHub Desktop.
Modified version of sshfilter.sh to allow for ipv6 and local IP filtering
#!/bin/bash
# based on script from http://www.axllent.org/docs/view/ssh-geoip
# based on script from https://gist.github.com/ManfMert/b34f098ad6e5094225ff9366ae4e9d7d
# License: WTFPL
# location /usr/local/bin
function private_ip()
{
local ip=$1
local stat=1
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS='.'
ip=($ip)
IFS=$OIFS
# ip address in decimal
dec=$[((((( ${ip[0]} * 256 ) + ${ip[1]} ) * 256 ) + ${ip[2]} ) * 256 ) + ${ip[3]}]
#echo "ip dec: "$dec
# Soure: https://en.wikipedia.org/wiki/Reserved_IP_addresses
scope=""
# 192.168.0.0 to 192.168.255.255
if [[ $dec -ge 0xC0A80000 && $dec -le 0xC0A8FFFF ]]; then
scope="Private network"
# 127.0.0.0 to 127.255.255.255
elif [[ $dec -ge 0x7F000000 && $dec -le 0x7FFFFFFF ]]; then
scope="Host"
fi
fi
echo $scope
}
# UPPERCASE space-separated country codes to ACCEPT
ALLOW_COUNTRIES="AR"
LOGDENY_FACILITY="authpriv.notice"
if [ $# -ne 1 ]; then
echo "Usage: `basename $0` <ip>" 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"
RESPONSE="DENY"
if [[ $ALLOW_COUNTRIES =~ $COUNTRY ]]; then
RESPONSE="ALLOW"
elif [[ $COUNTRY = "IP Address not found" ]]; then
COUNTRY=`private_ip $1`
if [[ $COUNTRY != "" ]]; then
RESPONSE="ALLOW"
else
COUNTRY="IP Address not found"
fi
fi
if [[ "$RESPONSE" == "ALLOW" ]] ; then
logger -p auth.notice "$RESPONSE sshd/vsftpd connection from $1 ($COUNTRY)"
exit 0
else
logger -p auth.warn "$RESPONSE sshd/vsftpd 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