Essential Security Maintenance Checklist

Essential Security Maintenance Checklist

Implement this comprehensive maintenance schedule:

#!/bin/bash
# /usr/local/bin/security-maintenance-scheduler.sh

# Security Maintenance Automation Script
# Schedules and tracks all security maintenance tasks

MAINTENANCE_DIR="/var/security-maintenance"
LOG_FILE="$MAINTENANCE_DIR/maintenance.log"
mkdir -p "$MAINTENANCE_DIR"

# Function to log activities
log_activity() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# Daily Security Tasks
daily_security_tasks() {
    log_activity "Starting daily security tasks"
    
    # Check for security updates
    log_activity "Checking for security updates"
    apt update > /dev/null 2>&1
    UPDATES=$(apt list --upgradable 2>/dev/null | grep -c security)
    if [ $UPDATES -gt 0 ]; then
        log_activity "WARNING: $UPDATES security updates available"
        echo "Security updates available on $(hostname)" | \
            mail -s "Security Updates Required" [email protected]
    fi
    
    # Review authentication logs
    log_activity "Reviewing authentication logs"
    FAILED_LOGINS=$(grep "Failed password" /var/log/auth.log | \
        grep "$(date '+%b %d')" | wc -l)
    if [ $FAILED_LOGINS -gt 100 ]; then
        log_activity "WARNING: High number of failed logins: $FAILED_LOGINS"
    fi
    
    # Check disk space for logs
    log_activity "Checking disk space"
    DISK_USAGE=$(df -h /var/log | tail -1 | awk '{print $5}' | sed 's/%//')
    if [ $DISK_USAGE -gt 80 ]; then
        log_activity "WARNING: Log partition usage at $DISK_USAGE%"
    fi
    
    # Verify critical services
    log_activity "Verifying critical services"
    for service in apache2 nginx fail2ban ufw; do
        if systemctl is-enabled $service 2>/dev/null | grep -q enabled; then
            if ! systemctl is-active $service | grep -q active; then
                log_activity "ERROR: Service $service is not running"
                systemctl start $service
            fi
        fi
    done
    
    # Check SSL certificate expiration
    log_activity "Checking SSL certificates"
    for cert in /etc/letsencrypt/live/*/cert.pem; do
        if [ -f "$cert" ]; then
            DAYS_LEFT=$(openssl x509 -enddate -noout -in "$cert" | \
                cut -d= -f2 | xargs -I {} date -d {} +%s | \
                xargs -I {} expr {} - $(date +%s) | \
                xargs -I {} expr {} / 86400)
            
            if [ $DAYS_LEFT -lt 30 ]; then
                DOMAIN=$(basename $(dirname "$cert"))
                log_activity "WARNING: Certificate for $DOMAIN expires in $DAYS_LEFT days"
            fi
        fi
    done
    
    log_activity "Daily security tasks completed"
}

# Weekly Security Tasks
weekly_security_tasks() {
    log_activity "Starting weekly security tasks"
    
    # Run security scans
    log_activity "Running security vulnerability scan"
    /usr/local/bin/automated-security-scan.sh > \
        "$MAINTENANCE_DIR/weekly-scan-$(date +%Y%m%d).log" 2>&1
    
    # Review and rotate logs
    log_activity "Rotating security logs"
    logrotate -f /etc/logrotate.d/apache2-security
    logrotate -f /etc/logrotate.d/nginx-security
    
    # Test backup restoration
    log_activity "Testing backup restoration"
    /usr/local/bin/test-backup-restore.sh
    
    # Update security rules
    log_activity "Updating ModSecurity rules"
    if [ -d /etc/modsecurity ]; then
        cd /etc/modsecurity
        git pull origin master
        apache2ctl configtest && systemctl reload apache2
    fi
    
    # Generate security report
    log_activity "Generating weekly security report"
    generate_weekly_report
    
    log_activity "Weekly security tasks completed"
}

# Monthly Security Tasks
monthly_security_tasks() {
    log_activity "Starting monthly security tasks"
    
    # Full system audit
    log_activity "Running comprehensive security audit"
    /usr/local/bin/config-audit.py > \
        "$MAINTENANCE_DIR/monthly-audit-$(date +%Y%m).json"
    
    # Review user accounts
    log_activity "Auditing user accounts"
    for user in $(getent passwd | awk -F: '$3 >= 1000 {print $1}'); do
        LAST_LOGIN=$(lastlog -u $user | tail -1 | awk '{print $4,$5,$6}')
        if [ -z "$LAST_LOGIN" ] || [ "$LAST_LOGIN" = "**Never" ]; then
            log_activity "INFO: User $user has never logged in"
        fi
    done
    
    # Performance optimization review
    log_activity "Reviewing performance metrics"
    analyze_performance_metrics
    
    # Update documentation
    log_activity "Updating security documentation"
    update_security_documentation
    
    # Disaster recovery test
    log_activity "Running disaster recovery test"
    /usr/local/bin/business-continuity-test.sh
    
    log_activity "Monthly security tasks completed"
}

# Generate weekly security report
generate_weekly_report() {
    cat > "$MAINTENANCE_DIR/weekly-report-$(date +%Y%m%d).html" << EOF
<!DOCTYPE html>
<html>
<head>
    <title>Weekly Security Report - $(date +%Y-%m-%d)</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .metric { padding: 10px; margin: 10px 0; border-left: 4px solid #2196F3; }
        .warning { border-left-color: #ff9800; }
        .critical { border-left-color: #f44336; }
    </style>
</head>
<body>
    <h1>Weekly Security Report</h1>
    <p>Period: $(date -d '7 days ago' +%Y-%m-%d) to $(date +%Y-%m-%d)</p>
    
    <h2>Security Metrics</h2>
    <div class="metric">
        <strong>Failed Login Attempts:</strong> $(grep -c "Failed password" /var/log/auth.log)
    </div>
    <div class="metric">
        <strong>Blocked IPs:</strong> $(fail2ban-client status | grep -c "Number of jail")
    </div>
    <div class="metric">
        <strong>Security Updates Applied:</strong> $(grep -c "Security" /var/log/apt/history.log)
    </div>
    
    <h2>Recommendations</h2>
    <ul>
        <li>Review and update firewall rules</li>
        <li>Conduct security awareness training</li>
        <li>Test incident response procedures</li>
    </ul>
</body>
</html>
EOF

    # Email report
    mail -s "Weekly Security Report" \
         -a "$MAINTENANCE_DIR/weekly-report-$(date +%Y%m%d).html" \
         [email protected] < /dev/null
}

# Performance analysis
analyze_performance_metrics() {
    # Collect performance data
    if command -v apache2ctl &> /dev/null; then
        apache2ctl -S > "$MAINTENANCE_DIR/apache-performance.txt"
    fi
    
    if command -v nginx &> /dev/null; then
        nginx -T > "$MAINTENANCE_DIR/nginx-performance.txt"
    fi
    
    # System metrics
    {
        echo "=== System Performance Metrics ==="
        echo "Date: $(date)"
        echo
        echo "CPU Usage:"
        top -bn1 | head -5
        echo
        echo "Memory Usage:"
        free -h
        echo
        echo "Disk I/O:"
        iostat -x 1 1
    } > "$MAINTENANCE_DIR/system-performance.txt"
}

# Update documentation
update_security_documentation() {
    # Generate current configuration documentation
    {
        echo "# Web Server Security Configuration"
        echo "Generated: $(date)"
        echo
        echo "## Current Security Settings"
        echo
        echo "### Firewall Rules"
        ufw status verbose
        echo
        echo "### SSL/TLS Configuration"
        grep -h "SSLProtocol\|ssl_protocols" /etc/apache2/sites-enabled/* /etc/nginx/sites-enabled/* 2>/dev/null
        echo
        echo "### Security Headers"
        grep -h "Header set\|add_header" /etc/apache2/sites-enabled/* /etc/nginx/sites-enabled/* 2>/dev/null | grep -E "(Strict-Transport|X-Frame|X-Content|CSP)"
    } > "$MAINTENANCE_DIR/security-configuration-$(date +%Y%m%d).md"
}

# Schedule tasks based on current date
schedule_tasks() {
    DAY_OF_WEEK=$(date +%u)
    DAY_OF_MONTH=$(date +%d)
    
    # Always run daily tasks
    daily_security_tasks
    
    # Run weekly tasks on Sunday (day 7)
    if [ $DAY_OF_WEEK -eq 7 ]; then
        weekly_security_tasks
    fi
    
    # Run monthly tasks on the 1st
    if [ $DAY_OF_MONTH -eq 1 ]; then
        monthly_security_tasks
    fi
}

# Main execution
log_activity "Security maintenance scheduler started"
schedule_tasks
log_activity "Security maintenance scheduler completed"

# Set up cron if not already configured
CRON_ENTRY="0 2 * * * /usr/local/bin/security-maintenance-scheduler.sh"
if ! crontab -l 2>/dev/null | grep -q "security-maintenance-scheduler"; then
    (crontab -l 2>/dev/null; echo "$CRON_ENTRY") | crontab -
    log_activity "Added security maintenance to crontab"
fi