Skip to content
subuilds.dev

← logbuild #15 passed1011954

Linux Server Security Baseline: What Every DevOps Engineer Should Apply

Seven hardening steps to run on any fresh Debian or Ubuntu server: an AWS EC2 instance, a GCP VM, or bare metal. They cover SSH hardening, UFW, Fail2ban, and automatic security updates.

· 16 min read

Every new Linux server starts with the same insecure defaults: root login enabled, port 22 open to everyone, password auth on. It does not matter if it is an EC2 instance, a GCP VM, a DigitalOcean droplet, or a bare-metal machine. Bots will find it within hours.

I run these seven steps on every new Debian or Ubuntu server before I put anything else on it. This work is called hardening: you make the server harder to attack.

Environment: Debian / Ubuntu, using apt.


In Simple Words#

The problem
A new Linux server is easy to attack. Root can log in, passwords are accepted, and SSH listens on port 22. Bots find the server within hours.
The root cause
A new server image comes with defaults that are not strict enough. It is also often weeks behind on security updates. And every bot scanner knows port 22.
The solution
Run seven steps on every new server. Update it, create a normal user, log in with an SSH key, and turn off root and password login. Then move the SSH port, turn on the UFW firewall, and let Fail2ban ban IPs that keep trying.
Think of it like this
A new house comes with the front door unlocked. Before you move in, you fit your own lock and close every window you do not use. You also put a guard at the door who sends away people who keep trying keys.

What We’ll Cover#

  1. Update the system — fix known security bugs (CVEs) before you put anything else on the server
  2. Create a non-root sudo user — so nobody uses root directly over SSH
  3. Set up SSH key authentication — replace passwords with cryptographic keys
  4. Disable root login and password auth — lock down the SSH daemon (the SSH server program)
  5. Change the SSH port — get less noise from automated scanners (+ when NOT to do it)
  6. Configure UFW firewall — deny all incoming traffic by default
  7. Install Fail2ban — auto-ban IPs that brute-force your SSH port (try many logins until one works)
  1. A fresh server. Root login is on, passwords are on, and SSH listens on port 22. Bots try to log in.
  2. Step 1: update the system and turn on automatic security updates.
  3. Steps 2 and 3: create a normal user with sudo, and set up login with an SSH key.
  4. Step 4: turn off root login and password login. A bot without your key cannot log in.
  5. Steps 5 and 6: move SSH to port 2222 and turn on UFW. UFW blocks all traffic that you did not allow.
  6. Step 7: Fail2ban bans an IP that keeps failing to log in.
6 / 6

Step 1: Update the System#

Patch everything before you do anything else. A patch is an update that fixes a bug. New server images are often weeks behind on security updates.

bash
sudo apt update && sudo apt full-upgrade -y
sudo reboot now

Reboot if a kernel update was applied. The running kernel should be the one you just patched.

Enable Automatic Security Updates#

People forget manual updates. unattended-upgrades installs security patches automatically, so you do not have to remember.

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

Answer Yes when it asks. This turns on automatic installs for the Debian-Security origin only. That is a careful and safe choice.


Step 2: Create a Non-Root Sudo User#

Logging in directly as root is risky. Root can change everything on the system. One stolen session or one mistyped command can damage all of it. Create a separate user, and use sudo only when you really need root rights.

bash
sudo adduser deploy
sudo usermod -aG sudo deploy

Replace deploy with any username you like. Verify:

bash
groups deploy
# deploy : deploy sudo

Step 3: Set Up SSH Key Authentication#

SSH with passwords can be broken by one brute-force attack: a bot tries many passwords until one works. Key authentication removes that risk fully. It is also faster to use every day.

Generate a Key Pair on Your Local Machine#

A key pair has two parts. The private key stays on your machine. The public key goes on the server.

Run this on your local machine, not the server:

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

ed25519 is the modern default. Its keys are smaller and faster, and it is as secure as RSA 4096. Set a strong passphrase.

Copy the Public Key to the Server#

bash
ssh-copy-id -i ~/.ssh/id_ed25519.pub deploy@your-server-ip

If ssh-copy-id is not on your local machine:

bash
cat ~/.ssh/id_ed25519.pub | ssh deploy@your-server-ip \
  "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

Verify Key Login Works#

Open a new terminal and check that key login works before you touch anything else:

bash
ssh -i ~/.ssh/id_ed25519 deploy@your-server-ip

