Hardening SSH on Ubuntu Server 20.04
Warning
This guide is not meant for a business critical production environment.
If you have a personal or development server, you can follow this guide to harden an ubuntu server, version 20.04, with extended security measures to help fend off intruders but in a business critical production environment, you will want to lock it down more than explained here.
For the sake of this guide, I am going to assume you already have Ubuntu server installed on a local machine or via a service. It will also assume you have a non-root user with sudo permissions.
2FA
-
Install the openssh-server package (if not already installed)
sudo apt update sudo apt install openssh-server
-
Install the Google Authenticator package
sudo apt install libpam-google-authenticator
-
Run the Google Authenticator setup program with
google-authenticator
and enter y for all the questions -
Scan the QR code with Google Authenticator or FreeOTP on your mobile device
-
Open the SSH configuration file so we can edit the contents
sudo vi /etc/ssh/sshd_config
-
Find the lines below in the
sshd_config
file and make sure they match the below example.UsePam yes PermitEmptyPasswords no ChallengeResponseAuthentication yes PasswordAuthentication yes
-
Save and close the file.
-
Open your SSH PAM configuration file for editing.
sudo vi /etc/pam.d/sshd
-
Add the line below to the bottom of the
sshd
file.auth required pam_google_authenticator.so
-
Save and close the file.
-
Restart the SSH service.
sudo systemctl restart ssh
-
Stay signed in & try to connect in a new terminal tab to make sure the authentication is working correctly.
Fail2ban
-
Install fail2ban
sudo apt install fail2ban
-
Create / open a local jail file.
sudo vi /etc/fail2ban/jail.local
-
Add extra SSH protection by adding the lines below to the local jail file you just created. Please replace the ##Home_IP## with your home IP address or ignore that line altogether.
[sshd] enabled = true maxretry = 3 bantime = -1 findtime = 24h ignoreip = ##Home_IP##
-
Restart fail2ban for the changes to take effect.
sudo systemctl reload fail2ban
UFW
-
Default deny everything incoming unless otherwise specified
sudo ufw default deny incoming
-
Allow SSH access through the firewall
sudo ufw allow ssh
-
Enable SSH
sudo ufw enable