Hiding your SSH login from potential attackers is crucial for safeguarding your server. In this guide, we’ll explore how to further enhance your server’s security by limiting SSH logins based on the country of the connecting IP address. While this method adds an extra layer of security, it’s important to note that it may not prevent access if attackers are using VPNs with IP addresses from allowed countries. Nevertheless, every additional security measure helps mitigate risks.
Step 1: Create an Account on MaxMind
- Sign up for a MaxMind account and activate it by following the instructions sent to your email.
- In your account, navigate to “Manage License Keys” and generate a new license key.
- Download the configuration file provided and keep the Account/User ID and License key handy.
Step 2: Install Required GeoIP Packages
Install the necessary GeoIP packages by running the following command in your terminal:
sudo apt install geoip-bin geoip-database geoipupdate
Edit the configuration file /etc/GeoIP.conf
and update the AccountID and LicenseKey with the values obtained in Step 1.
Step 3: Download Database Updates
Execute the following command to download the initial GeoIP database:
sudo geoipupdate
Create a cron job to automate database updates:
sudo crontab -e
Add the following line to the crontab file:
0 4 * * 0 /usr/bin/geoipupdate > /dev/null 2>&1
Step 4: Create the geoiplookup Script
Create a shell script named sshfilter.sh
:
sudo nano /usr/local/bin/sshfilter.sh
Paste the following script into the file:
#!/usr/bin/env bash
set -e
set -x
# Uppercase space-separated country codes to ACCEPT
ALLOW_COUNTRIES="SE US"
if [[ $# -ne 1 ]]; then
echo "Usage: $(basename "$0") <ip>" 1>&2
exit 0 # Return non-zero in case of incorrect usage
fi
IP="$1"
COUNTRY=$(/usr/bin/geoiplookup "$IP" | awk -F ": " '{ print $2 }' | awk -F "," '{ print $1 }' | head -n 1)
if [[ "$COUNTRY" = "IP Address not found" ]] || [[ ! "$ALLOW_COUNTRIES" =~ "$COUNTRY" ]]; then
logger "DENY sshd connection from $IP ($COUNTRY)"
exit 1
else
exit 0
fi
Make the script executable:
sudo chmod +x /usr/local/bin/sshfilter.sh
Step 5: Lock Down SSH
Edit the /etc/hosts.deny
file and add the following line:
sshd: ALL
Edit the /etc/hosts.allow
file and add the following line:
sshd: ALL: aclexec /usr/local/bin/sshfilter.sh %a
Reload the sshd service:
sudo systemctl reload sshd
Step 6: Testing
Verify that the setup is working by attempting to SSH into your server from a different IP address. Check the system logs for any denial messages.
sudo grep "DENY" /var/log/syslog
Ensure that you’re able to SSH into your server from an allowed country by modifying the script accordingly.
Conclusion
Implementing country-based SSH login restrictions adds an extra layer of security to your server, mitigating potential risks from unauthorized access attempts. By following these steps, you can enhance your server’s security posture and minimize the exposure to malicious actors.