Attackers scan the entire IPv4 address space in under an hour now. If your server is internet-facing, it's being probed constantly—SSH brute force, exploit kits hunting outdated services, bots checking for default credentials. Most breaches I investigate start with something preventable: an open port that didn't need to be, a service running as root, a missed kernel patch.
Server security hardening is the practice of reducing your attack surface by disabling unnecessary services, enforcing strict access controls, and patching aggressively. The goal is simple: make it hard enough that automated attacks move on and opportunistic attackers hit a wall. Here are the nine steps production teams are prioritizing right now.
1. Lock Down SSH Access Immediately
SSH is the front door. Every single day, bots hammer port 22 with credential stuffing attacks.
Disable root login and password authentication entirely. Use SSH keys only. Edit /etc/ssh/sshd_config:
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
Port 2222 # optional: non-standard port reduces log noise
Restart the service:
systemctl restart sshd
Change the port if you want (it won't stop a determined attacker, but it cuts down on automated scan traffic). More important: restrict access by IP. If your team connects from known office IPs or a VPN, whitelist them in your firewall and block everything else.
For servers behind a bastion host, disable direct SSH entirely and require the jump box. I've seen environments where a single exposed SSH port with password auth led to total compromise in under 72 hours.
2. Configure a Host Firewall and Default-Deny Policy
Every Linux server should run a host-based firewall with a default-deny posture: block everything inbound except what you explicitly allow.
On most distros, that's firewalld or ufw. Here's a basic ufw setup:
ufw default deny incoming
ufw default allow outgoing
ufw allow 2222/tcp # SSH on custom port
ufw allow 80/tcp
ufw allow 443/tcp
ufw enable
Check what's listening:
ss -tulnp
For each service you see, ask yourself: does this need to be reachable from the internet? Database ports (3306, 5432), Redis (6379), and memcached (11211) should never be exposed publicly. Bind them to localhost or a private VLAN.
If you're running Docker, be aware that it manipulates iptables directly and can punch holes through your firewall rules. Always verify with iptables -L -n after deploying containers.
3. Disable and Remove Unused Services
Default OS installs ship with services you'll never use. Each one is a potential entry point.
List what's enabled:
systemctl list-unit-files --type=service --state=enabled
Common candidates for removal:
- rpcbind (unless you're running NFS)
- avahi-daemon (Zeroconf/Bonjour)
- cups (print server on a headless box?)
- Old mail transfer agents if you're using a transactional email service
Disable and mask them:
systemctl disable --now avahi-daemon
systemctl mask avahi-daemon
Masking prevents accidental re-enablement. Fewer services mean fewer things to patch and fewer vectors for privilege escalation.
4. Enforce Automatic Security Updates
Manual patching doesn't scale and humans forget. Automate it.
On Ubuntu/Debian, install unattended-upgrades:
apt install unattended-upgrades
dpkg-reconfigure --priority=low unattended-upgrades
Configure /etc/apt/apt.conf.d/50unattended-upgrades to auto-install security updates and optionally reboot if needed:
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "03:00";
On RHEL/CentOS/AlmaLinux, use dnf-automatic:
dnf install dnf-automatic
systemctl enable --now dnf-automatic.timer
Edit /etc/dnf/automatic.conf and set apply_updates = yes.
Kernel updates require a reboot. Schedule maintenance windows or use live patching services like KernelCare or Ubuntu Livepatch if uptime requirements are strict. The cost of a zero-day exploit is higher than a three-minute reboot.
5. Harden Kernel Parameters with sysctl
The Linux kernel exposes hundreds of tunables that affect network behavior and security. A few critical ones:
# Disable IP forwarding unless you're routing
net.ipv4.ip_forward = 0
# Ignore ICMP redirects
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
# Ignore source-routed packets
net.ipv4.conf.all.accept_source_route = 0
# Enable SYN cookies (DoS mitigation)
net.ipv4.tcp_syncookies = 1
# Log martian packets
net.ipv4.conf.all.log_martians = 1
# Disable ICMP echo (optional, breaks some diagnostics)
# net.ipv4.icmp_echo_ignore_all = 1
Add these to /etc/sysctl.d/99-hardening.conf and apply:
sysctl -p /etc/sysctl.d/99-hardening.conf
These aren't magic bullets, but they close off well-known kernel-level attack techniques. In environments I've worked with, enabling SYN cookies alone prevented several small-scale DDoS attempts from taking services offline.
6. Implement Fail2Ban or Equivalent Intrusion Prevention
Fail2Ban monitors log files and bans IPs that exhibit malicious behavior—repeated failed SSH logins, 404 scans, authentication failures in web apps.
Install it:
apt install fail2ban # Debian/Ubuntu
dnf install fail2ban # RHEL-based
Default config is in /etc/fail2ban/jail.conf. Don't edit that file directly; override in /etc/fail2ban/jail.local:
[sshd]
enabled = true
port = 2222
maxretry = 3
bantime = 3600
findtime = 600
This bans any IP with three failed login attempts in ten minutes for one hour. Check active bans:
fail2ban-client status sshd
Add jails for web servers (Apache, Nginx), mail services, and any app that logs authentication attempts. Adjust bantime and maxretry based on your threat model. I typically set longer ban times for SSH and shorter for HTTP to avoid false positives from users mistyping passwords.
7. Enforce Mandatory Access Control with SELinux or AppArmor
Discretionary access controls (file permissions) aren't enough. If an attacker compromises a service running as a low-privilege user, they can still move laterally and escalate.
Mandatory Access Control (MAC) systems like SELinux and AppArmor add an extra layer: even if a process is compromised, it can only access what its policy allows.
SELinux is default on RHEL, CentOS, Fedora, and AlmaLinux. Check its status:
getenforce
If it says Permissive or Disabled, enable it. Edit /etc/selinux/config:
SELINUX=enforcing
Reboot. Yes, SELinux can be a pain during initial setup—services fail because policies are too strict. Don't disable it. Instead, check audit logs:
ausearch -m avc -ts recent
Use audit2allow to generate policy modules for legitimate denials. On Ubuntu, AppArmor is the default and typically requires less tuning.
In production environments, MAC has stopped lateral movement cold during incidents where web application vulnerabilities were exploited. The attacker got a shell but couldn't read database credentials or SSH keys because the policy blocked it.
8. Restrict User Privileges and Disable Unnecessary Accounts
Run services under dedicated, unprivileged user accounts. Never run web servers, databases, or app servers as root.
Check which users have login shells:
grep -v '/nologin\|/false' /etc/passwd
For service accounts (mysql, www-data, nginx), set their shell to /usr/sbin/nologin or /bin/false if it isn't already. Lock any default accounts you don't use:
usermod -L -s /usr/sbin/nologin games
Use sudo for administrative tasks instead of logging in as root. Configure /etc/sudoers (via visudo) to require passwords and log all commands:
Defaults logfile="/var/log/sudo.log"
For teams, consider centralized authentication (LDAP, Active Directory, or a bastion with short-lived certificates). The goal is traceability: if something breaks or an incident occurs, you need to know who did what.
So What About Application-Layer Security?
OS hardening won't save you if your application has SQL injection or command injection flaws. But it buys you time and limits blast radius.
Keep application dependencies updated. For PHP, Node.js, Python, or Ruby apps, pin versions in production and automate vulnerability scanning with tools like Dependabot, Snyk, or Trivy. Run web application firewalls (ModSecurity, Cloudflare WAF) to filter out obvious exploit attempts.
Don't rely on the WAF alone. It's a speed bump, not a fortress.
9. Audit and Monitor Continuously
Hardening is not a one-time task. Configurations drift, new vulnerabilities emerge, and attackers evolve.
Set up centralized logging. Ship logs to a remote syslog server or a hosted service (Papertrail, Logtail, Elastic Stack). If an attacker compromises the box, local logs can be wiped.
Enable auditd to track file access, system calls, and command execution:
apt install auditd
systemctl enable --now auditd
Add rules to watch sensitive files:
auditctl -w /etc/passwd -p wa -k passwd_changes
auditctl -w /etc/shadow -p wa -k shadow_changes
auditctl -w /var/log/auth.log -p wa -k auth_log
Schedule regular scans with tools like Lynis:
lynis audit system
It checks file permissions, running services, kernel parameters, and more. Review its output and prioritize high-severity findings.
Finally, practice incident response. Have a runbook: what do you do if you see a spike in failed SSH attempts? What if a web shell is uploaded? Document the steps before an incident happens.
What to Do Right Now
You don't need to implement all nine steps in one sitting. Start with SSH lockdown and firewall rules—those stop the noisiest attacks immediately. Automate patching next; that's your insurance against known exploits.
Then layer on Fail2Ban, kernel hardening, and MAC. The combination makes opportunistic attacks impractical and forces skilled attackers to spend significant time and resources, which most won't bother with when easier targets exist.
Hardening is about raising the cost of compromise. Perfect security doesn't exist, but a well-hardened server shifts the odds in your favor.
What if I'm already running a production server—can I harden it without downtime?
Most steps can be done live. SSH changes, firewall rules, and service disabling don't require reboots. Kernel parameter changes via sysctl take effect immediately. Enabling SELinux in enforcing mode and kernel updates do require a reboot—schedule a maintenance window for those.
Does changing the SSH port actually help?
It reduces log noise from automated scans but provides no real security against targeted attacks. Attackers run full port scans anyway. Use it if you want cleaner logs, but don't rely on it as a security control. Key-based auth and IP whitelisting matter far more.
Should I disable IPv6 if I'm not using it?
Yes, unless you need it. Many servers have IPv6 enabled by default but no firewall rules configured for it, creating an unmonitored attack surface. Add ipv6.disable=1 to your kernel boot parameters or configure ip6tables rules if you keep it enabled.
How often should I run security audits?
Run automated scans weekly with tools like Lynis or OpenSCAP. Manual reviews quarterly or after any significant infrastructure change. Also audit after any suspected incident—even if it turns out to be a false alarm, the process will reveal gaps.
Lock It Down Before They Do
Every misconfigured server on the internet is being scanned right now. Attackers have the tooling and the time. You have a finite security budget and a hundred other priorities.
The nine steps here aren't theoretical best practices—they're the actual controls stopping breaches in production environments every day. SSH hardening, firewalls, patching, and MAC aren't exciting, but they're effective. Boring security wins.
Start with the quick wins (SSH, firewall), automate the tedious parts (updates, log monitoring), and build the habit of auditing regularly. The goal isn't perfection. It's making your server harder to compromise than the one next door.