Do not go to the next step until this works.


Step 4: Disable Root SSH Login and Password Auth#

Key login works, so now lock down the SSH daemon (sshd, the SSH server program).

EC2 Debian 13 already comes with PasswordAuthentication no written in the config. The other directives (settings) are commented out, or they use built-in defaults that are not strict enough. Write all of them in the config yourself. Then your intent is clear, and it stays after package updates.

bash
sudo nano /etc/ssh/sshd_config

Find and set (or add) these four directives:

text
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
LogLevel VERBOSE
Directive EC2 Debian 13 Default Why set it yourself
PermitRootLogin no prohibit-password — root login allowed with a key no removes root SSH access fully, no matter what keys exist
PasswordAuthentication no Already no on EC2 Keeps it locked even if a package update or dpkg-reconfigure resets defaults
PubkeyAuthentication yes yes by default Documents itself — makes the intent clear to anyone who reads the config
LogLevel VERBOSE INFO Logs the key fingerprint used on each login — you need it to audit who logged in and when

Restart the SSH service:

bash
sudo systemctl restart sshd

Step 5: Change the SSH Port#

Port 22 is the default, and every bot scanner knows it. A new port does not stop an attack that is aimed at you, but it removes almost all automated noise.

When NOT to Change the SSH Port#

A new port is a good default. But skip this step if one of these cases applies:

Scenario Why to Keep Port 22
Behind a VPN The VPN is the outer wall — a hidden port adds nothing when nobody can reach the server without the VPN
AWS SSM / GCP OS Login No open SSH port needed at all — Session Manager (AWS) or OS Login (GCP) gives shell access without it
Kubernetes nodes Cluster tooling often assumes port 22 — changing it can break node provisioning and management
Bastion / jump host setup The bastion controls who gets in; internal servers behind it can stay on 22
Strict corporate Security Groups Some orgs lock outbound rules to port 22 only — a non-standard port may be blocked at the network level

Edit sshd_config#

bash
sudo nano /etc/ssh/sshd_config

Change or add the Port directive:

text
Port 2222

Restart sshd:

bash
sudo systemctl restart sshd

Connect Using the New Port#

bash
ssh -p 2222 deploy@your-server-ip

When it works, update ~/.ssh/config on your local machine, so you do not have to type the port every time:

text
Host myserver
    HostName your-server-ip
    User deploy
    Port 2222
    IdentityFile ~/.ssh/id_ed25519

Then: ssh myserver.


Step 6: Configure UFW Firewall#

A default-deny firewall blocks everything first. Only traffic that you allow by name can reach the server. Make it a habit to write down which ports you open and why. It makes you understand exactly what is running. It also stops the list of open ports from growing over time. The attack surface (everything an attacker can reach) stays as small as it can be.

bash
sudo apt install -y ufw

Set the baseline policy:

bash
sudo ufw default deny incoming
sudo ufw default allow outgoing

Allow your SSH port:

bash
sudo ufw allow 2222/tcp

Enable:

bash
sudo ufw enable

Verify:

bash
sudo ufw status verbose

Expected output:

text
Status: active
Default: deny (incoming), allow (outgoing)

To                         Action      From
--                         ------      ----
2222/tcp                   ALLOW IN    Anywhere
2222/tcp (v6)              ALLOW IN    Anywhere (v6)

Common Rules Reference#

Action Command
Allow HTTP sudo ufw allow 80/tcp
Allow HTTPS sudo ufw allow 443/tcp
Allow from specific IP only sudo ufw allow from 10.0.0.5 to any port 2222
Delete a rule sudo ufw delete allow 80/tcp

Only open what you really use. Every open port adds to the attack surface.


Step 7: Install Fail2ban#

UFW controls which ports can be reached. Fail2ban watches the authentication logs and bans IPs that keep probing those ports.

bash
sudo apt install -y fail2ban

Create a minimal jail.local. Do not copy all of jail.conf. It brings in jails for services that don’t exist on your system, and it will crash fail2ban on startup:

bash
sudo nano /etc/fail2ban/jail.local
ini
[DEFAULT]
ignoreip = 127.0.0.1/8 ::1 <your-ip>

[sshd]
enabled      = true
port         = 2222
backend      = systemd
journalmatch = _SYSTEMD_UNIT=ssh.service
bantime      = 1h
findtime     = 10m
maxretry     = 5

Start and enable:

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

