Responding to Security Events

Responding to Security Events

Create incident response procedures:

# Automated response script
cat > /usr/local/bin/security-response.sh << 'EOF'
#!/bin/bash
# Security incident response script

LOGFILE="/var/log/security-response.log"
ADMIN_EMAIL="[email protected]"

log_event() {
    echo "[$(date)] $1" >> "$LOGFILE"
}

block_ip() {
    IP=$1
    REASON=$2
    
    # Add to firewall
    sudo ufw insert 1 deny from $IP to any
    
    # Add to ipset
    sudo ipset add blocked_ips $IP
    
    # Log event
    log_event "Blocked IP $IP - Reason: $REASON"
    
    # Send alert
    echo "IP $IP has been blocked. Reason: $REASON" | mail -s "Security Alert: IP Blocked" $ADMIN_EMAIL
}

# Check for brute force attacks
check_bruteforce() {
    # Check SSH logs
    suspicious_ssh=$(journalctl -u ssh --since "10 minutes ago" | grep -c "Failed password")
    if [ $suspicious_ssh -gt 10 ]; then
        log_event "Detected SSH brute force attack"
        # Extract IPs and block them
        journalctl -u ssh --since "10 minutes ago" | grep "Failed password" | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | sort | uniq -c | while read count ip; do
            if [ $count -gt 5 ]; then
                block_ip $ip "SSH brute force"
            fi
        done
    fi
}

# Check for web scanners
check_scanners() {
    # Check web logs for scanning patterns
    if [ -f /var/log/nginx/access.log ]; then
        grep -E "(sqlmap|nikto|nmap|masscan|wpscan)" /var/log/nginx/access.log | grep -oE '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | sort | uniq | while read ip; do
            block_ip $ip "Vulnerability scanner detected"
        done
    fi
}

# Main execution
check_bruteforce
check_scanners

# Report status
echo "Security check completed at $(date)" >> "$LOGFILE"
EOF

sudo chmod +x /usr/local/bin/security-response.sh

# Add to crontab
echo "*/5 * * * * /usr/local/bin/security-response.sh" | sudo crontab -

Implementing comprehensive firewall rules combined with Fail2ban creates a dynamic security perimeter that adapts to threats in real-time. Regular monitoring and tuning ensure your defenses remain effective without impacting legitimate users. The next chapter will explore performance optimization strategies that enhance both security and server responsiveness.## Performance Optimization with Security in Mind

Optimizing web server performance while maintaining robust security requires careful balance and strategic configuration. This chapter explores how to enhance Apache and Nginx performance without compromising security, covering caching strategies, compression, connection handling, and resource optimization. We'll demonstrate that security and performance are not mutually exclusive—properly implemented security measures can actually improve performance by preventing resource-draining attacks and optimizing server behavior.