VPS security: first steps (firewall, Fail2ban and SSH keys)

A newly created VPS starts receiving login attempts from bots within minutes. With five simple steps you close the doors most used by automated attacks: automatic updates, a firewall, blocking of repeated attempts and SSH key access. The commands work on Ubuntu and Debian and must be run as root.

1. Update the system

# apt update
# apt full-upgrade -y
If a kernel update is installed, reboot the server with reboot when you can.

2. Enable automatic security updates

# apt install -y unattended-upgrades
# systemctl enable --now unattended-upgrades apt-daily.timer apt-daily-upgrade.timer
From then on, security fixes are installed on their own every day.

3. Turn on the firewall (UFW)

Allow SSH before enabling the firewall, otherwise your current connection drops. Also allow the ports of the services you will use, such as 80 and 443 for websites:

# apt install -y ufw
# ufw allow OpenSSH
# ufw allow 80,443/tcp
# ufw enable
# ufw status
Note: ports published by Docker bypass UFW rules. On servers running Docker, publish only the ports you need.

4. Block repeated attempts with Fail2ban

Fail2ban temporarily blocks addresses that get the SSH password wrong several times. It comes configured for SSH out of the box:

# apt install -y fail2ban
# fail2ban-client status sshd

5. Log in with an SSH key and turn off the password

On your computer (not on the server), generate a key pair and copy the public key to the server. On Windows, use PowerShell or Terminal:

# ssh-keygen -t ed25519
# ssh-copy-id root@SERVER-IP
On Windows, which has no ssh-copy-id, copy the content of .ssh\id_ed25519.pub in your user folder to /root/.ssh/authorized_keys on the server.

Open a new connection and confirm you get in without a password prompt. Only then turn off password login on the server:

# nano /etc/ssh/sshd_config.d/00-och.conf
Leave the file like this:

PermitRootLogin prohibit-password
PasswordAuthentication no
# sshd -t && systemctl reload ssh
From then on, the server only accepts logins with your key. If you lose the key, use the recovery console in your account panel to log in and revert the setting.
If you have any difficulties, open a support ticket: Open ticket