ZEROLAG

The right name for your project

Find a domain and check its availability with ZEROLAG.

Give your project a name.

Enter a domain name to check its availability.

How to secure a VPS: SSH keys, firewall, Fail2Ban and best practices

Linux terminal and SSH access checks.
Back to articles
Article contents

A new VPS must be secured before you host important applications or data on it. Start by updating the system, creating a non-root administrator and configuring SSH key authentication. Set up a firewall, Fail2Ban, automatic updates, backups and monitoring. The order is important: if you deactivate the password or root access before you check the new connection method, you can lock yourself out of the server.

The guide below is designed for Ubuntu Server and Debian. The controls must be adapted if you use AlmaLinux, Rocky Linux or a distribution with another package manager. Keep the current SSH session open until you successfully test a second connection.

Before you start

Make sure you have access to the VPS console in the supplier's panel. The console is the recovery method if the firewall or SSH configuration blocks network access. If the server already contains data, create a backup before the changes.

Check operating system and current user:

cat /etc/os-release
whoami
hostnamectl

In examples we use the user adminvps. You can replace it with your own name, different from root. Do not use the quotes or brackets in the explanations.

1. Update the operating system

Updates correct known vulnerabilities and errors. On Ubuntu or Debian is playing:

sudo apt update
sudo apt upgrade -y

If you are connected directly as root, the controls work without sudo. Check if the system requests restart:

test -f /var/run/reboot-required && cat /var/run/reboot-required || echo "Nu este necesară repornirea"

If necessary, restart the server at an appropriate time:

sudo reboot

Wait for the VPS to return and reconnect before you continue.

2. Create a separate administrative user

Permanent use of the root account increases the risk of a mistake and gives attackers a known username. Create a normal account and give it the right to use sudo:

sudo adduser adminvps
sudo usermod -aG sudo adminvps

Check group membership:

id adminvps

Open a second SSH connection and test authentication:

ssh adminvps@ADRESA_IP

After connection, check administrative access:

sudo whoami

The result must be: root. Do not disable root access yet and no password authentication.

3. Set up SSH key authentication

An SSH key uses a cryptographic pair: the private key remains on your computer, and the public key is installed on the server. The private key must not be sent to anyone and must not be copied to the VPS.

Generate the key on your computer

On Linux, MacOS or Windows PowerShell runs locally:

ssh-keygen -t ed25519 -a 100

Pick a password for the private key. It protects the key if the file reaches a lost or compromised device.

Copy Public Key to VPS

If you order ssh-copy-id on the computer:

ssh-copy-id adminvps@ADRESA_IP

On Windows you can display the public key as follows:

type $env:USERPROFILE\.ssh\id_ed25519.pub

It only copies the public key line, the one that usually starts with ssh-ed25519. On the server, connected as user adminvpscreate the necessary structure:

mkdir -p ~/.ssh
chmod 700 ~/.ssh
nano ~/.ssh/authorized_keys

Paste the public key on a single line, save the file, then set the permissions:

chmod 600 ~/.ssh/authorized_keys

Open another new connection and check authentication with key:

ssh adminvps@ADRESA_IP

Continue only if this connection works. Keep the initial session and the new session open until the end of SSH configuration.

4. Tighten SSH configuration

On modern Ubuntu it is recommended to keep the changes in a separate file from /etc/ssh/sshd_config.d/. For most OpenSSH directives, the first value found is used, which is why we choose a name that loads before other configuration fragments:

sudo nano /etc/ssh/sshd_config.d/00-zerolag-hardening.conf

Add:

PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
X11Forwarding no
MaxAuthTries 3

Before reloading the service, check the syntax:

sudo sshd -t

If no message appears, the configuration is valid. You can see the important actual values with:

sudo sshd -T | grep -E 'permitrootlogin|passwordauthentication|kbdinteractiveauthentication|pubkeyauthentication|maxauthtries'

Reload SSH service:

sudo systemctl reload ssh.service

Don't close the existing sessions. Open a new connection and check again with the administrative user and SSH key. After confirmation, direct login as a root and password authentication SSH should no longer work.

Should the port of SSH be changed?

The change of port may reduce the noise caused by automatic scans, but does not replace the SSH key, firewall and updates. If you choose a custom port, allow the new port in the firewall before changing SSH and check access in a separate session. A step in the wrong order can block the server's administration.

5. Enable the UFW firewall

Firewall must allow only the services used. Install UFW:

sudo apt install ufw -y

Set default policy:

sudo ufw default deny incoming
sudo ufw default allow outgoing

Allow SSH before activating firewall:

sudo ufw allow OpenSSH

If SSH is already running on a different 22 port, it allows real port instead of OpenSSH profile, for example sudo ufw allow NUMARUL_PORTULUI/tcp. Confirm active port with sudo sshd -T | grep '^port' before you activate the firewall.

If the VPS will host a website, allow HTTP and HTTPS:

sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

Enable firewall and check the rules:

sudo ufw enable
sudo ufw status verbose

For a database used only locally, do not open the public port. Services such as MySQL, PostgreSQL and Redis should only be displayed on the Internet if there is a clear need, IP restrictions and a secure configuration.

6. Check exposed services and ports

See what lawsuits they listen to on the network:

sudo ss -tulpn

For each port, it shall determine whether the service must be publicly accessible. Stop and disable unused services:

sudo systemctl disable --now NUME_SERVICIU

Replace NUME_SERVICIU only after you correctly identify the process. Do not disable SSH, network or other critical service without understanding its role.

You can check active services with:

systemctl --type=service --state=running

7. Install and configure Fail2Ban

