Skip to main content

Hardening Linux Servers for Production

Apply a production hardening baseline to Linux servers: SSH, users, firewall, sysctl, fail2ban and lynis scans to raise your audit score.

30 Terms

Overview and What You Will Learn

Linux server hardening is the process of removing default weaknesses from a fresh install so that only the access and services you intend are available. A default image typically allows password logins, runs packages you never use and applies kernel settings that favour compatibility over security.

By the end of this lab you will be able to:

  • Lock down SSH so only named users with keys can log in
  • Audit accounts and scope sudo rights to the commands each user needs
  • Remove unneeded packages and bind internal services to localhost
  • Turn on a host firewall without locking yourself out
  • Apply kernel hardening through sysctl, and know which settings break container hosts
  • Deploy fail2ban and measure your baseline with a lynis audit

Why This Matters in Production

A server with default settings is both a security risk and an audit finding. Teams that run regulated platforms, such as a broker like Zerodha operating under SEBI rules, are expected to show that servers meet a documented baseline. At global scale, companies like Cloudflare and Stripe treat hardening as automation: the baseline is applied by configuration management on every new host, not by hand. The checklist in this lab is that baseline for a single Linux server.

Core Principles

Defence in depth means no single control has to be perfect. Each layer below either prevents an attack or detects and measures one, so a mistake in one layer is caught by another.

flowchart TD subgraph P[Prevent] A[Network firewall
and security groups] --> B[SSH keys only
no root login] B --> C[Least privilege
users and sudo] C --> D[Minimal packages
and sysctl] end subgraph M[Detect and Measure] E[(fail2ban
and auth logs)] --> F[lynis audit
and score] end D -->|Logs| E classDef prevent fill:#326CE5,color:#FFFFFF classDef detect fill:#10B981,color:#FFFFFF class A,B,C,D prevent class E,F detect

Before you change anything, keep an existing root or sudo session open in a second terminal. Most hardening mistakes lock the operator out, and an open session is the cheapest recovery path.

Detailed Step-by-Step Practical Lab

How to Harden SSH on a Linux Server

Hardening SSH means disabling root login and password authentication, limiting which users may connect, and shortening the window for failed attempts. It is the highest-impact step because SSH is the main way in, and key-only authentication removes password guessing as an attack path.

Modern Debian, Ubuntu and RHEL based systems read drop-in files from /etc/ssh/sshd_config.d/. For each setting sshd uses the first value it reads, and files are read in alphabetical order. Cloud images often ship 50-cloud-init.conf with PasswordAuthentication yes, so name your file 00-hardening.conf to make sure it wins.

Bash
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.original
# Confirm the main file includes the drop-in directory
grep -n '^Include' /etc/ssh/sshd_config
# Write the hardening drop-in (00- prefix so it is read first)
sudo tee /etc/ssh/sshd_config.d/00-hardening.conf > /dev/null << 'EOF'
# Disable root login completely
PermitRootLogin no
# Keys only: no passwords, no keyboard-interactive prompts
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitEmptyPasswords no
AuthenticationMethods publickey
# Keep PAM on: it handles account locking and session setup
UsePAM yes
# Only these accounts may log in
AllowUsers rahul deploy jenkins monitoring-agent
# Limit guessing and half-open connections
MaxAuthTries 3
MaxSessions 10
LoginGraceTime 30
# Drop dead or idle sessions after about 10 minutes
ClientAliveInterval 300
ClientAliveCountMax 2
# Servers do not need these by default
X11Forwarding no
AllowAgentForwarding no
AllowTcpForwarding no
# Verbose logging records key fingerprints for audits
LogLevel VERBOSE
EOF
# Validate syntax (no output means valid)
sudo sshd -t
# Print the settings sshd will actually use
sudo sshd -T | grep -E 'permitrootlogin|passwordauthentication|allowusers|maxauthtries'
# Reload: the unit is "ssh" on Debian and Ubuntu, "sshd" on RHEL and Amazon Linux
sudo systemctl reload ssh || sudo systemctl reload sshd

Test from a second terminal before closing your first session. Also confirm that password login is really refused:

Bash
# Key login should work
ssh rahul@10.0.1.50
# Password login should fail with "Permission denied (publickey)"
ssh -o PubkeyAuthentication=no -o PreferredAuthentications=password rahul@10.0.1.50
Security

Keep UsePAM yes unless you are certain you do not need PAM. Turning it off can break account locking, session limits and PAM-based two-factor authentication. Key-only login does not require disabling PAM.

