A comprehensive guide to hardening Linux systems with practical implementations, use cases, and before/after comparisons.
- Firewall Configuration
- SSH Security Hardening
- Intrusion Detection & Prevention
- User Access Control
- Process Security
- System Monitoring
- Additional Security Tools
- Security Assessment Script
Firewall configuration involves setting up network packet filtering rules to control incoming and outgoing network traffic based on predetermined security rules.
- Block unauthorized network access
- Prevent network-based attacks
- Control which services are accessible from external networks
- Create defense layers against port scanning and intrusion attempts
# Check firewall status
sudo systemctl status firewalld
# Enable and start firewall
sudo systemctl enable firewalld
sudo systemctl start firewalld
# Check current configuration
sudo firewall-cmd --list-all
# Remove unnecessary services
sudo firewall-cmd --permanent --remove-service=cockpit
# Add only required services
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
# Reload configuration
sudo firewall-cmd --reload| Aspect | Before Hardening | After Hardening |
|---|---|---|
| Status | ❌ Firewall disabled | ✅ Firewall active and configured |
| Services | All ports potentially open | Only SSH (22), HTTP (80), HTTPS (443) |
| Protection | No network filtering | Packet filtering active |
| Attack Surface | High - all services exposed | Low - minimal services exposed |
SSH hardening involves configuring the SSH daemon with security-focused settings to prevent unauthorized access and reduce attack vectors.
- Prevent brute force attacks
- Disable insecure authentication methods
- Limit user access
- Enhance connection security and logging
#!/bin/bash
# SSH Security Hardening Script
echo "🔒 SSH Security Hardening"
# Backup original configuration
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup.$(date +%Y%m%d_%H%M%S)
# Apply security improvements
sudo sed -i 's/^#*PermitRootLogin.*/PermitRootLogin no/' /etc/ssh/sshd_config
sudo sed -i 's/^#*PasswordAuthentication.*/PasswordAuthentication yes/' /etc/ssh/sshd_config
# Add security settings
sudo tee -a /etc/ssh/sshd_config << 'EOF'
# Security Hardening Settings
MaxAuthTries 3
MaxStartups 5:30:10
LoginGraceTime 60
ClientAliveInterval 300
ClientAliveCountMax 2
X11Forwarding no
AllowTcpForwarding yes
GatewayPorts no
PermitTunnel no
Banner /etc/ssh/banner
LogLevel VERBOSE
Protocol 2
EOF
# Create security banner
sudo tee /etc/ssh/banner << 'EOF'
***************************************************************************
SECURITY NOTICE
***************************************************************************
This system is for authorized users only. All activities are monitored
and logged. Unauthorized access is prohibited.
***************************************************************************
EOF
# Set permissions and restart
sudo chmod 600 /etc/ssh/sshd_config
sudo chmod 644 /etc/ssh/banner
sudo systemctl restart sshd
echo "✅ SSH hardening completed!"#!/bin/bash
# Advanced SSH Hardening with Key Authentication
# Generate SSH key pair (run on client)
ssh-keygen -t rsa -b 4096 -C "[email protected]"
# Copy public key to server
ssh-copy-id username@server_ip
# Advanced SSH configuration
sudo tee /etc/ssh/sshd_config << 'EOF'
# Advanced SSH Security Configuration
Port 2222
AddressFamily inet
ListenAddress 0.0.0.0
# Authentication
PermitRootLogin no
MaxAuthTries 3
MaxStartups 3:30:10
LoginGraceTime 30
PasswordAuthentication no
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PermitEmptyPasswords no
ChallengeResponseAuthentication no
# Encryption
Protocol 2
Ciphers [email protected],[email protected],aes256-ctr
MACs [email protected],[email protected]
KexAlgorithms [email protected],diffie-hellman-group16-sha512
# User restrictions
AllowUsers yourusername
DenyUsers root
# Logging and monitoring
SyslogFacility AUTH
LogLevel VERBOSE
Banner /etc/ssh/banner
EOF
# Update firewall for new port
sudo firewall-cmd --permanent --remove-service=ssh
sudo firewall-cmd --permanent --add-port=2222/tcp
sudo firewall-cmd --reload
sudo systemctl restart sshd| Setting | Before Hardening | After Hardening |
|---|---|---|
| Root Login | ✅ Enabled | ❌ Disabled |
| Auth Attempts | Unlimited | 3 maximum |
| Connection Timeout | Default (no timeout) | 300 seconds with 2 max |
| X11 Forwarding | ✅ Enabled | ❌ Disabled |
| Logging Level | INFO | VERBOSE |
| Security Banner | None | Warning banner |
| Port | 22 (default) | 2222 (non-standard) |
| Authentication | Password | SSH Keys only |
Fail2ban is an intrusion prevention system that monitors log files and automatically bans IP addresses that show suspicious behavior.
- Automatically block brute force attacks
- Prevent dictionary attacks on SSH
- Protect web services from malicious requests
- Reduce server load from repeated failed attempts
# Install fail2ban
sudo dnf install -y fail2ban # RHEL/CentOS/AlmaLinux
# sudo apt install -y fail2ban # Debian/Ubuntu
# Enable and start service
sudo systemctl enable fail2ban
sudo systemctl start fail2ban#!/bin/bash
# Fail2ban Configuration Script
# Create jail configuration
sudo tee /etc/fail2ban/jail.local << 'EOF'
[DEFAULT]
# Ban duration (1 hour)
bantime = 3600
# Time window to count failures (10 minutes)
findtime = 600
# Maximum retries before ban
maxretry = 3
# Ignore local networks and VPN networks
ignoreip = 127.0.0.1/8 ::1 192.168.0.0/16 10.0.0.0/8 172.16.0.0/12 100.64.0.0/10
# Backend for log monitoring
backend = systemd
# Action when banning (firewall block)
action = %(action_)s
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = %(sshd_log)s
maxretry = 5
bantime = 1800
findtime = 600
[nginx-http-auth]
enabled = true
port = http,https
filter = nginx-http-auth
logpath = /var/log/nginx/error.log
maxretry = 6
[nginx-badbots]
enabled = true
port = http,https
filter = nginx-badbots
logpath = /var/log/nginx/access.log
maxretry = 2
EOF
# Test and restart
sudo fail2ban-client -t
sudo systemctl restart fail2ban
echo "✅ Fail2ban configured successfully!"#!/bin/bash
# Fail2ban Monitoring Script
echo "🛡️ Fail2ban Status Report"
echo "========================="
# Service status
echo "📈 Service Status:"
systemctl is-active fail2ban
# Currently banned IPs
echo "🔒 Currently Banned IPs:"
sudo fail2ban-client status
# SSH jail status
echo "📋 SSH Jail Status:"
sudo fail2ban-client status sshd
# Recent ban activity
echo "📝 Recent Ban Activity:"
sudo journalctl -u fail2ban.service -n 50 --no-pager | grep -E "(Ban|Unban)" | tail -10| Protection | Before Hardening | After Hardening |
|---|---|---|
| Brute Force Protection | ❌ None | ✅ Automatic IP banning |
| Attack Detection | Manual monitoring required | Automatic detection and response |
| Failed Login Handling | Unlimited attempts allowed | 5 attempts then 30-minute ban |
| Log Monitoring | Manual log review | Automated log analysis |
| Response Time | Manual intervention needed | Immediate automated response |
User access control involves managing user permissions, group memberships, and access to system resources and logs.
- Implement principle of least privilege
- Enable users to access necessary logs without sudo
- Control administrative access
- Audit user activities
#!/bin/bash
# User Access Control Configuration
# Add user to necessary groups for log access
sudo usermod -a -G systemd-journal username
sudo usermod -a -G adm username
# Create custom group for monitoring
sudo groupadd monitoring
sudo usermod -a -G monitoring username
# Set up sudo rules for specific commands
sudo tee /etc/sudoers.d/monitoring << 'EOF'
# Allow monitoring group to run specific security commands without password
%monitoring ALL=(ALL) NOPASSWD: /usr/bin/fail2ban-client status, /usr/bin/systemctl status *, /usr/bin/firewall-cmd --list-all
EOF
# Verify group membership
groups username
echo "✅ User access control configured!"#!/bin/bash
# Create dedicated security monitoring user
# Create security user
sudo useradd -m -s /bin/bash secadmin
sudo usermod -a -G systemd-journal,adm,monitoring secadmin
# Set up SSH key authentication for security user
sudo mkdir -p /home/secadmin/.ssh
sudo chmod 700 /home/secadmin/.ssh
# Generate dedicated SSH key pair for security access
ssh-keygen -t rsa -b 4096 -f ~/.ssh/secadmin_key -C "security-admin"
# Copy public key to security user
sudo cp ~/.ssh/secadmin_key.pub /home/secadmin/.ssh/authorized_keys
sudo chmod 600 /home/secadmin/.ssh/authorized_keys
sudo chown -R secadmin:secadmin /home/secadmin/.ssh
echo "✅ Security user account created!"| Access Control | Before Hardening | After Hardening |
|---|---|---|
| Log Access | Requires sudo for system logs | Direct access to systemd-journal |
| Administrative Tasks | Full sudo access needed | Granular sudo permissions |
| User Separation | Single user account | Dedicated security admin account |
| Audit Trail | Limited user activity tracking | Comprehensive group-based auditing |
Process security involves monitoring running processes, identifying potentially malicious activities, and ensuring processes run with appropriate privileges.
- Detect unauthorized processes
- Monitor resource usage
- Identify privilege escalation attempts
- Audit process execution
#!/bin/bash
# Process Security Monitoring Script
echo "🔍 Process Security Analysis"
echo "============================"
# Check processes running as root
echo "📊 Processes running as root:"
ps aux | awk '$1 == "root" {print $1, $2, $11}' | head -10
# Look for suspicious process names
echo "🚨 Checking for suspicious processes:"
ps aux | grep -E "(sh|bash|nc|netcat|python|perl)" | grep -v grep | head -5
# Check network connections by process
echo "🌐 Network connections by process:"
sudo netstat -tulpn | grep LISTEN | head -10
# Monitor CPU and memory usage
echo "💻 Top processes by resource usage:"
ps aux --sort=-%cpu | head -10
# Check for processes with unusual names or paths
echo "⚠️ Processes with unusual characteristics:"
ps aux | awk 'length($11) > 50 || $11 ~ /^[^\/]/ {print $1, $2, $11}' | head -5
# Check systemd services
echo "🔧 Active systemd services:"
systemctl list-units --type=service --state=active | head -10#!/bin/bash
# Service Hardening Script
# Disable unnecessary services
services_to_disable=(
"telnet"
"rsh"
"rlogin"
"vsftpd"
"httpd" # If not needed
"smb"
"nfs"
)
echo "🔒 Hardening Services"
for service in "${services_to_disable[@]}"; do
if systemctl is-enabled "$service" 2>/dev/null; then
echo "Disabling $service..."
sudo systemctl disable "$service"
sudo systemctl stop "$service"
fi
done
# Enable security-focused services
security_services=(
"fail2ban"
"firewalld"
"auditd"
)
for service in "${security_services[@]}"; do
if systemctl list-unit-files | grep -q "$service"; then
echo "Enabling $service..."
sudo systemctl enable "$service"
sudo systemctl start "$service"
fi
done
echo "✅ Service hardening completed!"| Process Security | Before Hardening | After Hardening |
|---|---|---|
| Process Monitoring | Manual inspection | Automated monitoring scripts |
| Service Management | Default services running | Only necessary services enabled |
| Resource Monitoring | No systematic monitoring | Regular resource usage checks |
| Suspicious Activity Detection | Reactive detection | Proactive monitoring |
System monitoring involves continuous observation of system performance, security events, and potential threats through log analysis and automated reporting.
- Early detection of security incidents
- Performance monitoring and optimization
- Compliance and audit requirements
- Automated alerting for critical events
#!/bin/bash
# Comprehensive Security Monitoring Script
REPORT_FILE="/var/log/security_report_$(date +%Y%m%d_%H%M%S).log"
generate_security_report() {
echo "🛡️ SECURITY MONITORING REPORT" | tee -a "$REPORT_FILE"
echo "==============================" | tee -a "$REPORT_FILE"
echo "Generated: $(date)" | tee -a "$REPORT_FILE"
echo "" | tee -a "$REPORT_FILE"
# System Information
echo "📊 SYSTEM INFORMATION" | tee -a "$REPORT_FILE"
echo "Hostname: $(hostname)" | tee -a "$REPORT_FILE"
echo "Uptime: $(uptime)" | tee -a "$REPORT_FILE"
echo "Kernel: $(uname -r)" | tee -a "$REPORT_FILE"
echo "" | tee -a "$REPORT_FILE"
# Network Security
echo "🌐 NETWORK SECURITY STATUS" | tee -a "$REPORT_FILE"
echo "Active listening ports:" | tee -a "$REPORT_FILE"
ss -tulpn | grep LISTEN | tee -a "$REPORT_FILE"
echo "" | tee -a "$REPORT_FILE"
# Firewall Status
echo "🔥 FIREWALL STATUS" | tee -a "$REPORT_FILE"
sudo firewall-cmd --list-all | tee -a "$REPORT_FILE"
echo "" | tee -a "$REPORT_FILE"
# Fail2ban Status
echo "🛡️ INTRUSION PREVENTION STATUS" | tee -a "$REPORT_FILE"
sudo fail2ban-client status | tee -a "$REPORT_FILE"
echo "" | tee -a "$REPORT_FILE"
# Authentication Analysis
echo "🔐 AUTHENTICATION ANALYSIS" | tee -a "$REPORT_FILE"
echo "Recent successful logins:" | tee -a "$REPORT_FILE"
journalctl -u sshd.service --since="24 hours ago" | grep "Accepted" | tail -10 | tee -a "$REPORT_FILE"
echo "" | tee -a "$REPORT_FILE"
echo "Recent failed logins:" | tee -a "$REPORT_FILE"
journalctl -u sshd.service --since="24 hours ago" | grep "Failed" | tail -10 | tee -a "$REPORT_FILE"
echo "" | tee -a "$REPORT_FILE"
# System Resource Usage
echo "💻 RESOURCE USAGE" | tee -a "$REPORT_FILE"
echo "Memory usage:" | tee -a "$REPORT_FILE"
free -h | tee -a "$REPORT_FILE"
echo "" | tee -a "$REPORT_FILE"
echo "Disk usage:" | tee -a "$REPORT_FILE"
df -h | tee -a "$REPORT_FILE"
echo "" | tee -a "$REPORT_FILE"
# Process Analysis
echo "🔍 PROCESS ANALYSIS" | tee -a "$REPORT_FILE"
echo "Top processes by CPU:" | tee -a "$REPORT_FILE"
ps aux --sort=-%cpu | head -10 | tee -a "$REPORT_FILE"
echo "" | tee -a "$REPORT_FILE"
echo "✅ Security report generated: $REPORT_FILE"
}
# Set up automated monitoring
setup_automated_monitoring() {
# Create monitoring script
sudo tee /usr/local/bin/security-monitor.sh << 'EOF'
#!/bin/bash
# Automated Security Monitoring
# Check for critical security events
ALERT_FILE="/tmp/security_alerts_$(date +%Y%m%d).log"
# Monitor failed SSH attempts
FAILED_SSH=$(journalctl -u sshd.service --since="1 hour ago" | grep -c "Failed password")
if [ "$FAILED_SSH" -gt 10 ]; then
echo "$(date): WARNING - $FAILED_SSH failed SSH attempts in the last hour" >> "$ALERT_FILE"
fi
# Check for new banned IPs
BANNED_IPS=$(sudo fail2ban-client status sshd 2>/dev/null | grep "Currently banned" | grep -o '[0-9]*')
if [ "$BANNED_IPS" -gt 0 ]; then
echo "$(date): INFO - $BANNED_IPS IPs currently banned by fail2ban" >> "$ALERT_FILE"
fi
# Monitor disk usage
DISK_USAGE=$(df / | awk 'NR==2 {print $5}' | sed 's/%//')
if [ "$DISK_USAGE" -gt 80 ]; then
echo "$(date): WARNING - Disk usage is ${DISK_USAGE}%" >> "$ALERT_FILE"
fi
# Check memory usage
MEMORY_USAGE=$(free | awk 'NR==2{printf "%.2f", $3*100/$2}')
if (( $(echo "$MEMORY_USAGE > 90" | bc -l) )); then
echo "$(date): WARNING - Memory usage is ${MEMORY_USAGE}%" >> "$ALERT_FILE"
fi
EOF
sudo chmod +x /usr/local/bin/security-monitor.sh
# Set up cron job for automated monitoring
(crontab -l 2>/dev/null; echo "0 */4 * * * /usr/local/bin/security-monitor.sh") | crontab -
echo "✅ Automated monitoring set up!"
}
# Run functions
generate_security_report
setup_automated_monitoring#!/bin/bash
# Advanced Log Analysis Script
analyze_security_logs() {
echo "📊 SECURITY LOG ANALYSIS"
echo "========================"
# Analyze SSH authentication patterns
echo "🔐 SSH Authentication Analysis:"
echo "Top source IPs for failed logins:"
journalctl -u sshd.service --since="7 days ago" | grep "Failed password" | \
awk '{print $(NF-3)}' | sort | uniq -c | sort -nr | head -10
# Analyze successful login patterns
echo "✅ Successful login patterns:"
journalctl -u sshd.service --since="7 days ago" | grep "Accepted password" | \
awk '{print $(NF-3)}' | sort | uniq -c | sort -nr | head -10
# Check for privilege escalation attempts
echo "⚠️ Privilege escalation attempts:"
journalctl --since="24 hours ago" | grep -i "sudo" | grep -E "(FAILED|failed|denied)" | tail -5
# Analyze system errors
echo "🚨 System errors and warnings:"
journalctl --priority=err --since="24 hours ago" | tail -10
# Network connection analysis
echo "🌐 Network connection analysis:"
echo "Unique external connections in last 24 hours:"
journalctl --since="24 hours ago" | grep -E "connection.*from" | \
awk '{print $NF}' | sort | uniq -c | sort -nr | head -10
}
# Set up real-time monitoring
setup_realtime_monitoring() {
# Create real-time SSH monitoring
sudo tee /usr/local/bin/ssh-monitor.sh << 'EOF'
#!/bin/bash
echo "🔍 Real-time SSH Monitoring Started"
echo "Press Ctrl+C to stop"
journalctl -u sshd.service -f | while read line; do
if echo "$line" | grep -q "Failed password"; then
IP=$(echo "$line" | awk '{print $(NF-3)}')
echo "🚨 ALERT: Failed SSH login from $IP at $(date)"
elif echo "$line" | grep -q "Accepted password"; then
IP=$(echo "$line" | awk '{print $(NF-3)}')
USER=$(echo "$line" | awk '{print $(NF-5)}')
echo "✅ INFO: Successful SSH login for $USER from $IP at $(date)"
fi
done
EOF
sudo chmod +x /usr/local/bin/ssh-monitor.sh
echo "✅ Real-time SSH monitoring script created at /usr/local/bin/ssh-monitor.sh"
}
analyze_security_logs
setup_realtime_monitoring| Monitoring | Before Hardening | After Hardening |
|---|---|---|
| Log Analysis | Manual log review | Automated analysis and reporting |
| Alert System | No automated alerts | Real-time monitoring and alerts |
| Security Reports | No regular reports | Automated daily/weekly reports |
| Threat Detection | Reactive | Proactive with automated detection |
Additional security tools provide enhanced protection through intrusion detection, file integrity monitoring, and advanced threat detection.
- File integrity monitoring
- Advanced intrusion detection
- System baseline creation
- Compliance reporting
#!/bin/bash
# AIDE Installation and Configuration
# Install AIDE
sudo dnf install -y aide # RHEL/CentOS/AlmaLinux
# sudo apt install -y aide # Debian/Ubuntu
# Initialize AIDE database
echo "🔍 Initializing AIDE database..."
sudo aide --init
# Move database to production location
sudo mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz
# Create AIDE configuration for specific monitoring
sudo tee /etc/aide.conf.d/custom.conf << 'EOF'
# Custom AIDE rules
# Monitor critical system directories
/etc p+i+n+u+g+s+b+m+c+md5+sha1+sha256
/bin p+i+n+u+g+s+b+m+c+md5+sha1+sha256
/sbin p+i+n+u+g+s+b+m+c+md5+sha1+sha256
/usr/bin p+i+n+u+g+s+b+m+c+md5+sha1+sha256
/usr/sbin p+i+n+u+g+s+b+m+c+md5+sha1+sha256
# Monitor SSH configuration
/etc/ssh p+i+n+u+g+s+b+m+c+md5+sha1+sha256
# Monitor user directories (adjust as needed)
/home p+i+n+u+g+s+b+m+c+md5+sha1+sha256
# Exclude frequently changing files
!/var/log
!/tmp
!/proc
!/sys
!/dev
EOF
# Create AIDE check script
sudo tee /usr/local/bin/aide-check.sh << 'EOF'
#!/bin/bash
AIDE_REPORT="/var/log/aide_report_$(date +%Y%m%d_%H%M%S).log"
echo "🔍 AIDE File Integrity Check" | tee "$AIDE_REPORT"
echo "============================" | tee -a "$AIDE_REPORT"
echo "Date: $(date)" | tee -a "$AIDE_REPORT"
echo "" | tee -a "$AIDE_REPORT"
# Run AIDE check
aide --check | tee -a "$AIDE_REPORT"
# Check if changes were detected
if [ $? -eq 0 ]; then
echo "✅ No unauthorized changes detected" | tee -a "$AIDE_REPORT"
else
echo "⚠️ Changes detected - review the report above" | tee -a "$AIDE_REPORT"
fi
echo "Report saved to: $AIDE_REPORT"
EOF
sudo chmod +x /usr/local/bin/aide-check.sh
# Set up automated AIDE checks
(crontab -l 2>/dev/null; echo "0 2 * * * /usr/local/bin/aide-check.sh") | crontab -
echo "✅ AIDE configured successfully!"#!/bin/bash
# Lynis Installation and Configuration
# Install Lynis
if command -v dnf &> /dev/null; then
sudo dnf install -y lynis
elif command -v apt &> /dev/null; then
sudo apt install -y lynis
else
# Install from source
cd /tmp
wget https://downloads.cisofy.com/lynis/lynis-3.0.8.tar.gz
tar -xzf lynis-3.0.8.tar.gz
sudo mv lynis /usr/local/
sudo ln -s /usr/local/lynis/lynis /usr/local/bin/lynis
fi
# Create Lynis audit script
sudo tee /usr/local/bin/security-audit.sh << 'EOF'
#!/bin/bash
AUDIT_REPORT="/var/log/lynis_audit_$(date +%Y%m%d_%H%M%S).log"
echo "🔍 Security Audit with Lynis" | tee "$AUDIT_REPORT"
echo "=============================" | tee -a "$AUDIT_REPORT"
echo "Date: $(date)" | tee -a "$AUDIT_REPORT"
echo "" | tee -a "$AUDIT_REPORT"
# Run Lynis audit
lynis audit system | tee -a "$AUDIT_REPORT"
echo "Audit report saved to: $AUDIT_REPORT"
# Extract hardening index
HARDENING_INDEX=$(grep "Hardening index" "$AUDIT_REPORT" | tail -1)
echo "Security Score: $HARDENING_INDEX"
EOF
sudo chmod +x /usr/local/bin/security-audit.sh
echo "✅ Lynis security auditing tool configured!"| Security Tools | Before Hardening | After Hardening |
|---|---|---|
| File Integrity | No monitoring | AIDE monitoring critical files |
| Security Auditing | Manual security checks | Automated Lynis audits |
| Baseline Creation | No system baseline | AIDE database baseline |
| Compliance Reporting | Manual documentation | Automated compliance reports |
A comprehensive security assessment script that evaluates the current security posture of the system and provides recommendations.
- Regular security assessments
- Compliance checking
- Vulnerability identification
- Security posture reporting
#!/bin/bash
# Comprehensive Security Assessment Script
ASSESSMENT_LOG="security_assessment_$(date +%Y%m%d_%H%M%S).log"
echo "Starting Linux Security Assessment..." | tee "$ASSESSMENT_LOG"
echo "Note: Some checks require root privileges for complete assessment." | tee -a "$ASSESSMENT_LOG"
echo "" | tee -a "$ASSESSMENT_LOG"
# System Information
echo "===============================================" | tee -a "$ASSESSMENT_LOG"
echo "SYSTEM INFORMATION" | tee -a "$ASSESSMENT_LOG"
echo "===============================================" | tee -a "$ASSESSMENT_LOG"
echo "Hostname: $(hostname)" | tee -a "$ASSESSMENT_LOG"
echo "OS: $(grep PRETTY_NAME /etc/os-release | cut -d'"' -f2)" | tee -a "$ASSESSMENT_LOG"
echo "Kernel: $(uname -r)" | tee -a "$ASSESSMENT_LOG"
echo "Uptime: $(uptime)" | tee -a "$ASSESSMENT_LOG"
echo "Current User: $(whoami)" | tee -a "$ASSESSMENT_LOG"
echo "Date: $(date)" | tee -a "$ASSESSMENT_LOG"
echo "" | tee -a "$ASSESSMENT_LOG"
# Network Security Assessment
echo "===============================================" | tee -a "$ASSESSMENT_LOG"
echo "NETWORK SECURITY ANALYSIS" | tee -a "$ASSESSMENT_LOG"
echo "===============================================" | tee -a "$ASSESSMENT_LOG"
echo "=== Active Listening Ports ===" | tee -a "$ASSESSMENT_LOG"
ss -tulpn | grep LISTEN | tee -a "$ASSESSMENT_LOG"
echo "" | tee -a "$ASSESSMENT_LOG"
echo "=== Established Connections ===" | tee -a "$ASSESSMENT_LOG"
ss -tupn | grep ESTAB | tee -a "$ASSESSMENT_LOG"
echo "" | tee -a "$ASSESSMENT_LOG"
echo "=== Network Interfaces ===" | tee -a "$ASSESSMENT_LOG"
ip addr show | tee -a "$ASSESSMENT_LOG"
echo "" | tee -a "$ASSESSMENT_LOG"
# Firewall Assessment
echo "===============================================" | tee -a "$ASSESSMENT_LOG"
echo "FIREWALL ANALYSIS" | tee -a "$ASSESSMENT_LOG"
echo "===============================================" | tee -a "$ASSESSMENT_LOG"
if command -v firewall-cmd &> /dev/null; then
echo "=== Firewall Status ===" | tee -a "$ASSESSMENT_LOG"
if systemctl is-active firewalld &> /dev/null; then
sudo firewall-cmd --list-all | tee -a "$ASSESSMENT_LOG"
else
echo "Firewalld not running" | tee -a "$ASSESSMENT_LOG"
fi
else
echo "Firewalld not installed" | tee -a "$ASSESSMENT_LOG"
fi
echo "" | tee -a "$ASSESSMENT_LOG"
# SSH Security Assessment
echo "===============================================" | tee -a "$ASSESSMENT_LOG"
echo "SSH CONFIGURATION ANALYSIS" | tee -a "$ASSESSMENT_LOG"
echo "===============================================" | tee -a "$ASSESSMENT_LOG"
if [ -r /etc/ssh/sshd_config ]; then
echo "=== SSH Configuration (Security Settings) ===" | tee -a "$ASSESSMENT_LOG"
echo "Key SSH settings:" | tee -a "$ASSESSMENT_LOG"
grep -E "^(Port|PermitRootLogin|PasswordAuthentication|PubkeyAuthentication|MaxAuthTries)" /etc/ssh/sshd_config | tee -a "$ASSESSMENT_LOG"
else
echo "SSH config file not readable" | tee -a "$ASSESSMENT_LOG"
fi
echo "" | tee -a "$ASSESSMENT_LOG"
# User and Authentication Assessment
echo "===============================================" | tee -a "$ASSESSMENT_LOG"
echo "USER AND AUTHENTICATION ANALYSIS" | tee -a "$ASSESSMENT_LOG"
echo "===============================================" | tee -a "$ASSESSMENT_LOG"
echo "=== User Accounts ===" | tee -a "$ASSESSMENT_LOG"
cut -d: -f1,3,4,6,7 /etc/passwd | grep -E ":(10[0-9][0-9]|[5-9][0-9][0-9]):" | tee -a "$ASSESSMENT_LOG"
echo "" | tee -a "$ASSESSMENT_LOG"
echo "=== Users with sudo access ===" | tee -a "$ASSESSMENT_LOG"
getent group sudo wheel | tee -a "$ASSESSMENT_LOG"
echo "" | tee -a "$ASSESSMENT_LOG"
# Process Assessment
echo "===============================================" | tee -a "$ASSESSMENT_LOG"
echo "PROCESS ANALYSIS" | tee -a "$ASSESSMENT_LOG"
echo "===============================================" | tee -a "$ASSESSMENT_LOG"
echo "=== Top Processes by CPU ===" | tee -a "$ASSESSMENT_LOG"
ps aux --sort=-%cpu | head -15 | tee -a "$ASSESSMENT_LOG"
echo "" | tee -a "$ASSESSMENT_LOG"
echo "=== Processes Running as Root ===" | tee -a "$ASSESSMENT_LOG"
ps aux | awk '$1 == "root" {print $1, $2, $11}' | head -10 | tee -a "$ASSESSMENT_LOG"
echo "" | tee -a "$ASSESSMENT_LOG"
# Security Tools Assessment
echo "===============================================" | tee -a "$ASSESSMENT_LOG"
echo "SECURITY TOOLS STATUS" | tee -a "$ASSESSMENT_LOG"
echo "===============================================" | tee -a "$ASSESSMENT_LOG"
# Check fail2ban
if command -v fail2ban-client &> /dev/null; then
echo "=== Fail2ban Status ===" | tee -a "$ASSESSMENT_LOG"
if systemctl is-active fail2ban &> /dev/null; then
sudo fail2ban-client status | tee -a "$ASSESSMENT_LOG"
else
echo "Fail2ban not running" | tee -a "$ASSESSMENT_LOG"
fi
else
echo "Fail2ban not installed" | tee -a "$ASSESSMENT_LOG"
fi
echo "" | tee -a "$ASSESSMENT_LOG"
# Check AIDE
if command -v aide &> /dev/null; then
echo "=== AIDE Status ===" | tee -a "$ASSESSMENT_LOG"
echo "AIDE installed - file integrity monitoring available" | tee -a "$ASSESSMENT_LOG"
else
echo "AIDE not installed - no file integrity monitoring" | tee -a "$ASSESSMENT_LOG"
fi
echo "" | tee -a "$ASSESSMENT_LOG"
# System Updates Assessment
echo "===============================================" | tee -a "$ASSESSMENT_LOG"
echo "SYSTEM UPDATES ANALYSIS" | tee -a "$ASSESSMENT_LOG"
echo "===============================================" | tee -a "$ASSESSMENT_LOG"
if command -v dnf &> /dev/null; then
echo "=== Available Security Updates ===" | tee -a "$ASSESSMENT_LOG"
dnf check-update --security 2>/dev/null | tee -a "$ASSESSMENT_LOG" || echo "No security updates available or check failed" | tee -a "$ASSESSMENT_LOG"
elif command -v apt &> /dev/null; then
echo "=== Available Security Updates ===" | tee -a "$ASSESSMENT_LOG"
apt list --upgradable 2>/dev/null | grep -i security | tee -a "$ASSESSMENT_LOG" || echo "No security updates found or check failed" | tee -a "$ASSESSMENT_LOG"
fi
echo "" | tee -a "$ASSESSMENT_LOG"
# Generate Security Score
calculate_security_score() {
score=0
# Firewall check (+20 points)
if systemctl is-active firewalld &> /dev/null; then
score=$((score + 20))
fi
# Fail2ban check (+20 points)
if systemctl is-active fail2ban &> /dev/null; then
score=$((score + 20))
fi
# SSH root login disabled (+15 points)
if grep -q "^PermitRootLogin no" /etc/ssh/sshd_config 2>/dev/null; then
score=$((score + 15))
fi
# SSH password auth disabled (+15 points)
if grep -q "^PasswordAuthentication no" /etc/ssh/sshd_config 2>/dev/null; then
score=$((score + 15))
fi
# Non-standard SSH port (+10 points)
if ! grep -q "^Port 22" /etc/ssh/sshd_config 2>/dev/null; then
score=$((score + 10))
fi
# AIDE installed (+10 points)
if command -v aide &> /dev/null; then
score=$((score + 10))
fi
# Regular user (not root) (+10 points)
if [ "$(whoami)" != "root" ]; then
score=$((score + 10))
fi
echo $score
}
# Summary and Recommendations
echo "===============================================" | tee -a "$ASSESSMENT_LOG"
echo "SECURITY ASSESSMENT SUMMARY" | tee -a "$ASSESSMENT_LOG"
echo "===============================================" | tee -a "$ASSESSMENT_LOG"
SECURITY_SCORE=$(calculate_security_score)
echo "Security Score: $SECURITY_SCORE/100" | tee -a "$ASSESSMENT_LOG"
echo "Assessment completed on: $(date)" | tee -a "$ASSESSMENT_LOG"
echo "Output saved to: $ASSESSMENT_LOG" | tee -a "$ASSESSMENT_LOG"
echo "" | tee -a "$ASSESSMENT_LOG"
echo "RECOMMENDATIONS:" | tee -a "$ASSESSMENT_LOG"
echo "1. Review any flagged suspicious processes or connections" | tee -a "$ASSESSMENT_LOG"
echo "2. Verify all user accounts are legitimate" | tee -a "$ASSESSMENT_LOG"
echo "3. Check SSH configuration and authorized keys" | tee -a "$ASSESSMENT_LOG"
echo "4. Monitor system logs regularly" | tee -a "$ASSESSMENT_LOG"
echo "5. Keep system updated with security patches" | tee -a "$ASSESSMENT_LOG"
echo "6. Consider implementing additional security tools if not present" | tee -a "$ASSESSMENT_LOG"
echo "" | tee -a "$ASSESSMENT_LOG"
# Security Recommendations Based on Score
if [ $SECURITY_SCORE -lt 50 ]; then
echo "🔴 CRITICAL: Security score is low. Immediate action required!" | tee -a "$ASSESSMENT_LOG"
echo " - Enable firewall immediately" | tee -a "$ASSESSMENT_LOG"
echo " - Install and configure fail2ban" | tee -a "$ASSESSMENT_LOG"
echo " - Harden SSH configuration" | tee -a "$ASSESSMENT_LOG"
elif [ $SECURITY_SCORE -lt 75 ]; then
echo "🟡 MODERATE: Security improvements needed" | tee -a "$ASSESSMENT_LOG"
echo " - Consider additional security tools" | tee -a "$ASSESSMENT_LOG"
echo " - Review and improve SSH settings" | tee -a "$ASSESSMENT_LOG"
else
echo "🟢 GOOD: Security posture is strong" | tee -a "$ASSESSMENT_LOG"
echo " - Maintain current security measures" | tee -a "$ASSESSMENT_LOG"
echo " - Regular monitoring and updates recommended" | tee -a "$ASSESSMENT_LOG"
fi
echo "" | tee -a "$ASSESSMENT_LOG"
echo "✅ Security assessment completed! Check $ASSESSMENT_LOG for full results." | tee -a "$ASSESSMENT_LOG"| Assessment | Before Hardening | After Hardening |
|---|---|---|
| Security Score | ~30/100 (Critical) | ~85/100 (Good) |
| Automated Assessment | Manual security checks | Comprehensive automated assessment |
| Reporting | No structured reporting | Detailed security reports with scores |
| Recommendations | Generic advice | Tailored recommendations based on findings |
This guide provides a comprehensive approach to Linux security hardening with practical implementations for:
- Firewall Configuration: Network-level protection
- SSH Security: Authentication and access control
- Intrusion Prevention: Automated threat response
- User Access Control: Principle of least privilege
- Process Security: Process monitoring and control
- System Monitoring: Continuous security oversight
- Additional Security Tools: Enhanced protection layers
Each section includes detailed implementation scripts, monitoring tools, and before/after comparisons to demonstrate the security improvements achieved.
- Enable and configure firewall
- Harden SSH configuration
- Install and configure fail2ban
- Set up user access controls
- Implement process monitoring
- Deploy system monitoring scripts
- Install additional security tools (AIDE, Lynis)
- Set up automated security assessments
- Configure log monitoring and alerting
- Create incident response procedures
- Daily: Monitor security alerts and logs
- Weekly: Review fail2ban reports and banned IPs
- Monthly: Run comprehensive security assessments
- Quarterly: Update security tools and configurations
- Annually: Complete security audit and policy review
This guide is continuously updated to reflect best practices in Linux security hardening. For the latest version and updates, visit: GitHub Gist