Fail2Ban follows failed authentication and can temporarily block the addresses that repeat the tests. Do not replace firewall and do not repair a weak password, but add protection against automatic attacks.

Install Package:

sudo apt install fail2ban -y

Do not copy the entire file jail.conf. Create only the required local configuration:

sudo nano /etc/fail2ban/jail.d/sshd.local

Add:

[sshd]
enabled = true
backend = systemd
bantime = 1h
findtime = 10m
maxretry = 5

If you use a custom SSH port, add to the section [sshd] and line port = NUMARUL_PORTULUI.

Test configuration, activate service and check SSH jaille:

sudo fail2ban-client -t
sudo systemctl enable --now fail2ban
sudo fail2ban-client status
sudo fail2ban-client status sshd

If the service does not start, check the log:

sudo journalctl -u fail2ban --no-pager -n 100

8. Enable automatic security updates

A secure VPS today can become vulnerable if not updated. Install automatic update mechanism:

sudo apt install unattended-upgrades -y
sudo dpkg-reconfigure --priority=low unattended-upgrades

Check that the periodic updates are enabled:

cat /etc/apt/apt.conf.d/20auto-upgrades

You can test the process without the actual installation of updates:

sudo unattended-upgrade --dry-run --debug

Automatic updates reduce the exposure window but do not replace the administration. Some updates may require restart and important services should be monitored after changes.

9. Configure the backup before you need it

The VPS backend shall cover the application data, databases, configuration files and the secrets required for restoration. Keep at least one copy out of the VPS. If the attacker or an error can simultaneously delete the server and backup, the copy does not provide sufficient protection.

A snapshot is useful before an important update or for quick recovery, but it does not have to be the only method of backup. Define a policy based on how much information you can afford to lose and how long the service may remain unavailable.

Test the restoration. A backup file that cannot be checked or restored shall not be considered a secure copy.

10. Enable monitoring and check logs

Monitor at least availability, processor, memory, disk space and important services. For quick checks:

uptime
free -h
df -h
systemctl --failed

Check authentication and SSH log:

last -a | head
sudo journalctl -u ssh.service --since today

Configure alerts before the incident. A full disk, a stopped service or an unusual increase in consumption shall be observed automatically, not after a customer reports that the application is not working.

Additional recommended measures

Keep AppArmor active

Ubuntu uses AppArmor to limit the actions of certain applications. Check status with:

sudo aa-status

Do not disable system protections just to bypass an error. Identify the rule or configuration to be corrected.

Use authentication with two factors where possible

The supplier's panel, the email account and backup systems shall be protected by 2FA. SSH security does not help if an attacker can enter the VPS panel and use the console or reinstall.

Separate Secrets from Code

Do not keep passwords, tokens and API keys in public repositorys or directly in code. Use environment variables, files with restrictive permissions or a dedicated secret management system.

Run applications with minimum privileges

The web server, database and applications must not run as root. Create separate system users and give each service only the access it needs.

Common mistakes that can block access

  • deactivation of password before key authentication is tested;
  • activation of UFW prior to authorisation of the SSH port;
  • closing the only active session before testing the new configuration;
  • change the SSH without running the control sshd -t;
  • simultaneous change of user, port, firewall and authentication;
  • full copy of jail.conf in jail.local;
  • considering snapshots as the only backup;
  • public exposure of the database or Redis without real need.

Apply changes in small steps and check access after each step. If there's a problem, you'll know what change needs to be cancelled.

Checklist for securing a VPS

  • the operating system is updated;
  • there is a non-root administrator;
  • The connection of SSH with the key was tested in a new session;
  • Root direct login and password SSH authentication are disabled;
  • SSH configuration passes test sshd -t;
  • firewall only allows the necessary ports;
  • the unused services are stopped;
  • Fail2Ban is active and jailul sshd operate;
  • Automatic security updates are configured;
  • the backups are kept separately and the restoration is tested;
  • monitoring and alerts are active;
  • 2FA is activated in the supplier's panel and on important accounts.

Frequently asked questions

Is it enough to change the port of SSH?

No. A different port can reduce the automatic scans visible in logs, but does not provide real protection against an attacker who checks all ports. Use SSH keys, disable the login by password, limit access through the firewall and maintain the updated system.

When can I deactivate password authentication?

Only after you've tested the authentication with the key in a new connection and confirmed that the user can use sudo. Keep the initial session open until the end of the test.

Fail2Ban replaces firewall?

No. Firewall determines which ports are accessible. Fail2Ban analyses failed trials and can temporarily block abusive sources. The two mechanisms have different roles and must be used together.

Can I completely deactivate the root account?

You can disable direct root login via SSH and manage the server with a normal user that uses sudo. The root system account continues to exist for administrative operations.

Is the VPS Snapshots a backup?

It's a useful copy for a quick comeback, but it doesn't have to be the only backup. Keep separate copies and test the restoration of important data.

How often does a VPS have to be checked?

Monitoring shall be permanent and alerts shall be automatic. Updates, logs, backups and services must be reviewed regularly and after any significant change.

What do I do if I'm stuck outside the server?

Use the console available in the supplier's panel to correct the firewall rule or SSH configuration. Therefore, access to the console should be checked before changes are made.

Conclusion

Securing a VPS does not end after installing the firewall. It is a continuous process based on updates, access with minimum privileges, monitoring, safety copies and regular verification of exposed services.

If you’re still deciding what resources your project needs, read our guide to what a VPS is and when you might need one. For virtualized KVM infrastructure hosted in Romania, see the ZEROLAG VPS configurations.

Choose the next step
for your project.

Explore the relevant service or discuss your requirements with us.

Explore your options