Common Mistake

Applying PasswordAuthentication no before key login is proven. If your key is not in authorized_keys, you need console access to recover. Test the key in a second terminal first.

Tip

If you change algorithm lists such as KexAlgorithms or Ciphers, keep the OpenSSH defaults unless a compliance rule forces a change. Defaults are maintained for you, and an over-tight custom list can lock out older automation clients.

How to Audit Linux Users and Sudo Access

Account hygiene means every login has a named owner, no account has an empty password, and sudo rights are limited to the commands that person or tool needs. Review it whenever someone joins or leaves the team.

Bash
# Accounts that can log in (real shell)
grep -v -E '/nologin$|/false$' /etc/passwd | cut -d: -f1,7
# Accounts with an EMPTY password field (critical finding)
# A "!" or "*" means locked or no password login, which is fine
sudo awk -F: '($2 == "") {print $1}' /etc/shadow
# Who has sudo, and which rules are passwordless
sudo grep -rE 'NOPASSWD|ALL' /etc/sudoers /etc/sudoers.d/ 2>/dev/null
getent group sudo
# Scope a CI runner to exactly what it needs (always edit with visudo)
sudo visudo -f /etc/sudoers.d/jenkins
# jenkins ALL=(root) NOPASSWD: /usr/bin/systemctl restart payment-api, /usr/bin/systemctl reload nginx
# Offboard an account: lock it, remove its shell and expire it
sudo passwd --lock old-employee
sudo usermod --shell /usr/sbin/nologin --expiredate 1 old-employee
# Review recent logins
last -n 20
lastlog | grep -v 'Never'

For accounts that still use passwords, set an expiry policy. Service accounts and key-only users usually should not expire.

Bash
sudo chage -l rahul
sudo chage -M 90 -W 14 rahul
How to Remove Unnecessary Packages and Services

Every installed package and every open port is attack surface. List what is listening, decide whether each service needs to be reachable, and remove or localhost-bind the rest.

