If you’ve ever managed an ssh server that’s open on the internet server you might have noticed a bunch of IPs scanning and trying to login from all over the world. Frequently from ips originating from China. If you want to prevent these simply moving the default port might be enough in some cases but in others you might also want to start blocking those ips when they make too many failed attempts. Using a vpn with a private network, like openvpn, would be the best way to access your server remotely, but barring that locking down your ssh is the next best thing.
In this guide we’ll change the default port for ssh from 22 to 22222, install fail2ban to watch for failed attempts and correctly setup the jail for the ubuntu firewall. We’ll also set the reporting email to send to you from the correct email address which should help you get the notices when fail2ban blocks a bad actor. This guide works for Ubuntu 14, 15, and 16. All of the commands below are designed for you to be able to copy and paste them into your shell.
The first step is to install fail2ban. Which does exactly as the name suggests, bans ip addresses for too many failed attempts to login.
apt-get -y install fail2ban
Setup fail2ban to use ufw and to know that ssh is on port 22222
/etc/fail2ban/jail.local is the correct file to setup custom jail behaviors and not hacking up the default config files.
cat >/etc/fail2ban/jail.local <<EOL [ssh] enabled = true banaction = ufw port = 22222 filter = sshd logpath = /var/log/auth.log maxretry = 3 EOL
Change email that reports blocking from too many login attempts.
sed -i -- 's/destemail = [email protected]/destemail = [email protected]/g' /etc/fail2ban/jail.conf sed -i -- 's/sender = r[email protected]/sender = [email protected]/g' /etc/fail2ban/jail.conf
Setup the ssh server to listen on port 22222
This also leaves ssh listening on port 22, but in the next step you’re not turning on access to port 22 via the ufw firewall.
grep -q "Port 22222" /etc/ssh/sshd_config; [ $? -eq 1 ] && perl -pi -w -e 's/Port 22/Port 22\nPort 22222\n/g;' /etc/ssh/sshd_config
Restart the SSH server to pickup the new port
This is an important step, if you don’t restart ssh it won’t listen on port 22222 and you might get locked out.
service ssh restart
Setup ufw to allow ports 443/80/25/22222. By omitting 22 you’re blocking the default ssh port.
It might be a good idea for you to also allow port 22 in this step, then come back after you verify you can login on port 22222 and delete the rule for port 22 with a “ufw deny 22/tcp”
ufw default deny incoming ufw default allow outgoing ufw allow 443/tcp ufw allow 80/tcp ufw allow 25/tcp ufw allow 22222/tcp ufw logging on
Turn the firewall on
Caution, enabling the firewall could remove your ability to access your server if you haven’t set your ssh server and firewall access to the ports correctly.
Check status of firewall
Log back into your server and verify its working
ssh -p 22222 [email protected]