What You Have Now#

Step What It Does
System updates + unattended-upgrades Patches known CVEs automatically
Non-root sudo user No direct root exposure over SSH
SSH key authentication Removes password brute force
Root login disabled, password auth off Forces key-only access
Custom SSH port Removes automated port-22 scanner noise
UFW default-deny Only traffic you allowed gets through
Fail2ban on SSH Bans IPs that actively probe your SSH port

This is a baseline (a minimum level), not a complete hardening spec. The next layers: auditing with Lynis, AppArmor profile tuning, centralized log forwarding, and rootkit detection with rkhunter.

Practical Walkthrough: AWS EC2 + Debian 13#

This section applies every step above on a real AWS EC2 instance that runs Debian 13.

Connect to the Instance#

bash
chmod 400 <path-to-private-key>
ssh -i <path-to-private-key> admin@<ec2-public-ip>

On the first connection, SSH asks you to verify the host fingerprint. Type yes:

text
The authenticity of host '<ec2-public-ip>' can't be established.
ED25519 key fingerprint is SHA256:rMAZNXzm4.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '<ec2-public-ip>' (ED25519) to the list of known hosts.

Fix Locale Warnings (EC2-Specific)#

A fresh Debian 13 EC2 shows many locale warnings when you log in. Run the reconfiguration tool and select en_US.UTF-8 UTF-8 when it asks:

bash
sudo dpkg-reconfigure locales

The perl: warning: Setting locale failed lines at the start are normal. They appear because the locale isn’t configured yet when the tool runs. The last lines show that it worked:

text
Generating locales (this might take a while)...
  en_US.UTF-8... done
Generation complete.

Exit and reconnect. The warnings are gone.

Step 1: Update the System#

bash
sudo apt update && sudo apt full-upgrade -y
sudo reboot now

After the reboot, reconnect and check that everything is up to date:

bash
sudo apt update
text
All packages are up to date.

Then enable automatic security updates. Answer Yes when it asks:

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

Step 2: Non-Root Sudo User#

AWS Debian 13 images come with a non-root admin user already configured. This step is done. You do not need to do anything.

Step 3: SSH Key Authentication#

The key pair was assigned at EC2 launch and is already in ~/.ssh/authorized_keys for the admin user. This step is done. Verify that the key is there before you continue:

bash
cat ~/.ssh/authorized_keys

Steps 4 & 5: Lock Down SSH and Change the Port#

bash
sudo nano /etc/ssh/sshd_config

Set these four directives:

text
Port 2233
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
LogLevel VERBOSE

Restart the SSH service:

bash
sudo systemctl restart sshd

Open a new terminal and verify that the new port works before you close the current session:

bash
ssh -i "key.pem" admin@<ec2-public-ip> -p 2233

Step 6: Configure UFW Firewall#

Follow the UFW setup commands from the guide above, but use port 2233 in place of 2222. When it is configured:

bash
sudo ufw status verbose
text
Status: active
Default: deny (incoming), allow (outgoing), disabled (routed)

To                         Action      From
--                         ------      ----
2233/tcp                   ALLOW IN    Anywhere
2233/tcp (v6)              ALLOW IN    Anywhere (v6)

Step 7: Install Fail2ban#

Follow the Fail2ban setup commands from the guide above. Set port = 2233 in jail.local, so it matches the SSH port of this walkthrough. Then verify that the jail is active:

bash
sudo fail2ban-client status sshd

Wrapping Up#

The EC2 instance is now hardened to the same baseline as in the guide:

What Was Applied State
System fully patched, auto-security-updates on Done
Non-root admin user (AWS default) Already present
SSH key auth only — key injected at launch Already present
Root SSH login disabled, password auth off Configured
SSH moved off port 22 → 2233 Configured
UFW default-deny, port 2233 open Configured
Fail2ban watching SSH port 2233 Running

This is a solid baseline for a server that is open to the internet, but it is not a complete hardening spec. The next steps:

  • Lynis — full system audit (sudo lynis audit system) with scored recommendations
  • AppArmor — strict access control profiles (MAC) for high-risk services
  • rkhunter — rootkit and integrity scanning
  • Centralized log forwarding — send /var/log/auth.log and fail2ban logs to a SIEM or log aggregator, so you can see them without an SSH login
  • Fail2ban production config — Fail2ban on Debian 13: The Right Config for OpenSSH 9.x