ssh into ubuntu

Securing your Ubuntu SSH Server the Right Way

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.

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.

Change email that reports blocking from too many login attempts.

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.

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.

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”

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