Operations 20 min read

8 Production‑Ready Linux Hardening Shell Scripts Every Sysadmin Should Use

The article walks through eight production‑grade shell scripts that secure Linux servers—from account policies and SSH hardening to firewalls, ClamAV, fail2ban, AIDE, SELinux and kernel sysctl tweaks—providing concrete commands, configuration examples and a one‑click hardening script.

AI Agent Super App
AI Agent Super App
AI Agent Super App
8 Production‑Ready Linux Hardening Shell Scripts Every Sysadmin Should Use

After a 2024 incident where a test server was compromised for a month due to a weak SSH password ("123456"), an open firewall and a replaced root binary, the author shows that installing fail2ban or AIDE could have stopped the attack within the first week.

1. Account and Password Policy

Linux does not enforce password complexity by default. The guide edits /etc/security/pwquality.conf to require a minimum length of 12 characters, at least one digit, one lowercase, one uppercase, one special character, remembers the last five passwords, limits repeated characters to three, and forces a minimum of four differing characters between old and new passwords.

It also configures PAM faillock in /etc/pam.d/system-auth and /etc/pam.d/password-auth to lock an account after five failed attempts for 900 seconds, and provides a loop to lock or delete unused system accounts.

2. SSH Hardening

The original sshd_config is backed up, then a production‑grade snippet is written to /etc/ssh/sshd_config.d/00-hardening.conf:

# Basic
Port 2233
AddressFamily inet
Protocol 2

# Authentication
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
PermitEmptyPasswords no
ChallengeResponseAuthentication no
KerberosAuthentication no
GSSAPIAuthentication no
UsePAM yes

# Limits
MaxAuthTries 3
MaxSessions 5
LoginGraceTime 60
ClientAliveInterval 300
ClientAliveCountMax 2

# Display & Forwarding
X11Forwarding no
PrintMotd no
PrintLastLog yes
TCPKeepAlive no
Compression no

# Access control
AllowUsers [email protected].*

The configuration is validated with sshd -t and reloaded without dropping existing sessions. The author recommends restricting login to a non‑root user (e.g., opsadmin) and optionally adding Google Authenticator or a bastion host.

3. ClamAV Antivirus

Installation on CentOS/RHEL:

yum install -y epel-release
yum install -y clamav clamav-server clamav-data clamav-update \
    clamav-scanner clamav-devel clamav-milter

The /etc/freshclam.conf file is edited to enable logging and set the database owner to root. A daily cron job updates the virus database, and several clamscan commands are provided for full‑disk, web‑root, mail, and quarantine scans.

4. Additional Detection Tools

The author also recommends Lynis, rkhunter, chkrootkit, OSSEC and its successor Wazuh for deeper host‑based intrusion detection.

5. Firewall Configuration

For CentOS 7/8 the preferred firewall is firewalld. A production zone setup opens only required services (http, https, custom SSH port 2233, Prometheus) and adds rich‑rule blocks for known malicious IP ranges. For new deployments on CentOS 8/RHEL 8+, nftables is shown:

#!/usr/sbin/nft -f
flush ruleset

table inet filter {
    chain input {
        type filter hook input priority 0; policy drop;
        iif lo accept
        ct state established,related accept
        ct state invalid drop
        ip protocol icmp accept
        ip6 nexthdr icmpv6 accept
        tcp dport 2233 ct state new meter ssh-meter { ip saddr limit rate 10/minute } accept
        tcp dport { 80, 443 } accept
        log prefix "nft-dropped: " limit rate 10/minute
    }
    chain forward { type filter hook forward priority 0; policy drop; }
    chain output { type filter hook output priority 0; policy accept; }
}

The ruleset is applied with nft -f /etc/nftables/main.nft and verified via nft list ruleset.

6. fail2ban

Installation and a custom /etc/fail2ban/jail.local are provided. The default jail bans an IP after three failures within ten minutes for 24 hours, with a whitelist for internal networks. A dedicated [sshd-custom] jail uses the non‑standard port and integrates with firewalld rich‑rules. Additional jails protect nginx and Apache HTTP authentication.

7. AIDE File Integrity Monitoring

After installing aide, a minimal /etc/aide.conf monitors critical directories (/, /boot, /etc, /usr, /bin, /sbin, /lib, /lib64, /opt) with SHA‑256, permissions, ACLs and timestamps. Exclusions prevent noisy logs. The database is initialized with aide --init, and a daily cron job runs aide --check and emails any differences.

8. SELinux & sysctl Hardening

SELinux is set to enforcing via setenforce 1 and a permanent change in /etc/selinux/config. Common troubleshooting commands ( semanage fcontext, restorecon, ausearch) are listed.

The kernel parameters are written to /etc/sysctl.d/99-security.conf and include disabling IP forwarding, enabling SYN‑cookies, rejecting source routing, disabling ICMP redirects, enabling reverse‑path filtering, ignoring broadcast pings, logging martian packets, randomizing virtual address space, disabling core dumps and optionally disabling IPv6. The settings are applied with sysctl --system.

9. One‑Click Hardening Script

A complete Bash script ( /root/harden.sh) ties all previous steps together. It backs up existing configurations, creates a dedicated admin user ( opsadmin), applies the password policy, SSH hardening, firewall rules, sysctl settings, installs and enables fail2ban, AIDE, ClamAV, auditd, and prints post‑run actions (copy SSH keys, verify new port, backup location). The script begins with a safety warning to test on a non‑production machine and ensure an out‑of‑band console is available.

10. Final Recommendations

The author stresses the "weakest‑link" principle: even with WAFs and compliance devices, an insecure SSH configuration leaves the server exposed. Regular yum update, bastion‑host usage, daily log review, encrypted off‑site backups and quarterly restore drills are recommended.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

firewalllinuxsecurityShellsysadminhardening
AI Agent Super App
Written by

AI Agent Super App

AI agent applications, installation, large-model testing, computer fundamentals, IT operations and maintenance exchange, network technology exchange, Linux learning

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.