Master Linux Security Hardening: Practical Scripts & Best Practices
This comprehensive guide walks you through Linux security threats, three-layer defense strategies, user account hardening, SSH and firewall configuration, file system protection, service hardening, kernel tuning, automated monitoring, incident response, and a step‑by‑step implementation roadmap to build a resilient, multi‑layered defense system.
Preventive Linux System Security Hardening Guide
In today's digital era, 90% of attacks start from system vulnerabilities. This guide shares practical hardening techniques to turn a bare server into a fortified one.
Current Threat Landscape: Is Your Linux Really Secure?
Common Threat Types
Brute-force attacks : password cracking on SSH, FTP, etc.
Privilege escalation : kernel exploits to gain root.
Malware infection : trojans, backdoors, cryptominers.
Data leakage : misconfigured file permissions.
DDoS attacks : resource exhaustion.
Three Defense Layers
第一道防线:系统层防护(用户管理、权限控制、服务加固)</code>
<code>第二道防线:网络层防护(防火墙、端口管理、流量监控)</code>
<code>第三道防线:应用层防护(日志审计、入侵检测、应急响应)User Account Security: Strengthening the First Line
1. Account Management Best Practices
Disable unnecessary system accounts
#!/bin/bash
# Disable unnecessary accounts
USERS_TO_DISABLE="games news uucp operator gopher"
for user in $USERS_TO_DISABLE; do
if id "$user" >/dev/null 2>&1; then
usermod -L "$user"
usermod -s /sbin/nologin "$user"
echo "Disabled account: $user"
fi
done
# Check accounts with empty passwords
awk -F: '($2 == "") {print "Warning: " $1 " account has empty password"}' /etc/shadowCreate a secure admin account
# Create a sudo-enabled user
useradd -m -s /bin/bash -G wheel secadmin
passwd secadmin
# Optional passwordless sudo (use with caution)
echo "secadmin ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers.d/secadmin
chmod 440 /etc/sudoers.d/secadmin2. Password Policy Hardening
Configure strong password policy
# /etc/login.defs
PASS_MAX_DAYS 90
PASS_MIN_DAYS 7
PASS_MIN_LEN 12
PASS_WARN_AGE 14
# Install pam_pwquality
yum install -y libpwquality
echo "password requisite pam_pwquality.so retry=3 minlen=12 dcredit=-1 ucredit=-1 ocredit=-1 lcredit=-1" >> /etc/pam.d/system-authAccount lockout policy
# /etc/pam.d/sshd
auth required pam_tally2.so deny=5 unlock_time=300 even_deny_root root_unlock_time=300
account required pam_tally2.soSSH Security Hardening: Closing Dangerous Doors
1. SSH Configuration Optimization
Core security settings
# /etc/ssh/sshd_config
Port 2022
Protocol 2
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
MaxAuthTries 3
MaxSessions 2
ClientAliveInterval 300
ClientAliveCountMax 2
AllowUsers secadmin developer
DenyUsers root guest2. SSH Key Authentication
Generate and deploy keys
# On client
ssh-keygen -t ed25519 -b 4096 -f ~/.ssh/id_ed25519 -N ""
# Copy to server
ssh-copy-id -i ~/.ssh/id_ed25519.pub secadmin@server_ip
# Set permissions on server
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chown -R secadmin:secadmin ~/.sshSSH login monitoring script
#!/bin/bash
LOG_FILE="/var/log/secure"
ALERT_EMAIL="[email protected]"
tail -f $LOG_FILE | while read line; do
if echo "$line" | grep -q "Failed password"; then
IP=$(echo "$line" | awk '{print $11}')
USER=$(echo "$line" | awk '{print $9}')
echo "SSH login failure: $USER from $IP" | mail -s "SSH Security Alert" $ALERT_EMAIL
FAIL_COUNT=$(grep "Failed password" $LOG_FILE | grep "$IP" | wc -l)
if [ $FAIL_COUNT -gt 5 ]; then
iptables -A INPUT -s $IP -j DROP
echo "Blocked IP: $IP"
fi
fi
doneFirewall Configuration: Building Network Shield
1. iptables firewall rules
Basic firewall script
#!/bin/bash
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp --dport 2022 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT2. firewalld modern management
firewalld example
# Enable firewalld
systemctl enable --now firewalld
# Set default zone
firewall-cmd --set-default-zone=public
# Add services
firewall-cmd --permanent --zone=public --add-service=ssh
firewall-cmd --permanent --zone=public --add-service=http
firewall-cmd --permanent --zone=public --add-service=https
# Custom port
firewall-cmd --permanent --zone=public --add-port=2022/tcp
# Restrict SSH source
firewall-cmd --permanent --zone=public --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" service name="ssh" accept'
firewall-cmd --reloadFile System Security: Protecting Data Assets
1. File Permission Management
Key file permission check script
#!/bin/bash
check_file_permissions() {
local file=$1
local expected_perm=$2
local current_perm=$(stat -c "%a" "$file" 2>/dev/null)
if [ "$current_perm" != "$expected_perm" ]; then
echo "Warning: $file permission abnormal, current: $current_perm, expected: $expected_perm"
chmod $expected_perm "$file"
echo "Fixed: $file permission set to $expected_perm"
fi
}
check_file_permissions "/etc/passwd" "644"
check_file_permissions "/etc/shadow" "600"
check_file_permissions "/etc/group" "644"
check_file_permissions "/etc/gshadow" "600"
check_file_permissions "/etc/ssh/sshd_config" "600"
# Find files with SUID/SGID bits
find / -type f \( -perm -4000 -o -perm -2000 \) -exec ls -lg {} \; 2>/dev/null | head -202. Disk Encryption and Secure Mounts
Secure mount options
# /etc/fstab
/dev/sda1 /home ext4 defaults,nodev,nosuid,noexec 0 2
/dev/sda2 /tmp ext4 defaults,nodev,nosuid,noexec 0 2
/dev/sda3 /var/log ext4 defaults,nodev,nosuid,noexec 0 2
# Create encrypted partition
cryptsetup luksFormat /dev/sdb1
cryptsetup luksOpen /dev/sdb1 encrypted_disk
mkfs.ext4 /dev/mapper/encrypted_diskService Hardening: Reducing Attack Surface
1. Service Management and Port Control
Service security check script
#!/bin/bash
DISABLE_SERVICES="telnet rsh rlogin ypbind tftp talk ntalk"
for service in $DISABLE_SERVICES; do
if systemctl is-enabled $service >/dev/null 2>&1; then
systemctl disable --now $service
echo "Disabled service: $service"
fi
done
echo "=== Current listening ports ==="
netstat -tlnp | grep LISTEN
echo "=== Running services ==="
systemctl list-units --type=service --state=running | grep -v "systemd"2. Web Server Security
Nginx secure configuration example
# /etc/nginx/nginx.conf
http {
server_tokens off;
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";
client_max_body_size 10M;
client_body_buffer_size 128k;
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=5r/s;
server {
listen 443 ssl http2;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
ssl_prefer_server_ciphers off;
limit_conn conn_limit_per_ip 10;
limit_req zone=req_limit_per_ip burst=10 nodelay;
}
}System Monitoring and Log Auditing: Insight into Security Posture
1. System Log Configuration
rsyslog security log setup
# /etc/rsyslog.conf
auth,authpriv.* /var/log/auth.log
kern.* /var/log/kern.log
mail.* /var/log/mail.log
*.*@log-server.company.com:514
# Logrotate for auth.log
cat > /etc/logrotate.d/security <<EOF
/var/log/auth.log {
daily
missingok
rotate 52
compress
delaycompress
notifempty
create 0640 syslog adm
}
EOF2. Intrusion Detection System Deployment
AIDE file integrity monitoring
# Install AIDE
yum install -y aide
aide --init
mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz
# Daily check cron
cat > /etc/cron.daily/aide-check <<'EOF'
#!/bin/bash
AIDE_REPORT=/tmp/aide_report_$(date +%Y%m%d)
aide --check > $AIDE_REPORT 2>&1
if [ $? -ne 0 ]; then
mail -s "AIDE detected changes" [email protected] < $AIDE_REPORT
fi
EOF
chmod +x /etc/cron.daily/aide-checkKernel Parameter Tuning: System‑Level Security
1. Network Security Parameters
sysctl hardening
# /etc/sysctl.conf
net.ipv4.ip_forward = 0
net.ipv6.conf.all.forwarding = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 2048
net.ipv4.tcp_synack_retries = 2
net.ipv4.icmp_echo_ignore_all = 1
sysctl -p2. Memory and Process Security
Process security controls
# Limit core dumps
echo "* soft core 0" >> /etc/security/limits.conf
echo "* hard core 0" >> /etc/security/limits.conf
# Limit number of processes
echo "* soft nproc 65536" >> /etc/security/limits.conf
echo "* hard nproc 65536" >> /etc/security/limits.conf
# Enable address space randomization
echo 2 > /proc/sys/kernel/randomize_va_spaceAutomated Security Checks: Continuous Assurance
1. Comprehensive Daily Check Script
#!/bin/bash
REPORT_FILE="/tmp/security_report_$(date +%Y%m%d).txt"
echo "=== Linux Security Check Report ===" > $REPORT_FILE
echo "Check time: $(date)" >> $REPORT_FILE
echo "" >> $REPORT_FILE
echo "=== Recent logins ===" >> $REPORT_FILE
last -10 >> $REPORT_FILE
echo "=== sudo usage ===" >> $REPORT_FILE
grep sudo /var/log/auth.log | tail -10 >> $REPORT_FILE
echo "=== Suspicious processes ===" >> $REPORT_FILE
ps aux | awk '{print $1, $2, $11}' | grep -v "^\[" | sort | uniq -c | sort -nr | head -20 >> $REPORT_FILE
echo "=== Network connections ===" >> $REPORT_FILE
netstat -tupln | grep LISTEN >> $REPORT_FILE
mail -s "Daily Security Report" [email protected] < $REPORT_FILE2. CIS Baseline Check Snippet
#!/bin/bash
check_password_policy() {
echo "Checking password policy..."
if grep -q "PASS_MAX_DAYS.*90" /etc/login.defs; then
echo "✓ Password max days correct"
else
echo "✗ Password max days incorrect"
fi
}
check_ssh_config() {
echo "Checking SSH config..."
if grep -q "^PermitRootLogin no" /etc/ssh/sshd_config; then
echo "✓ SSH root login disabled"
else
echo "✗ SSH root login allowed"
fi
}
check_password_policy
check_ssh_configIncident Response Playbook: Handling Security Events
1. Intrusion Detection and Response
Security incident response script
#!/bin/bash
isolate_system() {
echo "Isolating system..."
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -A INPUT -p tcp --dport 2022 -s 192.168.1.100 -j ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
systemctl stop httpd nginx mysql
echo "System isolated, only management access remains"
}
collect_evidence() {
EVIDENCE_DIR="/tmp/incident_$(date +%Y%m%d_%H%M%S)"
mkdir -p $EVIDENCE_DIR
ps aux > $EVIDENCE_DIR/processes.txt
netstat -tupln > $EVIDENCE_DIR/network.txt
lsof > $EVIDENCE_DIR/openfiles.txt
cp /var/log/auth.log $EVIDENCE_DIR/
cp /var/log/messages $EVIDENCE_DIR/
echo "Evidence collected: $EVIDENCE_DIR"
}
# Example usage:
# isolate_system
# collect_evidenceSecurity Configuration Templates: Standardized Deployment
1. One‑click Hardening Script
Complete hardening script
#!/bin/bash
set -e
SCRIPT_NAME="Linux Security Hardening"
LOG_FILE="/var/log/security_hardening.log"
log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a $LOG_FILE
}
log "Starting $SCRIPT_NAME"
# Update system
log "Updating packages..."
yum update -y >> $LOG_FILE 2>&1
# Configure SSH
log "Configuring SSH..."
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
sed -i 's/#Port 22/Port 2022/' /etc/ssh/sshd_config
sed -i 's/#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
systemctl restart sshd
# Configure firewall
log "Setting firewall rules..."
systemctl enable --now firewalld
firewall-cmd --permanent --remove-service=ssh
firewall-cmd --permanent --add-port=2022/tcp
firewall-cmd --reload
log "Hardening complete! Check log: $LOG_FILE"Continuous Improvement: Building a Security Culture
Security Monitoring Dashboard
#!/bin/bash
METRICS_FILE="/var/log/security_metrics.json"
{
echo "{"
echo " \"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\","
echo " \"failed_logins\": $(grep "Failed password" /var/log/auth.log | wc -l),"
echo " \"active_connections\": $(netstat -tn | grep :22 | wc -l),"
echo " \"suspicious_processes\": $(ps aux | grep -E "(nc|wget|curl)" | wc -l),"
echo " \"disk_usage\": $(df / | awk 'NR==2 {print $5}' | sed 's/%//'),"
echo " \"load_average\": \"$(uptime | awk -F'load average:' '{print $2}')\""
echo "}"
} > $METRICS_FILESecurity Training and Awareness
New employee security awareness training
Regular security drills and tests
Security incident experience sharing
Latest threat intelligence learning
Conclusion: Building a Multi‑Layered Defense System
Linux security hardening is an ongoing process that requires a layered approach, continuous monitoring, regular updates, and a strong security culture.
Core Security Principles
Least‑privilege principle : grant only necessary permissions and review regularly.
Depth in defense : multiple layers so a single failure does not compromise overall security.
Continuous monitoring : real‑time status to quickly detect anomalies.
Regular updates : apply patches and refresh configurations promptly.
Implementation Roadmap
Phase 1: Basic hardening (1‑2 weeks)
User and permission management
SSH hardening
Basic firewall rules
Critical service hardening
Phase 2: Monitoring enhancement (2‑3 weeks)
Log configuration and monitoring
Intrusion detection system
Automated check scripts
Security baseline checks
Phase 3: Continuous improvement (long term)
Security training and drills
Threat intelligence integration
Incident response optimization
Security tool upgrades
Success Stories
In practice, these measures reduced brute‑force success by 95%, cut incident response time from hours to minutes, and established a 24/7 security monitoring posture.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
