Secure your Linux VPS on first boot
Update the system, create a user, turn off root password login and enable the firewall.
Update the system
- 1.Connect to your VPS with SSH.
- 2.Type
apt update && apt upgrade -y, then Enter. - 3.If the system asks for a reboot, type
reboot, wait a minute, then reconnect.
On Rocky Linux and AlmaLinux, replace apt update && apt upgrade -y with dnf upgrade -y, the sudo group with wheel, the ssh service with sshd, and ufw with firewalld.
Create a user to work with
- 1.Install sudo if it is missing:
apt install -y sudo. - 2.Create the user:
adduser alice. Choose a password, the other questions can stay empty (Enter). - 3.Give it administration rights:
usermod -aG sudo alice. - 4.Open a second terminal and connect with
ssh alice@203.0.113.10. - 5.Type
sudo whoami. The answerrootconfirms everything works.
Turn off root password login
Do not touch this file before you have a working SSH key. With PasswordAuthentication no and no key, nobody can log in.
- 1.On your computer, create an SSH key if you do not have one yet: see Switch to an SSH key.
- 2.Send the key to your user:
ssh-copy-id alice@203.0.113.10. - 3.Test with
ssh alice@203.0.113.10. You must get in without being asked for the user password. - 4.Open the VPS configuration file:
sudo nano /etc/ssh/sshd_config. - 5.Set
PermitRootLogin noandPasswordAuthentication no. Save with Ctrl+O, Enter, then exit with Ctrl+X. - 6.Reload SSH:
sudo systemctl restart ssh. - 7.Without closing the old terminal, open a third one and test
ssh alice@203.0.113.10.
Keep one terminal connected until the final test. On Ubuntu, also check the files in /etc/ssh/sshd_config.d/: one of them may set PasswordAuthentication yes again.
Enable the firewall
On our VPS, all ports are open: it is up to you to choose which ones stay reachable.
- 1.Install ufw:
sudo apt install -y ufw. - 2.Allow SSH:
sudo ufw allow 22/tcp. - 3.If the VPS hosts a website, also allow the web:
sudo ufw allow 80/tcpandsudo ufw allow 443/tcp. - 4.Enable the firewall:
sudo ufw enable, then typey. - 5.Check with
sudo ufw status.
Always allow SSH before ufw enable, or you lose access. If that happens, the VPS VNC console lets you take back control from the browser.
Block repeated attempts with fail2ban
- 1.Install fail2ban:
sudo apt install -y fail2ban. - 2.Start it:
sudo systemctl enable --now fail2ban. - 3.Check the SSH protection with
sudo fail2ban-client status sshd.
On Rocky Linux and AlmaLinux, fail2ban comes from the EPEL repository: first install epel-release with sudo dnf install -y epel-release.