On this page
Why VPS hardening is not optional but a necessity
The moment your server is connected to the internet with a public IP address, it becomes a target. This is not scaremongering but a measurable reality: put a new server on the internet with SSH open on port 22 and watch its logs after a single hour. You will find dozens or even hundreds of login attempts from IP addresses around the world, trying common usernames (root, admin, user) and passwords from leaked lists. These are not attacks aimed at you personally but bots that scan the entire internet automatically, looking for any server with a weak default configuration to break into.
The difference between shared hosting and a VPS is fundamental here. On shared hosting, the provider takes care of securing the server and you are isolated in your account. On an unmanaged VPS, you are solely responsible for security from layer zero. The server reaches you with a raw operating system and a root password, and everything after that (hardening, updates, monitoring) is up to you. This power is itself the source of the risk: a server left at its default configuration without hardening is an open invitation.
The consequences are not theoretical. A compromised server may be used to send spam, getting your IP blocklisted; turned into a node in a DDoS botnet; used to mine cryptocurrency, with the miner devouring its CPU and your bill; or, worst of all, your customers' data and your databases may be stolen. More dangerous still, a breach is often silent: the attacker does not want you to discover it, but to stay as long as possible.
The philosophy: defense in depth
The principle that governs this whole guide is defense in depth: do not rely on a single layer of protection, but build several independent layers so that if an attacker breaks through one, the next stops them. If you relied only on a strong password, leaking it would mean everything collapses. But if login is by SSH key (not a password), on a non-standard port, behind a firewall that rejects every port except the allowed ones, with Fail2ban banning repeated attempts and a user with limited privileges who does not have root, then breaking through a single layer is not nearly enough.
Each layer in this diagram is independent of the others, and each adds a new obstacle for the attacker. The layers from the outside in: access control (SSH keys and disabling root), the firewall (UFW), intrusion detection and blocking (Fail2ban), attack surface reduction (stopping services), self-protection (automatic updates), and finally visibility and recovery (monitoring and backups). We will build these layers one by one.
Overview of the hardening map (an initial checklist)
Before diving into the commands, here is the complete roadmap in a single table. This is the checklist we will apply step by step, ordered by priority:
| # | Hardening action | Layer | Priority | Risk if neglected |
|---|---|---|---|---|
| 1 | Create a non-root user with sudo privileges | Access control | Critical | Running everything as root |
| 2 | Set up SSH keys for authentication | Access control | Critical | Relying on a guessable password |
| 3 | Disable root login over SSH | Access control | Critical | Root targeted directly |
| 4 | Disable password authentication | Access control | Critical | Brute-force attacks |
| 5 | Change the SSH port (optional) | Access control | Medium | Automated scanning noise |
| 6 | Restrict users with AllowUsers | Access control | High | Logins to unintended accounts |
| 7 | Enable the UFW firewall | Firewall | Critical | All ports exposed |
| 8 | Install and configure Fail2ban | Intrusion detection | High | Unlimited guessing |
| 9 | Enable automatic security updates | Self-protection | Critical | Known vulnerabilities left unpatched |
| 10 | Stop unnecessary services | Attack surface reduction | High | Ports open for no reason |
| 11 | Secure databases and services | Attack surface reduction | High | A database exposed to the world |
| 12 | Set permissions on sensitive files | Attack surface reduction | High | Unauthorized reading/modification |
| 13 | Set up logging and monitoring | Visibility | Medium | A silent, undetected breach |
| 14 | Set up off-site backups | Recovery | Critical | Permanent data loss |
If you are starting from a completely empty server and have not done the basic setup yet (first connection, system update), start with the guide to setting up your first VPS from scratch, then come back here for the advanced hardening layers. And if you are not yet comfortable with the basics of connecting, the article on SSH basics is the right starting point.
Layer 1: a non-root user and the principle of least privilege
The first mistake beginners make is living inside the root account. The root user is the absolute god of a Linux system: it can delete any file, change any setting, and install or remove anything without restriction. Doing your daily work as root means that any typo could destroy the system, and that any compromised program immediately gains full control. The solution is the principle of least privilege: always work with the least privileges your task requires, and elevate privileges temporarily only when needed, through sudo.
Creating a user with sudo privileges
Connect to the server as root the first time, then create a new user (we will call it deploy as an example) and add it to the sudo group:
# Create the new user (you will be asked for a password and optional details)
adduser deploy
# Add the user to the sudo group (on Ubuntu/Debian)
usermod -aG sudo deploy
# On AlmaLinux/CentOS, use the wheel group instead of sudo:
# usermod -aG wheel deploy
# Check that the user is in the right group
groups deployYou now have a deploy user that can run administrative commands by typing sudo before them (and will be asked for its password to confirm). Remember: do not move on to disabling root login until you are completely sure the deploy user works and can log in and get sudo; otherwise you may lock yourself out of the server.
The principle of least privilege in practice
| Wrong practice | Safe alternative | Reason |
|---|---|---|
| Daily work as root | A regular user + sudo when needed | Limits the impact of mistakes and breaches |
sudo su - to stay as root for long | sudo <command> for each command | An open root session is a permanent risk |
| Running web apps as root | A dedicated service user (www-data) | Isolates the app from the system |
| Passwordless sudo for everyone | sudo with a password, limited to those who need it | Prevents automatic escalation |
Layer 2: SSH keys instead of a password
The most important security decision you will ever make is giving up the SSH password and replacing it with cryptographic keys. A password, however long, can be guessed, can be stolen by phishing, and is tried automatically millions of times. An SSH key, on the other hand, is a huge mathematical pair (usually 256 bits for Ed25519): a private key that stays on your computer and never leaves it, and a public key placed on the server. The private key cannot be derived from the public one, and it cannot be guessed in practice.
As the diagram shows, when you connect, the server asks you to prove that you hold the private key without actually revealing it (by signing a mathematical challenge). This kind of authentication is almost completely immune to guessing.
Generating the key pair on your computer
Run this on your local computer (not on the server). We recommend the modern Ed25519 algorithm, which is fast and more secure:
# Generate an Ed25519 key pair (the best choice today)
ssh-keygen -t ed25519 -C "deploy@my-vps" -f ~/.ssh/id_ed25519
# An alternative compatible with very old systems (4096-bit RSA)
# ssh-keygen -t rsa -b 4096 -C "deploy@my-vps"You will be asked to enter a passphrase for the private key: enter a strong one. This is an extra layer of security: even if the private key file is stolen, the attacker is still helpless without the passphrase. You will get two files: id_ed25519 (the private key: guard it with your life and never share it) and id_ed25519.pub (the public key: this is the one copied to the server).
Copying the public key to the server
# The easiest way: ssh-copy-id copies the public key to the user on the server
ssh-copy-id -i ~/.ssh/id_ed25519.pub deploy@203.0.113.10
# If ssh-copy-id is not available, copy it manually:
cat ~/.ssh/id_ed25519.pub | ssh deploy@203.0.113.10 \
"mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"Now try logging in: ssh deploy@203.0.113.10. You should get in without being asked for the server account's password (you may be asked for the key's passphrase if you set one). Do not take a single step further until you are sure key login works, because the next step disables the password for good. For more detail on generating and managing keys, see SSH basics.
Layer 3: hardening the sshd configuration
Now we come to the heart of hardening: the SSH service's configuration file on the server, located at /etc/ssh/sshd_config. This is where we disable everything that opens the door to attackers. Open the file in an editor (do this from the deploy session with sudo):
sudo nano /etc/ssh/sshd_configEdit (or add) the following values. The most important: PermitRootLogin no, PasswordAuthentication no, and setting the port and the allowed users:
# A non-standard port reduces automated scanning noise (optional but useful)
Port 2222
# Block direct root login: log in as a regular user, then sudo
PermitRootLogin no
# Disable password authentication completely: keys only
PasswordAuthentication no
ChallengeResponseAuthentication no
KbdInteractiveAuthentication no
# Enable public key authentication explicitly
PubkeyAuthentication yes
# Block empty passwords and limit attempts and sessions
PermitEmptyPasswords no
MaxAuthTries 3
MaxSessions 5
LoginGraceTime 30
# Restrict login to specific users only
AllowUsers deploy
# Disable X11 forwarding if you do not need it
X11Forwarding noAfter saving, test that the configuration is valid before restarting to avoid breaking the service:
# Check the file's syntax for errors before applying it
sudo sshd -t
# If no error appears, restart the SSH service
sudo systemctl restart ssh
# On some systems the service name may be sshd:
# sudo systemctl restart sshdCritical: before you close your current session, open a new SSH session in a separate window and make sure you can log in with the new port and user (ssh -p 2222 deploy@203.0.113.10). If it works, close the old one safely. If it fails, your old session is still open so you can fix the mistake. This rule saves you from the "I locked myself out of the server" scenario.
Recommended sshd_config settings
| Setting | Recommended value | Default | What it does |
|---|---|---|---|
Port | 2222 (or any port other than 22) | 22 | Reduces automated scanning of the well-known port |
PermitRootLogin | no | prohibit-password | Prevents root from being targeted directly |
PasswordAuthentication | no | yes | Eliminates password-guessing attacks |
PubkeyAuthentication | yes | yes | Enables key-based authentication |
PermitEmptyPasswords | no | no | Blocks accounts without a password |
MaxAuthTries | 3 | 6 | Limits authentication attempts per connection |
LoginGraceTime | 30 | 120 | Shortens the time allowed to complete login |
AllowUsers | deploy | (all) | Restricts login to specific users |
X11Forwarding | no | yes/no | Disables graphical interface forwarding |
ChallengeResponseAuthentication | no | Varies | Closes alternative authentication paths |
An important note: if you change the port, you will need to open the new port in the UFW firewall before restarting SSH (the next step); otherwise UFW will block your new connection. The safe order: open the port in UFW first, then change the port in sshd, then restart.
Layer 4: the UFW firewall
The firewall is the guard at the server's gate: it decides which network traffic is allowed and which is rejected. The golden principle is a default deny policy: reject all incoming connections, then open only the ports you actually need, rather than opening everything and trying to plug the holes later. UFW (short for Uncomplicated Firewall) makes this easy on Ubuntu/Debian.
# Install UFW if it is not already present
sudo apt update && sudo apt install -y ufw
# The most important step: deny all incoming, allow all outgoing
sudo ufw default deny incoming
sudo ufw default allow outgoing
# Allow the SSH port, if you are on the default port:
sudo ufw allow OpenSSH
# If you changed the SSH port to 2222, allow it explicitly instead of the previous line:
sudo ufw allow 2222/tcp
# Allow web traffic (HTTP and HTTPS) if you host a site
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
# Enable the firewall (it warns it may cut SSH; make sure you allowed your port first)
sudo ufw enable
# Check the status and the active rules
sudo ufw status verboseA critical warning: before running ufw enable, be 100% sure you have allowed the correct SSH port (whether OpenSSH or 2222). If you enable the firewall with a deny policy without allowing the SSH port, your session will be cut immediately and you will only be able to get back in through the console in your provider's control panel.
Common ports in UFW
| Service | Port | Protocol | UFW command | When to open it |
|---|---|---|---|---|
| SSH (default) | 22 | TCP | ufw allow OpenSSH | For remote administration |
| SSH (custom) | 2222 | TCP | ufw allow 2222/tcp | When you change the port |
| HTTP | 80 | TCP | ufw allow 80/tcp | For websites (and HTTPS redirects) |
| HTTPS | 443 | TCP | ufw allow 443/tcp | For SSL-encrypted sites |
| MySQL/MariaDB | 3306 | TCP | Never open it to the world | Local only (see below) |
| PostgreSQL | 5432 | TCP | Never open it to the world | Local only |
| Redis | 6379 | TCP | Never open it to the world | Local only |
| FTP | 21 | TCP | Avoid it (use SFTP) | Unencrypted: dangerous |
Note the golden rule in the table: database and Redis ports are never opened to the world. These services should listen on 127.0.0.1 only, so they do not need a UFW rule at all; we will cover this in the section on securing services.
Restricting ports to a specific source
For more hardening, you can restrict the SSH port to your own IP address only (if you have a static IP):
# Allow SSH only from a specific IP address (replace it with yours)
sudo ufw allow from 198.51.100.25 to any port 2222 proto tcp
# To delete an old rule by number: list the numbered rules, then delete
sudo ufw status numbered
sudo ufw delete 3Layer 5: Fail2ban against brute-force attacks
Even after disabling the password, bots will keep knocking on the SSH port. This is where Fail2ban comes in: a tool that monitors the server's logs and, when it detects a number of failed attempts from a single IP address within a short period, automatically bans that address through the firewall for a set time. This turns guessing from unlimited attempts into a handful before the ban.
# Install Fail2ban
sudo apt update && sudo apt install -y fail2ban
# Do not edit jail.conf directly: create jail.local so it survives updates
sudo nano /etc/fail2ban/jail.localPut the following content in jail.local. It sets the general rules and then enables SSH protection (note that the port matches your custom port):
[DEFAULT]
# Ban duration (in seconds): one hour here
bantime = 3600
# Window for counting attempts (in seconds): 10 minutes
findtime = 600
# Number of failed attempts before a ban
maxretry = 3
# Do not ban your trusted addresses (add your computer's IP and localhost)
ignoreip = 127.0.0.1/8 ::1 198.51.100.25
[sshd]
enabled = true
port = 2222
# On modern Ubuntu it reads from the systemd journal
backend = systemd
maxretry = 3
bantime = 3600Start the service and check its status:
# Enable Fail2ban and start it at boot
sudo systemctl enable --now fail2ban
# Check the overall service status
sudo fail2ban-client status
# Check the sshd jail specifically (banned IPs, attempt count)
sudo fail2ban-client status sshdUseful Fail2ban commands
| Task | Command | Note |
|---|---|---|
| Status of all jails | sudo fail2ban-client status | Shows the active jails |
| Status of a specific jail | sudo fail2ban-client status sshd | Shows the banned IPs |
| Ban an IP manually | sudo fail2ban-client set sshd banip 203.0.113.7 | Immediate ban |
| Unban an IP | sudo fail2ban-client set sshd unbanip 203.0.113.7 | When banned by mistake |
| Reload the configuration | sudo fail2ban-client reload | After editing jail.local |
| Test the regular expression | sudo fail2ban-regex /var/log/auth.log <filter> | For diagnosing filters |
An important tip: add your computer's IP address to ignoreip to avoid banning yourself by mistake if you get the login wrong several times. If you do lock yourself out, you will need to log in through the provider's console and lift the ban with unbanip.
Layer 6: automatic security updates
The biggest source of server compromises is known, unpatched vulnerabilities. When a vulnerability is discovered in a package, the fix is released quickly, but if you do not install it, you stay exposed. The solution: automatic security updates through the unattended-upgrades package, which installs security patches without manual intervention.
# Install the tool and the priority configuration package
sudo apt update
sudo apt install -y unattended-upgrades apt-listchanges
# Enable automatic updates (when prompted, choose Yes)
sudo dpkg-reconfigure -plow unattended-upgrades
# Adjust the details in the configuration file
sudo nano /etc/apt/apt.conf.d/50unattended-upgradesIn the 50unattended-upgrades file, make sure the security updates source is enabled, and enable automatic removal of unused packages and rebooting when necessary (at a quiet time):
Unattended-Upgrade::Allowed-Origins {
"${distro_id}:${distro_codename}-security";
"${distro_id}ESMApps:${distro_codename}-apps-security";
};
// Automatically remove unused dependencies
Unattended-Upgrade::Remove-Unused-Dependencies "true";
// Reboot automatically if a kernel update requires it, at a quiet time
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "04:00";Enable the periodic schedule in the 20auto-upgrades file:
sudo nano /etc/apt/apt.conf.d/20auto-upgradesAPT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::AutocleanInterval "7";
APT::Periodic::Unattended-Upgrade "1";Test that everything works without actually applying anything:
# A dry run that shows what would be updated without installing
sudo unattended-upgrade --dry-run --debugAutomatic update options
| Option | Value | Effect |
|---|---|---|
Allowed-Origins | -security | Installs security patches only (the safest) |
Automatic-Reboot | true | Reboots when the kernel is updated |
Automatic-Reboot-Time | 04:00 | Schedules the reboot for a quiet time |
Remove-Unused-Dependencies | true | Cleans up orphaned packages automatically |
Unattended-Upgrade (periodic) | 1 | Enables the daily job |
A tip: limit automatic updates to security patches only, and leave major feature upgrades to be applied manually after testing, so that an update does not break your application unsupervised.
Layer 7: reducing the attack surface
Every running service and every open port is a potential door for an attack. Reducing the attack surface means shutting down everything you do not actually need: stop unnecessary services, close unused ports and remove superfluous packages. The rule: what is not running cannot be hacked.
Finding out what is listening on the network
First, find out what is actually listening on the ports:
# List all listening ports with their programs (the modern ss tool)
sudo ss -tulpn
# An older alternative for those who prefer netstat
# sudo netstat -tulpn
# To scan the ports from outside (from another machine) with nmap
nmap -sV 203.0.113.10Look in the output for any service listening on 0.0.0.0 (all interfaces) that you do not recognize or do not need. Every line is an exposed port that you must either justify or close.
Stopping and removing unnecessary services
# List all services enabled at boot
sudo systemctl list-unit-files --type=service --state=enabled
# Stop a service and prevent it from starting at boot (example: a service you do not need)
sudo systemctl disable --now avahi-daemon
# Remove an unnecessary package completely (common example: a default mail server)
sudo apt purge -y exim4 exim4-base
sudo apt autoremove -yExamples of services that are often present without being needed: avahi-daemon (local network discovery), cups (printing), rpcbind, and default mail servers such as exim4 on a server that does not send email. Check each service before stopping it.
Securing services: make them listen locally
The most dangerous misconfiguration is leaving a database listening on all interfaces (0.0.0.0), so it is exposed to the internet. The right approach is to have it listen on 127.0.0.1 only, so your local application can reach it and no one from outside can.
# MySQL/MariaDB: in /etc/mysql/mariadb.conf.d/50-server.cnf make sure of:
# bind-address = 127.0.0.1
# PostgreSQL: in postgresql.conf make sure of:
# listen_addresses = 'localhost'
# Redis: in /etc/redis/redis.conf make sure of:
# bind 127.0.0.1 ::1
# protected-mode yes
# After editing, restart the service and check it is no longer on 0.0.0.0
sudo systemctl restart mariadb
sudo ss -tulpn | grep 3306The Nginx web server should be hardened by hiding its version, preventing script execution in upload folders and adding security headers:
# In /etc/nginx/nginx.conf, inside http {}, hide the Nginx version
# server_tokens off;
# Test the configuration, then reload
sudo nginx -t && sudo systemctl reload nginxTo go deeper into Nginx and security headers (CSP, HSTS, X-Frame-Options), see the guide to HTTP security headers, which explains each header and how to set it.
Permissions on sensitive files
Wrong permissions on sensitive files allow users who should not reach them to read or modify them. Set them precisely:
# The user's SSH folder: 700 (owner only)
chmod 700 ~/.ssh
# The authorized keys file: 600
chmod 600 ~/.ssh/authorized_keys
# The private key (if present on the server): 600
chmod 600 ~/.ssh/id_ed25519
# The global SSH configuration file, owned by root, with 644
sudo chown root:root /etc/ssh/sshd_config
sudo chmod 644 /etc/ssh/sshd_config
# Configuration files containing passwords (such as wp-config.php): 640, owned by the web user
sudo chown www-data:www-data /var/www/html/wp-config.php
sudo chmod 640 /var/www/html/wp-config.phpPermissions for sensitive files
| File/folder | Permissions | Owner | Reason |
|---|---|---|---|
~/.ssh | 700 | The user | Prevents others from seeing the keys |
~/.ssh/authorized_keys | 600 | The user | Read/write for the owner only |
~/.ssh/id_ed25519 (private) | 600 | The user | Protects the private key |
~/.ssh/id_ed25519.pub (public) | 644 | The user | Public but not modifiable |
/etc/ssh/sshd_config | 644 | root | System configuration protected from modification |
wp-config.php | 640 | www-data | Hides the database credentials |
| Web folders | 755 | www-data | Execute/read with no world write |
| Web files | 644 | www-data | Read without execute |
Layer 8: logs, monitoring and alerts
Hardening is not complete without visibility: the ability to know what is happening on your server and to detect anomalies early. The worst breach is the silent one you do not notice for months. Logs are your eyes on the server.
# Monitor failed and successful login attempts (Ubuntu/Debian)
sudo journalctl -u ssh --since "today"
# Or the file directly on some systems:
sudo tail -f /var/log/auth.log
# Recent successful logins
last -a | head -20
# Failed login attempts
sudo lastb | head -20
# Monitor resource usage in real time (to detect hidden mining)
top
# Or, better
htopMonitoring indicators
| Indicator | Command/source | Danger sign |
|---|---|---|
| Failed SSH attempts | /var/log/auth.log, lastb | A sudden spike from a single IP |
| CPU usage | htop, top | An unknown process using 100% |
| Open network connections | ss -tunp | Outgoing connections to strange addresses |
| Disk space | df -h | Sudden filling up (may be an attack log) |
| Unknown processes | ps aux | Programs you do not recognize |
| Changes to system files | AIDE/Tripwire | A sensitive file's fingerprint has changed |
| New logins | last | Logins at unusual times |
For advanced monitoring, consider installing a file integrity checker such as AIDE, which takes a "fingerprint" of system files and alerts you to any unexpected change, and a rootkit scanner such as rkhunter:
# Scan for rootkits periodically
sudo apt install -y rkhunter
sudo rkhunter --update
sudo rkhunter --check --skip-keypressLayer 9: off-site backups
All the hardening above reduces the likelihood of disaster, but it does not eliminate it. Backups are the last safety net: if the server is compromised, its data is encrypted by ransomware, or there is a hardware failure, the off-site backup is what brings you back to life. The golden rule is 3-2-1: three copies of the data, on two different media, one of them off-site.
Most importantly: the backup must be off the server itself. A copy on the same disk does not help you if the server is compromised or the hardware fails. Send it to object storage (such as Cloudflare R2 or S3) or to another server:
# Example: archive the site's database and files, then upload them to external storage
# 1) Back up the database
mysqldump -u root -p --all-databases | gzip > /tmp/db-$(date +%F).sql.gz
# 2) Archive the site's files
tar czf /tmp/www-$(date +%F).tar.gz /var/www
# 3) Sync securely to an external server/storage with rsync over SSH
rsync -avz -e "ssh -p 2222" /tmp/db-*.sql.gz /tmp/www-*.tar.gz \
backup@backup-server:/backups/
# 4) Schedule the backup daily with cron
crontab -e
# Add the following line to run daily at 3 a.m.:
# 0 3 * * * /home/deploy/scripts/backup.shTest restores regularly. A backup whose restore has never been tested is not a backup but a hope. Set a monthly appointment to restore a backup on a test server and confirm it is complete and intact. To dig deeper into backup strategies and scheduling, see the backup guide.
Backup layers
| Type | Frequency | Location | Use |
|---|---|---|---|
| Provider snapshot | Daily/weekly | Provider's control panel | Fast recovery of the whole system |
| Database backup | Daily | External storage | Restoring critical data |
| Files backup | Daily/weekly | External storage | Restoring content and settings |
| Full off-site copy | Weekly | Another geographic region | Major disasters |
2FA for SSH (an extra layer)
For a higher level of security, you can add two-factor authentication (2FA) to SSH through Google Authenticator, so that, in addition to the key, a time-based code (TOTP) from an app on your phone is required. This combines "something you have" (the key) with a second "something you have" (the phone) in an independent layer:
# Install the PAM module for TOTP
sudo apt install -y libpam-google-authenticator
# Run the setup for each user (generates a QR code and emergency codes)
google-authenticatorEnabling it requires editing /etc/pam.d/sshd and setting AuthenticationMethods publickey,keyboard-interactive in sshd_config. Be careful and always test in a new session before closing the current one, because this step is delicate and can lock you out if it is misconfigured.
Expert tips for after the basic hardening
- Review your logs weekly: set aside 10 minutes to review
lastbandauth.log. Anomalous patterns show up early for anyone who looks. - Use a password manager for key passphrases and service accounts. Never reuse them.
- Separate environments: do not share one server between production and testing. A breach of the test environment must not reach production.
- Least privilege for applications: run each application as a dedicated service user with limited privileges, not as root and not as your admin user.
- Document your configuration: keep a record (off the server) of what you changed and why, to make recovery and rebuilding easier.
- Enable automatic alerts: set up an email notification for every successful SSH login, so you know immediately about any unexpected login.
- Harden the control panel if there is one: if you run cPanel or another panel, it has its own attack surface; see securing cPanel.
- Also update manually on a regular basis: automatic updates cover security, but review major upgrades manually each month, after a backup.
Troubleshooting
Most of the problems you will face during hardening involve locking yourself out of the server. This table covers the common symptoms, their causes and their fixes:
| Symptom | Possible cause | Fix |
|---|---|---|
Permission denied (publickey) after disabling the password | The public key was not copied correctly, or the .ssh permissions are wrong | Log in through the provider's console and check authorized_keys and its permissions (600) and the .ssh folder (700) |
Connection refused after changing the port | You are connecting on the old port, or UFW is blocking the new one | Connect with -p 2222 and make sure of ufw allow 2222/tcp |
Connection timed out after enabling UFW | The port is not allowed in the firewall, or the provider's firewall blocks it | Open the port in UFW and in the Cloud Firewall in the provider's panel |
I locked myself out after ufw enable | You enabled deny without allowing SSH | Log in through the provider's console and run ufw allow 2222/tcp |
| Fail2ban banned my IP | You exceeded maxretry, or your IP is not listed in ignoreip | Via the console: fail2ban-client set sshd unbanip <ip> and add it to ignoreip |
sudo: command not found for the new user | The user is not in the sudo/wheel group | As root: usermod -aG sudo deploy |
| The site does not open after enabling UFW | Port 80/443 is not allowed | ufw allow 80/tcp and ufw allow 443/tcp |
| The app cannot reach the database after binding locally | The app connects via an external IP, not localhost | Set the app's connection to 127.0.0.1 |
sshd -t shows a syntax error | A typo in sshd_config | Fix the indicated line and do not restart until sshd -t passes |
If you lock yourself out of SSH completely
Your most important safety net is the emergency console (Console/VNC) in the provider's control panel. Every serious VPS provider offers browser-based access to the server that does not go through SSH or the firewall at all. Through it you can log in as root (or with the user's password) and fix any mistake in sshd_config, UFW or Fail2ban. That is why we repeat it throughout the guide: do not close your old session until you have confirmed the new one works, and know how to reach your provider's console before you need it.
Frequently asked questions
Does changing the SSH port really harden the server? Changing the port greatly reduces the noise of automated scans targeting the well-known port 22, so your logs get less cluttered and random guessing attempts drop. But it is security by obscurity, not real protection on its own: a port scanner such as nmap finds your port within seconds. Treat it as a nice complementary improvement on top of the real foundation: SSH keys, disabled password login, the firewall and Fail2ban.
Do I need all these layers for a small project? Yes, at least the basics. SSH keys, disabling root and password login, UFW and automatic updates are not "advanced hardening" but the minimum for any server on the internet, however small your project. Bots do not distinguish between big and small sites: they attack any exposed IP. You add the more advanced layers (2FA, AIDE) according to how sensitive your project is.
What is the difference between disabling root and deleting it?
We disable root login over SSH (PermitRootLogin no); we do not delete the account. The root account stays in place and is essential for the system, but you no longer log in with it directly from the internet; instead, you log in as a regular user and elevate privileges with sudo. Deleting root itself is a bad idea that can break the system.
Is Fail2ban a replacement for SSH keys? No, they are two different, complementary layers. SSH keys prevent guessing in the first place (there is no password to guess). Fail2ban protects against flooding the server with connection attempts and also blocks attacks on other services. Real security combines the two as part of defense in depth, rather than one replacing the other.
Why should the database listen on localhost only?
Because a web application on the same server reaches the database through 127.0.0.1 with no need to expose it to the internet. Leaving the database listening on 0.0.0.0 makes it a direct target for brute-force attacks and exploits from anywhere in the world. Listening locally eliminates this surface completely without affecting how your application works.
How often should I update the server? Security patches should be installed automatically every day through unattended-upgrades; this is not something to postpone. Major upgrades (OS releases, feature updates), on the other hand, should be applied manually each month or as needed, always after taking a backup and testing, so that a big update does not break your application unsupervised.
Can automatic updates break my site?
The chance is small if you limit them to the security source (-security) only, as in the setup in this guide, because security patches are designed to be as backward compatible as possible. The risk comes from major feature upgrades, which is why we leave those to be applied manually. As a precaution, run backups daily so you can roll back if something unexpected happens.
What do I do if I discover my server really has been compromised? Disconnect it from the internet or stop the exposed services immediately, and do not trust the compromised server at all. The safest course is generally a clean rebuild: a new server, restoring data from a trusted backup made before the breach, changing every password and key, then applying this guide from scratch. Cleaning a compromised server "by hand" with complete confidence is almost impossible, because you do not know what the attacker planted.
Do I need a firewall if my provider has a cloud firewall? Yes, use both: this is defense in depth. The cloud firewall filters traffic before it reaches the server, and UFW filters at the level of the system itself as a second layer. If the cloud firewall is misconfigured or disabled, UFW is still your guard. Relying on a single layer goes against the whole principle of defense in depth.
Is two-factor authentication (2FA) for SSH necessary? It is not necessary in most cases if you use SSH keys with a strong passphrase, because the key alone is highly resistant to guessing. But it is valuable for highly sensitive servers or when several people access them, since it adds an independent factor (your phone), so possessing the key alone is not enough. Weigh the extra security against the setup complexity according to your server's sensitivity.
Is all this enough, or is there more hardening to do? This guide covers the strong core hardening that stops the overwhelming majority of automated attacks. For more sensitive environments, layers such as intrusion detection systems (IDS), network segmentation, auditd auditing, kernel hardening (sysctl) and isolated containers are added. But if you apply the checklist here in full, you are ahead of the vast majority of servers exposed on the internet.
Summary and final checklist
Hardening a VPS is not a task you do once and forget, but an ongoing practice of defense in depth: successive layers, each stopping whatever got past the one before. Start with the non-negotiable foundation (SSH keys, disabling root and password login, the UFW firewall and automatic updates), then add Fail2ban, attack surface reduction, monitoring and backups. And do not forget the golden rule at every sensitive step: a new session for testing before closing the old one, and knowing the way to your provider's console before you need it.
Review this checklist before you consider your server hardened:
| ✓ | Item | Required state |
|---|---|---|
| ☐ | A non-root user with sudo privileges | Works and logs in successfully |
| ☐ | SSH keys | Key login works without a password |
| ☐ | PermitRootLogin no | Enabled and tested |
| ☐ | PasswordAuthentication no | Enabled and tested |
| ☐ | AllowUsers set | Restricts login to the allowed users |
| ☐ | SSH port (optional) | Opened in UFW before switching |
| ☐ | UFW with a deny policy + SSH/80/443 | Enabled and status confirms it |
| ☐ | Fail2ban on sshd | Running, with your IP in ignoreip |
| ☐ | unattended-upgrades | Enabled and tested with a dry run |
| ☐ | Unnecessary services stopped | ss -tulpn is clean |
| ☐ | Databases on localhost | Not listening on 0.0.0.0 |
| ☐ | Permissions on sensitive files | Set as in the table |
| ☐ | Monitoring and logs | Reviewed regularly |
| ☐ | Off-site backups | Working, with restores tested |
If you have completed every item on this checklist, you have built a hardened server that stands up to the vast majority of automated attacks and opportunistic attempts. Hardening is an ongoing journey, but this solid foundation is what separates an exposed server from a secure one.
Sources
Frequently asked questions
Does changing the SSH port really harden the server?
Changing the port greatly reduces the noise of automated scans targeting the well-known port 22, so your logs get less cluttered and random guessing attempts drop. But it is security by obscurity, not real protection on its own: a port scanner such as nmap finds your port within seconds. Treat it as a nice complementary improvement on top of the real foundation: SSH keys, disabled password login, the firewall and Fail2ban.
Do I need all these layers for a small project?
Yes, at least the basics. SSH keys, disabling root and password login, UFW and automatic updates are not "advanced hardening" but the minimum for any server on the internet, however small your project. Bots do not distinguish between big and small sites: they attack any exposed IP. You add the more advanced layers (2FA, AIDE) according to how sensitive your project is.
What is the difference between disabling root and deleting it?
We disable root login over SSH (PermitRootLogin no); we do not delete the account. The root account stays in place and is essential for the system, but you no longer log in with it directly from the internet; instead, you log in as a regular user and elevate privileges with sudo. Deleting root itself is a bad idea that can break the system.
Is Fail2ban a replacement for SSH keys?
No, they are two different, complementary layers. SSH keys prevent guessing in the first place (there is no password to guess). Fail2ban protects against flooding the server with connection attempts and also blocks attacks on other services. Real security combines the two as part of defense in depth, rather than one replacing the other.
Why should the database listen on localhost only?
Because a web application on the same server reaches the database through 127.0.0.1 with no need to expose it to the internet. Leaving the database listening on 0.0.0.0 makes it a direct target for brute-force attacks and exploits from anywhere in the world. Listening locally eliminates this surface completely without affecting how your application works.
How often should I update the server?
Security patches should be installed automatically every day through unattended-upgrades; this is not something to postpone. Major upgrades (OS releases, feature updates), on the other hand, should be applied manually each month or as needed, always after taking a backup and testing, so that a big update does not break your application unsupervised.
Can automatic updates break my site?
The chance is small if you limit them to the security source (-security) only, as in the setup in this guide, because security patches are designed to be as backward compatible as possible. The risk comes from major feature upgrades, which is why we leave those to be applied manually. As a precaution, run backups daily so you can roll back if something unexpected happens.
What do I do if I discover my server really has been compromised?
Disconnect it from the internet or stop the exposed services immediately, and do not trust the compromised server at all. The safest course is generally a clean rebuild: a new server, restoring data from a trusted backup made before the breach, changing every password and key, then applying this guide from scratch. Cleaning a compromised server "by hand" with complete confidence is almost impossible, because you do not know what the attacker planted.
Do I need a firewall if my provider has a cloud firewall?
Yes, use both: this is defense in depth. The cloud firewall filters traffic before it reaches the server, and UFW filters at the level of the system itself as a second layer. If the cloud firewall is misconfigured or disabled, UFW is still your guard. Relying on a single layer goes against the whole principle of defense in depth.
Is two-factor authentication (2FA) for SSH necessary?
It is not necessary in most cases if you use SSH keys with a strong passphrase, because the key alone is highly resistant to guessing. But it is valuable for highly sensitive servers or when several people access them, since it adds an independent factor (your phone), so possessing the key alone is not enough. Weigh the extra security against the setup complexity according to your server's sensitivity.
Is all this enough, or is there more hardening to do?
This guide covers the strong core hardening that stops the overwhelming majority of automated attacks. For more sensitive environments, layers such as intrusion detection systems (IDS), network segmentation, auditd auditing, kernel hardening (sysctl) and isolated containers are added. But if you apply the checklist here in full, you are ahead of the vast majority of servers exposed on the internet.