Script 14 · Security
14. Fail2ban Config
Installs Fail2ban and creates an interactive SSH jail configuration for brute-force protection.
Category: Security
Risk: Low
Lines: calculating
Language: Bash / Linux
What this script does
- Block repeated failed SSH logins.
- Customize ban duration, findtime, and retry threshold.
- Enable Fail2ban at boot.
Prerequisites
- Root access
- SSH logs available
- fail2ban package repository access
Execution flow
- Installs fail2ban
- Prompts for bantime/findtime/maxretry
- Writes jail.local
- Restarts and enables fail2ban
Validation checklist
- fail2ban-client status
- fail2ban-client status sshd
- systemctl status fail2ban
Operational cautions
- Permanent bans can lock out legitimate IPs.
- Changing SSH ports later requires jail update.
Original script notes
ℹ️ Script Info: Installs and configures Fail2ban to protect your SSH port from brute-force attacks by automatically blocking IP addresses that fail to log in multiple times.
cat << 'EOF' > setup_fail2ban.sh && chmod +x setup_fail2ban.sh && ./setup_fail2ban.sh
#!/bin/bash
sudo apt-get update -q && sudo apt-get install -y fail2ban && \
echo -e "\n\033[1;32m=== FAIL2BAN INTERACTIVE CONFIGURATION ===\033[0m" && \
read -p "1. BANTIME (Ban Duration):
- Enter number in DAYS (e.g., 1 for 1 day, 7 for a week).
- OR type '-1' to ban PERMANENTLY.
>> Enter your choice: " INPUT_DAYS && \
if [ "$INPUT_DAYS" == "-1" ]; then REAL_BANTIME="-1"; else REAL_BANTIME=$((INPUT_DAYS * 86400)); fi && \
read -p "
2. FINDTIME (Time Window):
- How long should the system remember login failures?
- Example: '10m' (If failed 3x within 10 mins, then ban).
>> Enter time (e.g., 10m): " REAL_FINDTIME && \
read -p "
3. MAXRETRY (Max Retries):
- How many wrong passwords allowed before banning?
- Example: '3' or '5'.
>> Enter number (e.g., 3): " REAL_MAXRETRY && \
echo -e "\n\033[1;33mApplying configuration...\033[0m" && \
sudo bash -c "cat > /etc/fail2ban/jail.local <<EOF
[DEFAULT]
# Global Configuration
bantime = $REAL_BANTIME
findtime = $REAL_FINDTIME
maxretry = $REAL_MAXRETRY
[sshd]
# SSH Jail Enabled Automatically
enabled = true
port = ssh
logpath = %(sshd_log)s
backend = %(sshd_backend)s
EOF" && \
sudo systemctl restart fail2ban && sudo systemctl enable fail2ban && \
echo -e "\n\033[1;32m=== DONE! CURRENT SSH JAIL STATUS ===\033[0m" && \
sudo fail2ban-client status sshd
EOF