Fail2ban Setup and Configuration
Installs Fail2ban and configures automatic protection for SSH, Apache, Nginx.
Published: April 10, 2024
Detailed Information
This script installs Fail2ban security tool and configures automatic protection for SSH, Apache, Nginx. Fail2ban monitors failed login attempts and automatically blocks attacker IP addresses.
What Does This Script Do?
This script automates Fail2ban installation and configuration:
- Installs Fail2ban package
- Configures SSH protection
- Configures Apache protection
- Configures Nginx protection
- Starts and enables service
Why Should You Use It?
Fail2ban provides critical protection against brute-force attacks:
- Automatic Blocking: Automatically blocks attacker IPs
- Multi-Service Protection: Protection for SSH, Apache, Nginx
- Configurable: Ban time and retry count adjustable
How to Use
Step-by-Step Usage Guide
1. Run Script
sudo chmod +x fail2ban_setup.sh
sudo ./fail2ban_setup.sh
2. Check Status
sudo fail2ban-client status
sudo fail2ban-client status sshd Requirements
Requirements
- Root Privileges: Script must be run as root
- Python: Required for Fail2ban (usually installed)
Use Cases
Use Cases
1. Brute-Force Protection
Prevent brute-force attacks on SSH and web servers.
2. Production Server Security
Provide automatic security protection on production servers.
Examples
Usage Examples
Example 1: Basic Usage
sudo ./fail2ban_setup.sh Code
#!/bin/bash
# Fail2ban Setup Script
if [ "$EUID" -ne 0 ]; then
echo "Please run as root"
exit 1
fi
echo "Installing Fail2ban..."
if command -v apt-get &> /dev/null; then
apt-get update
apt-get install -y fail2ban
elif command -v yum &> /dev/null; then
yum install -y epel-release
yum install -y fail2ban
fi
cat > /etc/fail2ban/jail.local << EOF
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 5
destemail = admin@localhost
sendername = Fail2Ban
action = %(action_mwl)s
[sshd]
enabled = true
port = ssh
logpath = /var/log/auth.log
maxretry = 3
[apache-auth]
enabled = true
port = http,https
logpath = /var/log/apache*/*error.log
[nginx-http-auth]
enabled = true
port = http,https
logpath = /var/log/nginx/error.log
[nginx-noscript]
enabled = true
port = http,https
logpath = /var/log/nginx/access.log
[nginx-badbots]
enabled = true
port = http,https
logpath = /var/log/nginx/access.log
[nginx-noproxy]
enabled = true
port = http,https
logpath = /var/log/nginx/access.log
EOF
systemctl enable fail2ban
systemctl start fail2ban
echo "✓ Fail2ban installed and configured!"
echo ""
echo "Check status: fail2ban-client status"
echo "Check banned IPs: fail2ban-client status sshd"
echo "Unban IP: fail2ban-client set sshd unbanip <IP>"
Usage
sudo chmod +x fail2ban_setup.sh
sudo ./fail2ban_setup.sh
# Check status
sudo fail2ban-client status
sudo fail2ban-client status sshd
Troubleshooting
Troubleshooting
Problem: Fail2ban not running
Solution: Check service:
sudo systemctl status fail2ban
sudo systemctl restart fail2ban