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.
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.
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.original # Confirm the main file includes the drop-in directorygrep -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 completelyPermitRootLogin no # Keys only: no passwords, no keyboard-interactive promptsPasswordAuthentication noKbdInteractiveAuthentication noPermitEmptyPasswords noAuthenticationMethods publickey # Keep PAM on: it handles account locking and session setupUsePAM yes # Only these accounts may log inAllowUsers rahul deploy jenkins monitoring-agent # Limit guessing and half-open connectionsMaxAuthTries 3MaxSessions 10LoginGraceTime 30 # Drop dead or idle sessions after about 10 minutesClientAliveInterval 300ClientAliveCountMax 2 # Servers do not need these by defaultX11Forwarding noAllowAgentForwarding noAllowTcpForwarding no # Verbose logging records key fingerprints for auditsLogLevel VERBOSEEOF # Validate syntax (no output means valid)sudo sshd -t # Print the settings sshd will actually usesudo sshd -T | grep -E 'permitrootlogin|passwordauthentication|allowusers|maxauthtries' # Reload: the unit is "ssh" on Debian and Ubuntu, "sshd" on RHEL and Amazon Linuxsudo systemctl reload ssh || sudo systemctl reload sshdTest from a second terminal before closing your first session. Also confirm that password login is really refused:
# Key login should workssh rahul@10.0.1.50 # Password login should fail with "Permission denied (publickey)"ssh -o PubkeyAuthentication=no -o PreferredAuthentications=password rahul@10.0.1.50SecurityKeep
UsePAM yesunless 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 MistakeApplying
PasswordAuthentication nobefore key login is proven. If your key is not inauthorized_keys, you need console access to recover. Test the key in a second terminal first.
TipIf you change algorithm lists such as
KexAlgorithmsorCiphers, 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.
# 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 finesudo awk -F: '($2 == "") {print $1}' /etc/shadow # Who has sudo, and which rules are passwordlesssudo grep -rE 'NOPASSWD|ALL' /etc/sudoers /etc/sudoers.d/ 2>/dev/nullgetent 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 itsudo passwd --lock old-employeesudo usermod --shell /usr/sbin/nologin --expiredate 1 old-employee # Review recent loginslast -n 20lastlog | grep -v 'Never'For accounts that still use passwords, set an expiry policy. Service accounts and key-only users usually should not expire.
sudo chage -l rahulsudo chage -M 90 -W 14 rahulHow 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.
# Everything that is listening, and who owns itsudo ss -tulpn # Running servicessystemctl list-units --type=service --state=running # Remove legacy remote-access tools (Debian and Ubuntu)sudo apt remove --purge telnet rsh-client ftpsudo apt autoremove # Disable services servers rarely needsudo systemctl disable --now avahi-daemon cups # Bind internal-only services to localhost, for example PostgreSQLgrep -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:
# Debian and Ubuntusudo apt install unattended-upgradessudo dpkg-reconfigure -plow unattended-upgrades # RHEL familysudo dnf install dnf-automaticsudo systemctl enable --now dnf-automatic.timerHow 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.
sudo apt install ufw # Default posture: deny inbound, allow outboundsudo ufw default deny incomingsudo ufw default allow outgoing # Allow SSH only from the office and bastion range, and web traffic from anywheresudo ufw allow from 10.0.0.0/16 to any port 22 proto tcpsudo ufw allow 443/tcp # Enable, then reviewsudo ufw enablesudo ufw status verboseOn 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.
sudo tee /etc/sysctl.d/99-hardening.conf > /dev/null << 'EOF'# Network: SYN flood protection and reverse path filteringnet.ipv4.tcp_syncookies = 1net.ipv4.conf.all.rp_filter = 1net.ipv4.conf.default.rp_filter = 1 # Network: ignore redirects and source routingnet.ipv4.conf.all.accept_redirects = 0net.ipv4.conf.default.accept_redirects = 0net.ipv4.conf.all.send_redirects = 0net.ipv6.conf.all.accept_redirects = 0net.ipv4.conf.all.accept_source_route = 0 # Network: ignore broadcast pings and log spoofed packetsnet.ipv4.icmp_echo_ignore_broadcasts = 1net.ipv4.conf.all.log_martians = 1 # Kernel: hide logs and pointers, disable SysRq, restrict ptracekernel.dmesg_restrict = 1kernel.kptr_restrict = 2kernel.sysrq = 0kernel.yama.ptrace_scope = 1 # Memory and files: ASLR, no core dumps from setuid programs, link protectionkernel.randomize_va_space = 2fs.suid_dumpable = 0fs.protected_hardlinks = 1fs.protected_symlinks = 1EOF # Load every sysctl file, then verifysudo sysctl --systemsysctl net.ipv4.tcp_syncookiesRememberDo not set
net.ipv4.ip_forward = 0on 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.
sudo apt install fail2ban # Never edit jail.conf: put overrides in jail.localsudo tee /etc/fail2ban/jail.local > /dev/null << 'EOF'[DEFAULT]# Never ban the bastion, office or monitoring rangesignoreip = 127.0.0.1/8 10.0.0.0/16# Ban for 1 hour after 5 failures within 10 minutesbantime = 3600findtime = 600maxretry = 5# Use nftables-multiport on nftables-based systemsbanaction = iptables-multiport# Read the systemd journal (no log file needed on current distros)backend = systemd [sshd]enabled = truemaxretry = 3# Stricter and longer for SSH: 24 hoursbantime = 86400 [nginx-http-auth]enabled = trueEOF sudo systemctl enable --now fail2ban # Overall and per-jail statussudo fail2ban-client statussudo fail2ban-client status sshd # Remove a ban (for example a teammate who mistyped)sudo fail2ban-client set sshd unbanip 192.0.2.45How 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.
# The distribution package can be old; the CISOfy repository or GitHub has the latestsudo apt install lynis # Full audit (add --quick to skip pauses)sudo lynis audit system # Warnings and suggestions are saved in the report filesudo grep -E '^(warning|suggestion)\[\]=' /var/log/lynis-report.dat | head -20 # Explain one finding using the test ID printed in the outputsudo lynis show details TEST-IDThe 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.dandsudoers.dsurvive package upgrades and are easy to review in version control. - Verify effective values. Use
sshd -T,sysctl <key>andfail2ban-client statusrather 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 |