Bash
# Everything that is listening, and who owns it
sudo ss -tulpn
# Running services
systemctl list-units --type=service --state=running
# Remove legacy remote-access tools (Debian and Ubuntu)
sudo apt remove --purge telnet rsh-client ftp
sudo apt autoremove
# Disable services servers rarely need
sudo systemctl disable --now avahi-daemon cups
# Bind internal-only services to localhost, for example PostgreSQL
grep -R "listen_addresses" /etc/postgresql/*/main/postgresql.conf
# listen_addresses = 'localhost'

Only purge an MTA such as postfix if nothing relies on it. Some servers use it to send cron and alert mail.

Patching is part of hardening, so turn on automatic security updates:

Bash
# Debian and Ubuntu
sudo apt install unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades
# RHEL family
sudo dnf install dnf-automatic
sudo systemctl enable --now dnf-automatic.timer
How to Configure a Host Firewall with ufw

A host firewall blocks everything not explicitly allowed, even if a cloud security group is misconfigured. Always allow SSH before you enable the firewall, or you will cut your own session off.

Bash
sudo apt install ufw
# Default posture: deny inbound, allow outbound
sudo ufw default deny incoming
sudo ufw default allow outgoing
# Allow SSH only from the office and bastion range, and web traffic from anywhere
sudo ufw allow from 10.0.0.0/16 to any port 22 proto tcp
sudo ufw allow 443/tcp
# Enable, then review
sudo ufw enable
sudo ufw status verbose

On RHEL based systems the equivalent tool is firewalld (firewall-cmd).

How to Apply Kernel Hardening with sysctl

sysctl settings change kernel behaviour at runtime. The set below blocks common network tricks and limits information leaks. Put them in a drop-in file so they survive reboots.

Bash
sudo tee /etc/sysctl.d/99-hardening.conf > /dev/null << 'EOF'
# Network: SYN flood protection and reverse path filtering
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
# Network: ignore redirects and source routing
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
# Network: ignore broadcast pings and log spoofed packets
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.conf.all.log_martians = 1
# Kernel: hide logs and pointers, disable SysRq, restrict ptrace
kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
kernel.sysrq = 0
kernel.yama.ptrace_scope = 1
# Memory and files: ASLR, no core dumps from setuid programs, link protection
kernel.randomize_va_space = 2
fs.suid_dumpable = 0
fs.protected_hardlinks = 1
fs.protected_symlinks = 1
EOF
# Load every sysctl file, then verify
sudo sysctl --system
sysctl net.ipv4.tcp_syncookies
Remember

Do not set net.ipv4.ip_forward = 0 on Docker or Kubernetes nodes, VPN servers or routers. Containers rely on IP forwarding, and the setting is deliberately left out of the file above. Only add it on hosts that never route traffic.

How to Install and Configure fail2ban

fail2ban reads authentication logs and temporarily bans IP addresses that fail repeatedly. With password login disabled it will not stop an attacker who has no key, but it cuts log noise and connection load, and it protects services that still use passwords such as web admin pages.

Bash
sudo apt install fail2ban
# Never edit jail.conf: put overrides in jail.local
sudo tee /etc/fail2ban/jail.local > /dev/null << 'EOF'
[DEFAULT]
# Never ban the bastion, office or monitoring ranges
ignoreip = 127.0.0.1/8 10.0.0.0/16
# Ban for 1 hour after 5 failures within 10 minutes
bantime = 3600
findtime = 600
maxretry = 5
# Use nftables-multiport on nftables-based systems
banaction = iptables-multiport
# Read the systemd journal (no log file needed on current distros)
backend = systemd
[sshd]
enabled = true
maxretry = 3
# Stricter and longer for SSH: 24 hours
bantime = 86400
[nginx-http-auth]
enabled = true
EOF
sudo systemctl enable --now fail2ban
# Overall and per-jail status
sudo fail2ban-client status
sudo fail2ban-client status sshd
# Remove a ban (for example a teammate who mistyped)
sudo fail2ban-client set sshd unbanip 192.0.2.45
How to Run a Lynis Security Audit

lynis is an open-source auditing tool that scans the server and prints a hardening index plus a prioritised list of warnings and suggestions. Run it before a server enters production and again after every major change.

Bash
# The distribution package can be old; the CISOfy repository or GitHub has the latest
sudo apt install lynis
# Full audit (add --quick to skip pauses)
sudo lynis audit system
# Warnings and suggestions are saved in the report file
sudo grep -E '^(warning|suggestion)\[\]=' /var/log/lynis-report.dat | head -20
# Explain one finding using the test ID printed in the output
sudo lynis show details TEST-ID

The end of the run prints a summary such as Hardening index : 67. Use the number as a trend line, not a certificate: record it, fix the warnings, rerun, and watch it rise. Many teams set a target near 80 for sensitive servers, but a high score does not replace reading the individual findings.

Production Best Practices & Common Pitfalls

  • Automate the baseline. Put these settings in Ansible, cloud-init or an image pipeline so every host starts hardened, rather than hardening by hand.
  • Rely on drop-ins. Files in sshd_config.d, sysctl.d and sudoers.d survive package upgrades and are easy to review in version control.
  • Verify effective values. Use sshd -T, sysctl <key> and fail2ban-client status rather than assuming the file you wrote is what runs.
  • Patch continuously. Enable unattended security updates, and schedule a quarterly lynis scan and sudo review.
  • Layer controls. A firewall, key-only SSH and least-privilege sudo each cover the failure of the others.
  • Keep a recovery path. Use a second session or cloud console access whenever you change SSH, firewall or PAM settings.
Area Wrong Correct
SSH Root login on, passwords allowed PermitRootLogin no, key-only, AllowUsers list
SSH drop-in hardening.conf after 50-cloud-init.conf 00-hardening.conf, verified with sshd -T
Users Shared accounts, NOPASSWD: ALL Named accounts, scoped sudo commands
Kernel Defaults, or blanket ip_forward = 0 Hardening file that fits the host role
Detection No view of failed logins fail2ban with ignoreip set, plus log review

Quick Reference & Troubleshooting Commands

Task Command
Validate sshd config sudo sshd -t
Show effective sshd settings sudo sshd -T
List sudo rules sudo grep -r NOPASSWD /etc/sudoers.d/
Listening services sudo ss -tulpn
Apply all sysctl files sudo sysctl --system
Firewall status sudo ufw status verbose
fail2ban jail status sudo fail2ban-client status sshd
Unban an IP sudo fail2ban-client set sshd unbanip IP
Run lynis audit sudo lynis audit system
Recent SSH failures journalctl -u ssh -g 'Failed' --no-pager -n 20

Resources

Explore More in Linux Networking and Security

All 4 Topics

Frequently Asked Questions

Is Hardening Linux Servers for Production free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Hardening Linux Servers for Production topic cover?

Apply a production hardening baseline to Linux servers: SSH, users, firewall, sysctl, fail2ban and lynis scans to raise your audit score.

Found a mistake, an outdated step or a broken link?