Cybersecurity

Secure a New Linux Server in 30 Minutes: SSH Keys, Firewall, Fail2ban and Auto-Updates

A fresh VPS starts getting login attempts from bots within minutes. This step-by-step checklist locks it down with SSH keys, a firewall, Fail2ban and automatic security updates, without locking yourself out.

Secure a New Linux Server in 30 Minutes: SSH Keys, Firewall, Fail2ban and Auto-Updates
On this page
  1. Step 1: Update everything
  2. Step 2: Create a normal user with sudo
  3. Step 3: Switch to SSH key authentication
  4. Step 4: Disable password and root login
  5. Step 5: Turn on the firewall (UFW)
  6. Step 6: Ban repeat offenders with Fail2ban
  7. Step 7: Install security updates automatically
  8. Final checklist
  9. What this does and doesn't protect against

Who this is for: anyone who just created a VPS or cloud server (DigitalOcean, Hetzner, AWS EC2, Azure and so on) running Ubuntu or Debian. Commands are for Ubuntu 22.04/24.04 and Debian 12, and most steps apply to other distributions with small changes.

Golden rule for this whole guide: keep your current SSH session open until you have confirmed a new session works. That one habit prevents almost every lock-out.

Put a server on the public internet and check its authentication log an hour later. You will almost certainly find failed login attempts for users like root, admin and ubuntu from addresses all over the world. These are automated bots trying common passwords around the clock. They aren't targeting you specifically; they target everyone. The defaults on many images (password login, root access) make their job easier.

You can see this on your own server:

sudo grep "Failed password" /var/log/auth.log | tail -n 20
# on systems without auth.log (e.g. Debian 12):
sudo journalctl -u ssh --since "1 hour ago" | grep -i "failed"

Let's shut that door.

Step 1: Update everything#

sudo apt update && sudo apt upgrade -y

Cloud images are often weeks or months old. Patching first closes known vulnerabilities before you do anything else. If a kernel update was installed, reboot with sudo reboot and reconnect.

Step 2: Create a normal user with sudo#

Working as root all the time means one typo can destroy the system, and it gives attackers a username they already know. Create your own user (replace saad with your name):

sudo adduser saad
sudo usermod -aG sudo saad

Some providers (such as AWS with its ubuntu user) already give you a non-root sudo user. In that case you can skip this step.

Step 3: Switch to SSH key authentication#

An SSH key pair is far stronger than any password a human can remember, and it can't be guessed by a bot. The private key stays on your laptop. The public key goes on the server.

On your own computer (Linux, macOS, or Windows PowerShell), generate a key:

ssh-keygen -t ed25519 -C "saad-laptop"

Press Enter to accept the default location, and set a passphrase. If your laptop is ever stolen, the passphrase stops the key from being used.

Copy the public key to the server. On Linux and macOS:

ssh-copy-id saad@YOUR_SERVER_IP

On Windows PowerShell, which doesn't include ssh-copy-id:

type $env:USERPROFILE\.ssh\id_ed25519.pub | ssh saad@YOUR_SERVER_IP "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

Now open a new terminal and log in. You should get in without being asked for the account password (you may be asked for your key's passphrase):

ssh saad@YOUR_SERVER_IP

Don't continue until this works.

Step 4: Disable password and root login#

Modern Ubuntu and Debian read extra SSH settings from files in /etc/ssh/sshd_config.d/. There's an important trap here: for most settings, OpenSSH uses the first value it finds, and files are read in alphabetical order. Some cloud images ship a file such as 50-cloud-init.conf containing PasswordAuthentication yes. If you put your settings in a file named 99-..., the cloud file wins and passwords stay enabled.

So name your file so it sorts first:

sudo nano /etc/ssh/sshd_config.d/00-hardening.conf
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3

Check the configuration for errors, then confirm the effective settings:

sudo sshd -t
sudo sshd -T | grep -Ei "^(permitrootlogin|passwordauthentication|kbdinteractiveauthentication)"

You should see permitrootlogin no and passwordauthentication no. Then restart SSH (the service is called ssh on Ubuntu/Debian and sshd on Red Hat-based systems):

sudo systemctl restart ssh

Test in a new terminal again before closing your existing session. You can also confirm that passwords are now refused:

ssh -o PubkeyAuthentication=no saad@YOUR_SERVER_IP
# expected: Permission denied (publickey).

Step 5: Turn on the firewall (UFW)#

UFW ("Uncomplicated Firewall") blocks every incoming port except the ones you explicitly allow. The order of these commands matters: allow SSH before enabling the firewall, or you will cut off your own connection.

sudo apt install ufw -y
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow OpenSSH
# only if this server hosts a website:
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
sudo ufw status verbose

Many cloud providers also offer a network-level firewall (often called security groups). Using both is good defence in depth: the provider's firewall blocks traffic before it reaches your server, and UFW protects you if that rule is ever misconfigured.

Step 6: Ban repeat offenders with Fail2ban#

With passwords disabled, bots can't get in, but they still fill your logs and waste resources. Fail2ban watches for repeated failures and temporarily blocks the offending IP address.

sudo apt install fail2ban -y
sudo nano /etc/fail2ban/jail.local
[sshd]
enabled  = true
maxretry = 5
findtime = 10m
bantime  = 1h
# Debian 12 and other systems without /var/log/auth.log:
# backend = systemd

Always put your changes in jail.local, never jail.conf, because package updates can overwrite jail.conf. Then:

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

After a few hours, that status command will usually show a list of banned IPs. If you ever ban yourself by accident, unban from another connection with sudo fail2ban-client set sshd unbanip YOUR_IP.

Step 7: Install security updates automatically#

sudo apt install unattended-upgrades -y
sudo dpkg-reconfigure -plow unattended-upgrades

Choose "Yes". Security patches will now install daily without you remembering to do it. Ubuntu cloud images often have this enabled already, so this step just confirms it.

Final checklist#

CheckCommandExpected
Root login disabledsudo sshd -T | grep permitrootloginpermitrootlogin no
Passwords disabledsudo sshd -T | grep passwordauthenticationpasswordauthentication no
Firewall activesudo ufw statusStatus: active, only needed ports allowed
Fail2ban runningsudo fail2ban-client status sshdJail listed, with a ban count
Listening servicessudo ss -tulpnNothing unexpected exposed to 0.0.0.0

What this does and doesn't protect against#

These steps stop the vast majority of automated attacks on a new server: password guessing, root brute-forcing and exposure through forgotten open ports. They don't protect a vulnerable web application you deploy later, weak database passwords, or a stolen laptop with an unencrypted private key. Keep your applications updated, give each service the minimum permissions it needs, and keep backups somewhere other than the server itself.

Building something on this server that stores user accounts? Read our guide to hashing vs encryption vs encoding so the passwords in your database are protected too.

Sources and further reading: sshd_config manual (OpenSSH) · Ubuntu Server docs: OpenSSH · Ubuntu community docs: UFW · Fail2ban project

M
About the author

Writes about AI, cybersecurity and software development for Techoria.

More articles →