← 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#
- Update the system — fix known security bugs (CVEs) before you put anything else on the server
- Create a non-root sudo user — so nobody uses root directly over SSH
- Set up SSH key authentication — replace passwords with cryptographic keys
- Disable root login and password auth — lock down the SSH daemon (the SSH server program)
- Change the SSH port — get less noise from automated scanners (+ when NOT to do it)
- Configure UFW firewall — deny all incoming traffic by default
- Install Fail2ban — auto-ban IPs that brute-force your SSH port (try many logins until one works)
- A fresh server. Root login is on, passwords are on, and SSH listens on port 22. Bots try to log in.
- Step 1: update the system and turn on automatic security updates.
- Steps 2 and 3: create a normal user with
sudo, and set up login with an SSH key. - Step 4: turn off root login and password login. A bot without your key cannot log in.
- Steps 5 and 6: move SSH to port
2222and turn on UFW. UFW blocks all traffic that you did not allow. - Step 7: Fail2ban bans an IP that keeps failing to log in.
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.
sudo apt update && sudo apt full-upgrade -y
sudo reboot nowReboot 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.
sudo apt install -y unattended-upgrades apt-listchanges
sudo dpkg-reconfigure --priority=low unattended-upgradesAnswer 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.
sudo adduser deploy
sudo usermod -aG sudo deployReplace deploy with any username you like. Verify:
groups deploy
# deploy : deploy sudoStep 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:
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#
ssh-copy-id -i ~/.ssh/id_ed25519.pub deploy@your-server-ipIf ssh-copy-id is not on your local machine:
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:
ssh -i ~/.ssh/id_ed25519 deploy@your-server-ipDo 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.
sudo nano /etc/ssh/sshd_configFind and set (or add) these four directives:
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:
sudo systemctl restart sshdStep 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#
sudo nano /etc/ssh/sshd_configChange or add the Port directive:
Port 2222Restart sshd:
sudo systemctl restart sshdConnect Using the New Port#
ssh -p 2222 deploy@your-server-ipWhen it works, update ~/.ssh/config on your local machine, so you do not have to type the port every time:
Host myserver
HostName your-server-ip
User deploy
Port 2222
IdentityFile ~/.ssh/id_ed25519Then: 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.
sudo apt install -y ufwSet the baseline policy:
sudo ufw default deny incoming
sudo ufw default allow outgoingAllow your SSH port:
sudo ufw allow 2222/tcpEnable:
sudo ufw enableVerify:
sudo ufw status verboseExpected output:
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.
sudo apt install -y fail2banCreate 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:
sudo nano /etc/fail2ban/jail.local[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 = 5Start and enable:
sudo systemctl enable --now fail2ban
sudo fail2ban-client status sshdWhat 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#
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:
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:
sudo dpkg-reconfigure localesThe 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:
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#
sudo apt update && sudo apt full-upgrade -y
sudo reboot nowAfter the reboot, reconnect and check that everything is up to date:
sudo apt updateAll packages are up to date.Then enable automatic security updates. Answer Yes when it asks:
sudo apt install -y unattended-upgrades apt-listchanges
sudo dpkg-reconfigure --priority=low unattended-upgradesStep 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:
cat ~/.ssh/authorized_keysSteps 4 & 5: Lock Down SSH and Change the Port#
sudo nano /etc/ssh/sshd_configSet these four directives:
Port 2233
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
LogLevel VERBOSERestart the SSH service:
sudo systemctl restart sshdOpen a new terminal and verify that the new port works before you close the current session:
ssh -i "key.pem" admin@<ec2-public-ip> -p 2233Step 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:
sudo ufw status verboseStatus: 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:
sudo fail2ban-client status sshdWrapping 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.logand 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