How to Secure Your VPS Firewall SSH Keys

Why VPS Security Matters So Much

Your VPS has a public IP address and exposes ports to the internet around the clock. Automated bots continuously scan for unprotected servers looking for weak passwords and known vulnerabilities. A freshly deployed VPS with default settings can be compromised within hours if you do not harden it immediately.

The good news is that the essential hardening steps are straightforward. This checklist covers everything you need to do right after deploying a new Linux VPS.

AsiaGB VPS includes Full Root Access, so you can implement every step in this guide from day one. Plans start at 500 THB/month.

1. Change the SSH Port from 22

Port 22 is the default SSH port and the first target every bot scans. Switching to a non-standard port such as 2222 or 54321 dramatically reduces brute-force attempts.

nano /etc/ssh/sshd_config
Change Port 22 to Port 2222
systemctl restart sshd

Always open the new port in your firewall before closing port 22 to avoid locking yourself out.

2. Disable Root Login and Create a Sudo User

Logging in directly as root is a major risk. Create a regular user with sudo privileges instead:

adduser yourusername
usermod -aG sudo yourusername

Then disable root SSH login in sshd_config:

Change PermitRootLogin yes to PermitRootLogin no

3. Set Up SSH Key Authentication

SSH keys are far stronger than passwords because an attacker needs both your private key file and its passphrase to gain access. Generate a key pair on your local machine:

ssh-keygen -t ed25519 -C "[email protected]"

Copy the public key to your VPS:

ssh-copy-id -i ~/.ssh/id_ed25519.pub yourusername@YOUR_VPS_IP

Once you confirm key-based login works, disable password authentication:

Change PasswordAuthentication yes to PasswordAuthentication no

4. Install and Configure UFW Firewall

UFW (Uncomplicated Firewall) makes it easy to allow only the ports your server needs:

apt install ufw -y
ufw default deny incoming
ufw default allow outgoing
ufw allow 2222/tcp (your new SSH port)
ufw allow 80/tcp (HTTP)
ufw allow 443/tcp (HTTPS)
ufw enable

5. Keep the System Updated

Most exploits target known vulnerabilities that have already been patched. Failing to apply updates is one of the most common causes of server compromises:

apt update && apt upgrade -y
Enable automatic security updates: apt install unattended-upgrades -y

6. Install Fail2ban

Fail2ban monitors log files and automatically bans IP addresses that show repeated failed login attempts, effectively blocking brute-force attacks:

apt install fail2ban -y
systemctl enable fail2ban
systemctl start fail2ban

7. Regular Backups

Even the most hardened server can fail. Regular backups are your last line of defence. See our VPS backup guide for a complete backup strategy.

Hardening SSH End-to-End (key-only, disable root login, change port)

The sections above covered SSH settings one by one, but in practice you should configure them together in /etc/ssh/sshd_config, because SSH is the main gateway to your server. Harden this door well and the odds of an intruder getting in drop dramatically. The principle is simple: keys only (no passwords), no direct root login, and a port moved off 22 to cut down on automated bot noise.

Here is a recommended configuration for Ubuntu on an AsiaGB VPS. Edit the file with nano /etc/ssh/sshd_config and set these values:

# /etc/ssh/sshd_config — recommended values
Port 2222
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
ChallengeResponseAuthentication no
UsePAM yes
MaxAuthTries 3
LoginGraceTime 30
AllowUsers yourusername
X11Forwarding no
ClientAliveInterval 300
ClientAliveCountMax 2

After editing, validate the syntax and restart the service — but do not close your existing session until you have confirmed a new login works in a separate terminal:

sshd -t                      # validate syntax before restarting
systemctl restart ssh        # or: systemctl restart sshd
# Open a new terminal and try: ssh -p 2222 yourusername@YOUR_VPS_IP

Avoid locking yourself out: always keep one SSH session open while testing. If a misconfiguration prevents new logins, the existing session lets you revert the change. This is the single most common way people lock themselves out of a VPS.

Using MaxAuthTries 3 and LoginGraceTime 30 limits the number of attempts and time per connection, while AllowUsers acts as a whitelist: only the listed users may log in over SSH, so even if a bot guesses another valid username, it cannot get in.

Firewall + Fail2Ban + Regular Updates (three layers working together)

Good protection never relies on a single measure; it works in layers (defense in depth). The three baseline layers every VPS should have are a firewall that closes all but the necessary ports, Fail2Ban to ban IPs that attempt brute-force attacks, and automatic updates that patch vulnerabilities before they can be exploited.

Start with UFW: set the default incoming policy to deny, then open only the ports you actually use:

ufw default deny incoming
ufw default allow outgoing
ufw allow 2222/tcp        # your new SSH port
ufw allow 80/tcp          # HTTP
ufw allow 443/tcp         # HTTPS
ufw limit 2222/tcp        # rate-limit SSH connections (anti brute-force)
ufw enable
ufw status verbose        # review all rules

Next, configure Fail2Ban with an SSH jail that matches your new port. Create /etc/fail2ban/jail.local (never edit jail.conf directly — it gets overwritten on update):

# /etc/fail2ban/jail.local
[sshd]
enabled  = true
port     = 2222
maxretry = 3
findtime = 600
bantime  = 3600
backend  = systemd

This means a single IP that fails to log in three times within 10 minutes (findtime = 600) is banned for one hour (bantime = 3600). Restart the service with systemctl restart fail2ban and check the ban status with fail2ban-client status sshd.

The final layer is updates. Most exploits target vulnerabilities that have already been patched, so configure unattended-upgrades to install security updates automatically:

apt update && apt upgrade -y
apt install unattended-upgrades -y
dpkg-reconfigure --priority=low unattended-upgrades   # enable it

Least Privilege and Disabling Unused Services

The principle of least privilege — granting only the minimum access required — is the heart of server security. Every running service, user, and open port adds one more piece of attack surface. The less you expose, the smaller the chance of being breached.

Start by surveying which services are listening on ports, then disable the ones you do not need:

ss -tulpn                          # see which services are listening
systemctl list-units --type=service --state=running
systemctl disable --now SERVICE    # disable unused services (e.g. cups, avahi-daemon)

Least-privilege practices worth adopting:

Binding databases to localhost is a step many people miss. If MySQL or PostgreSQL listens directly on the internet, bots will scan, find it, and immediately attempt brute-force. Always verify bind-address = 127.0.0.1 in your database config file.

Monitoring and Backups Are Part of Security

Many people think security ends at the firewall and SSH keys, but in reality visibility (monitoring) and recoverability (backups) are the two pillars that make a system resilient to real incidents. If you are breached but never notice, the damage spreads; if you have no backup when data is lost, it is game over.

For monitoring, start with the built-in tools and review logs regularly:

journalctl -u ssh --since "1 hour ago"   # review SSH access logs
last -20                                   # recent login history
grep "Failed password" /var/log/auth.log   # find failed login attempts
apt install auditd -y                       # install the audit framework

Things worth watching regularly include unusual logins (odd hours or foreign IPs), abnormal spikes in CPU, RAM, or disk usage (a possible sign of a cryptominer that was secretly installed), and files in /etc or the web root that change for no known reason.

For backups, follow the 3-2-1 rule: keep three copies of your data, on two types of media, with at least one copy offsite. Most importantly, test your restores periodically — a backup you cannot restore is no backup at all. See our VPS backup guide for a complete strategy.

Security Checklist Summary

  1. Change the SSH port from 22
  2. Disable root login, create a sudo user
  3. Enable SSH key authentication, disable password login
  4. Configure UFW firewall and open only required ports
  5. Keep packages up to date (unattended-upgrades)
  6. Install and configure a Fail2ban jail matching your port
  7. Apply least privilege and disable unused services
  8. Bind databases to 127.0.0.1 only
  9. Set up monitoring and review logs regularly
  10. Back up using the 3-2-1 rule and test restores

Frequently Asked Questions

Does changing the SSH port really improve security?

Changing the port off 22 is not a true security measure (it is security through obscurity), but it dramatically reduces noise from bots that automatically scan port 22, keeping your logs cleaner and easing the load on Fail2Ban. It is only a supplementary layer — the real protection comes from using SSH keys, disabling password login, and disabling root login, which should all be done together.

What should I do if a misconfiguration locks me out of my VPS?

The best safeguard is to always keep your existing SSH session open while making changes. If you do lock yourself out, AsiaGB VPS provides Console / VNC access through the control panel, giving you direct server access without SSH. You can log in via the console and revert your sshd_config or firewall rules.

Do I still need Fail2Ban if I already use SSH keys?

Using both is recommended. SSH keys prevent password guessing, but Fail2Ban also reduces server load from unwanted connections and can cover other services too (such as web logins and mail). It also mitigates light DoS from connection flooding. Multiple layers are always safer than one.

How often should I back up my VPS?

It depends on how quickly your data changes. A site with orders or a frequently updated database should be backed up daily (or more often for the database), while a static site that rarely changes may only need weekly backups. More important than frequency is keeping backups offsite and testing restores periodically to ensure you can actually recover when needed.

VPS with Full Root Access for Complete Security Control

Implement every security measure yourself. Linux VPS starting at 500 THB/month.

View VPS Plans