How to Harden a Fresh Linux Server in 15 Minutes

A step-by-step baseline for securing a new Linux server: updates, a non-root user, locked-down SSH, a firewall, fail2ban, and automatic patching.

8 min read
AI-assisted

Author's AI disclosure

The author reports using AI to help with this article.

The author confirms reviewing this article.

How to Harden a Fresh Linux Server in 15 Minutes

Your New Server Is Already Being Probed

Spin up a fresh server with a public IP address and check its login logs an hour later. In most cases you will find automated scanners trying root, admin, and ubuntu with thousands of common passwords. Nobody is targeting you. Bots simply sweep the entire internet, looking for easy wins.

The good news is that most real-world compromises are not clever. They come from the basics: weak or reused passwords, services exposed to the internet that should not be, and software that was never patched. Fixing those handful of things shuts the door on the vast majority of automated attacks.

This guide is a 15-minute baseline. It is not a complete security program, and it will not stop a determined attacker. But it turns a wide-open server into a solid starting point.

The commands target Ubuntu and Debian, with notes for RHEL, Fedora, and Rocky where they differ.

Before You Start: Do Not Lock Yourself Out

Many people have locked themselves out of a server while hardening it. Prepare for that:

  • Know where your provider's web console is. It lets you log in even when SSH is broken.

  • Keep your current SSH session open until you have confirmed the new settings work in a second terminal.

  • Take a snapshot first if your provider offers one.

  • Do things in the order shown. In particular, set up your key and non-root user before disabling password and root logins.

The 15-Minute Checklist

Step

Task

Time

1

Update everything

2 min

2

Create a non-root admin user

1 min

3

Set up SSH keys and lock down SSH

4 min

4

Turn on a firewall

2 min

5

Install fail2ban

2 min

6

Enable automatic security updates

1 min

7

Remove or restrict unneeded services

2 min

8

Verify everything

1 min

Let us go through them.

Step 1: Update Everything (2 minutes)

A fresh image can be weeks or months out of date. Patch it first.

# Debian / Ubuntu
sudo apt update && sudo apt upgrade -y

# Fedora / RHEL / Rocky
sudo dnf upgrade -y

If the kernel or core libraries were updated, a reboot is needed. On Ubuntu and Debian, check for this file:

ls /var/run/reboot-required && sudo reboot

Step 2: Create a Non-Root Admin User (1 minute)

Working as root means every typo has maximum power, and root is the first username attackers try. Create a regular user with sudo rights instead.

# Debian / Ubuntu
sudo adduser deploy
sudo usermod -aG sudo deploy

# Fedora / RHEL / Rocky
sudo useradd -m deploy
sudo passwd deploy
sudo usermod -aG wheel deploy

Replace deploy with whatever name you like. Confirm it works:

su - deploy
sudo whoami          # should print: root

Step 3: SSH Keys and a Locked-Down SSH Server (4 minutes)

Passwords can be guessed. Keys effectively cannot. This is the single most valuable change you can make.

3a. Create a key on your own computer (skip if you already have one)

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

Set a passphrase when asked.

3b. Copy the public key to the server

Run this from your own computer:

ssh-copy-id deploy@SERVER_IP

3c. Test key login before changing anything

ssh deploy@SERVER_IP

You should get in without being asked for the account password (you may be asked for your key's passphrase). If this does not work, stop and fix it now.

3d. Lock down the SSH server

Create a small override file on the server. The file name matters, and I will explain why below.

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

Put this inside:

PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
LoginGraceTime 30
X11Forwarding no
AllowUsers deploy

What these do: root cannot log in over SSH, passwords are refused entirely, failed attempts are capped, and only the listed user may connect.

Why 00- in the file name? SSH uses the first value it reads for each setting, and files in sshd_config.d are read in alphabetical order. Some cloud images ship a file such as 50-cloud-init.conf that sets PasswordAuthentication yes. If your file sorts after it, yours silently loses. Starting the name with 00- makes it win.

Check the syntax, then reload:

sudo sshd -t                              # no output means the config is valid
sudo systemctl reload ssh                 # Debian / Ubuntu (the service is "sshd" on RHEL)
sudo sshd -T | grep -E 'passwordauthentication|permitrootlogin'

The last command prints the settings SSH is actually using. You want to see passwordauthentication no and permitrootlogin no.

Now test from a second terminal (do not close your first one yet):

ssh deploy@SERVER_IP                      # should work
ssh root@SERVER_IP                        # should be denied

About changing the SSH port: moving SSH from port 22 to something else cuts down log noise, but it is not real security. If you do it, update your firewall rules first, and do not treat it as a substitute for keys.

Step 4: Turn On a Firewall (2 minutes)

A firewall ensures that only the ports you intentionally expose are reachable.

Ubuntu / Debian (ufw)

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw limit OpenSSH           # allow SSH, with rate limiting against brute force
sudo ufw allow 80/tcp            # only if this is a web server
sudo ufw allow 443/tcp           # only if this is a web server
sudo ufw enable
sudo ufw status verbose

Allow SSH before you run ufw enable. Enabling a deny-all firewall without an SSH rule cuts off your own session.

Fedora / RHEL / Rocky (firewalld)

sudo systemctl enable --now firewalld
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --permanent --add-service=http      # only if needed
sudo firewall-cmd --permanent --add-service=https     # only if needed
sudo firewall-cmd --reload
sudo firewall-cmd --list-all

Two important extras

  1. Use your cloud provider's firewall too (security groups or network firewalls). It blocks traffic before it ever reaches your server.

  2. Docker can bypass ufw. Docker edits the firewall rules itself, so a container started with -p 8080:80 may be reachable from the internet even if ufw says otherwise. For services that should stay private, bind them to localhost: -p 127.0.0.1:8080:80.

Step 5: Install fail2ban (2 minutes)

fail2ban watches your logs and temporarily bans IP addresses that repeatedly fail to log in.

sudo apt install fail2ban                 # Debian / Ubuntu
sudo dnf install fail2ban                 # Fedora / RHEL (may need EPEL on RHEL/Rocky)

Never edit the default config directly. Create a local override:

sudo nano /etc/fail2ban/jail.local
[DEFAULT]
bantime  = 1h
findtime = 10m
maxretry = 5

[sshd]
enabled = true

Start it and check:

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

An honest note: once password logins are disabled, brute-force attempts cannot succeed anyway. fail2ban mostly reduces log noise and server load for SSH, but it becomes much more valuable when you protect other services such as a web login or mail server.

Step 6: Enable Automatic Security Updates (1 minute)

Most breaches use vulnerabilities that already have patches. Let the server apply security fixes itself.

# Debian / Ubuntu
sudo apt install unattended-upgrades
sudo dpkg-reconfigure --priority=low unattended-upgrades
sudo unattended-upgrade --dry-run --debug     # confirm it works

Some updates need a reboot. To schedule that for a quiet hour, set these in /etc/apt/apt.conf.d/50unattended-upgrades:

Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "03:00";

Only enable automatic reboots if a short restart at that time is acceptable for your workload.

On Fedora / RHEL / Rocky:

sudo dnf install dnf-automatic
# in /etc/dnf/automatic.conf set:  upgrade_type = security   and   apply_updates = yes
sudo systemctl enable --now dnf-automatic-install.timer

Step 7: Remove or Restrict Unneeded Services (2 minutes)

Every listening service is a potential way in. See what is open:

sudo ss -tulpn

Look at the Local Address column:

  • 0.0.0.0 or [::] means reachable from anywhere (subject to your firewall).

  • 127.0.0.1 means reachable only from the server itself.

For each service, ask: do I need this, and does it need to be public?

sudo systemctl disable --now servicename     # stop and disable it
sudo apt purge packagename                   # or remove it entirely

Typical candidates on a fresh server are mail transfer agents you do not use, cups, avahi-daemon, and rpcbind.

Databases and caches should almost never be public. Redis, MongoDB, PostgreSQL, MySQL, and Elasticsearch left open to the internet are among the most common causes of data leaks. Bind them to localhost (or a private network) in their config files, for example bind 127.0.0.1 for Redis or bind-address = 127.0.0.1 for MySQL, and use SSH tunnels for remote access.

Step 8: Verify Everything (1 minute)

Trust, but verify. Run these checks.

# On the server
sudo sshd -T | grep -E 'passwordauthentication|permitrootlogin|allowusers'
sudo ufw status verbose                       # or: sudo firewall-cmd --list-all
sudo fail2ban-client status
sudo ss -tulpn
timedatectl | grep synchronized               # accurate time matters for logs
# From your own computer
ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no deploy@SERVER_IP
# expected: Permission denied (publickey)

ssh root@SERVER_IP
# expected: Permission denied

You can also scan your own server from outside with nmap -Pn SERVER_IP to see which ports are really open. Only scan servers you own or have permission to test.

Bonus: A Read-Only Audit Script

Here is a small script that checks your baseline without changing anything. It builds on the Bash scripting skills from earlier in this series. It is written for Ubuntu and Debian.

#!/usr/bin/env bash
set -u

check() {
  # $1 = description, $2 = command that succeeds when the check passes
  if bash -c "$2" >/dev/null 2>&1; then
    printf '[ OK ]  %s\n' "$1"
  else
    printf '[FAIL]  %s\n' "$1"
  fi
}

check 'Root SSH login is disabled'      "sudo sshd -T | grep -qi '^permitrootlogin no'"
check 'SSH password login is disabled'  "sudo sshd -T | grep -qi '^passwordauthentication no'"
check 'Firewall (ufw) is active'        "sudo ufw status | grep -q 'Status: active'"
check 'fail2ban is running'             "systemctl is-active --quiet fail2ban"
check 'Automatic updates are enabled'   "systemctl is-enabled --quiet unattended-upgrades"
check 'Clock is synchronized'           "timedatectl | grep -q 'synchronized: yes'"

Run it after setup and again every few months to catch drift.

What to Do After the First 15 Minutes

The baseline above handles the basics. When you have more time, consider these next steps:

  • Keep AppArmor or SELinux enabled. Do not disable them to "fix" a permissions problem. Learn to adjust the policy instead.

  • Take backups, and test restoring them. A backup you have never restored is a hope, not a plan.

  • Keep SSH off the public internet by placing it behind a VPN or a private network (WireGuard and Tailscale are popular choices).

  • Add two-factor authentication for SSH if the server is high value.

  • Run a security audit tool such as Lynis (sudo lynis audit system) and work through its suggestions.

  • Centralize logs so an attacker cannot erase the evidence on the same machine.

  • Review who has access regularly, and remove users and keys that are no longer needed.

  • Consider file integrity monitoring (for example, AIDE) and the auditd framework for sensitive systems.

  • Compare against a benchmark such as the CIS Benchmarks for your distribution.

Common Mistakes to Avoid

  1. Disabling password login before testing key login. This is the classic way to lock yourself out.

  2. Enabling the firewall before allowing SSH.

  3. Leaving databases and admin panels open to the world.

  4. Disabling SELinux or AppArmor as a quick fix.

  5. Assuming the firewall covers Docker. It may not.

  6. Setting it up once and never looking again. Patches, users, and open ports change over time.

  7. Storing secrets in scripts or shell history. Use environment files with strict permissions or a secrets manager.

Final Thoughts

Security is not a single switch. It is layers: strong authentication, a small attack surface, timely patches, and visibility into what is happening. In fifteen minutes, you can put the most important layers in place, and that already puts your server ahead of the many machines running with default settings.

Do this on your next server before you install anything else. Then set a reminder to run the audit script monthly. Good security is mostly consistent, boring habits.

Comments0

Log in to join the discussion.

No comments yet.

Arpan Singh

Read articles by this author.

Subscribe to Arpan Singh's newsletter

Get the articles this author chooses to send by email.