fail2ban-setup

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Fail2ban Setup Skill

Fail2ban 配置技能

Configure fail2ban to automatically protect servers against brute-force attacks by banning malicious IP addresses.
配置fail2ban以自动封禁恶意IP地址,保护服务器免受暴力破解攻击。

What This Skill Does

本技能的作用

This skill helps AI agents install and configure fail2ban on VPS servers. Even with SSH keys configured, bots will constantly hammer your server with login attempts. Fail2ban monitors log files and automatically bans IP addresses that show malicious behavior, such as too many password failures.
Key capabilities:
  • Install fail2ban package
  • Configure SSH brute-force protection
  • Set ban times and retry thresholds
  • Create custom jails for different services
  • Monitor and manage banned IPs
  • Integrate with UFW/iptables firewall
本技能帮助AI Agent在VPS服务器上安装和配置fail2ban。即使已配置SSH密钥,机器人仍会持续尝试登录服务器。Fail2ban会监控日志文件,并自动封禁存在恶意行为的IP地址,例如多次密码验证失败。
核心功能:
  • 安装fail2ban包
  • 配置SSH暴力破解防护
  • 设置封禁时长和重试阈值
  • 为不同服务创建自定义规则(jail)
  • 监控和管理已封禁IP
  • 与UFW/iptables防火墙集成

When to Use

使用场景

Use this skill when you need to:
  • Protect SSH from brute-force attacks
  • Reduce server load from automated login attempts
  • Automatically block malicious IPs
  • Complement SSH hardening and firewall configuration
  • Monitor authentication logs for suspicious activity
  • Protect web applications from abuse
Critical understanding: Three failed attempts in 10 minutes = banned for an hour. This drastically reduces brute-force attack effectiveness.
当你需要以下功能时使用本技能:
  • 保护SSH免受暴力破解攻击
  • 减少自动化登录尝试带来的服务器负载
  • 自动拦截恶意IP
  • 配合SSH加固和防火墙配置使用
  • 监控认证日志中的可疑活动
  • 保护Web应用免受滥用
重要说明: 10分钟内3次尝试失败 = 封禁1小时。这能大幅降低暴力破解攻击的有效性。

Prerequisites

前置条件

  • Root or sudo access to the server
  • Ubuntu, Debian, or RHEL-based Linux distribution
  • SSH access to the server
  • Firewall configured (UFW or iptables)
  • Services to protect (SSH, web server, etc.) running and logging
  • 服务器的Root或sudo访问权限
  • 基于Ubuntu、Debian或RHEL的Linux发行版
  • 服务器的SSH访问权限
  • 已配置防火墙(UFW或iptables)
  • 待保护的服务(SSH、Web服务器等)已运行并开启日志记录

Fail2ban Installation

Fail2ban 安装

Ubuntu/Debian

Ubuntu/Debian

bash
sudo apt update
sudo apt install fail2ban -y
bash
sudo apt update
sudo apt install fail2ban -y

CentOS/RHEL

CentOS/RHEL

bash
sudo yum install epel-release -y
sudo yum install fail2ban -y
bash
sudo yum install epel-release -y
sudo yum install fail2ban -y

Verify Installation

验证安装

bash
sudo systemctl status fail2ban
bash
sudo systemctl status fail2ban

Basic Configuration

基础配置

Step 1: Create Local Configuration

步骤1:创建本地配置文件

CRITICAL: Never edit
jail.conf
directly. It gets overwritten on updates!
Create a local configuration file:
bash
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
Edit the local configuration:
bash
sudo nano /etc/fail2ban/jail.local
重要提示: 切勿直接编辑
jail.conf
,它会在更新时被覆盖!
创建本地配置文件:
bash
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
编辑本地配置文件:
bash
sudo nano /etc/fail2ban/jail.local

Step 2: Configure Global Settings

步骤2:配置全局设置

Find and update these settings in
jail.local
:
ini
[DEFAULT]
jail.local
中找到并更新以下设置:
ini
[DEFAULT]

Ban time in seconds (1 hour)

封禁时长(秒),1小时

bantime = 3600
bantime = 3600

Find time window (10 minutes)

检测时间窗口(10分钟)

findtime = 600
findtime = 600

Number of failures before ban

封禁前的失败尝试次数

maxretry = 3
maxretry = 3

Destination email for notifications (optional)

通知接收邮箱(可选)

destemail = admin@example.com
destemail = admin@example.com

Sender email

发件人名称

sendername = Fail2Ban
sendername = Fail2Ban

Email action

执行动作

action = %(action_)s
action = %(action_)s

Or with email: %(action_mwl)s

如需邮件通知,使用:%(action_mwl)s

undefined
undefined

Step 3: Configure SSH Protection

步骤3:配置SSH防护

Find the
[sshd]
section and configure:
ini
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
findtime = 600
For custom SSH port:
ini
[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
找到
[sshd]
部分并进行配置:
ini
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
findtime = 600
自定义SSH端口时:
ini
[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
maxretry = 3

Step 4: Enable and Start Fail2ban

步骤4:启用并启动Fail2ban

bash
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
Verify it's running:
bash
sudo systemctl status fail2ban
bash
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
验证服务运行状态:
bash
sudo systemctl status fail2ban

Advanced Configuration

高级配置

Multiple Service Protection

多服务防护

Add jails for other services in
/etc/fail2ban/jail.local
:
Nginx/Apache (HTTP Auth):
ini
[nginx-http-auth]
enabled = true
port = http,https
filter = nginx-http-auth
logpath = /var/log/nginx/error.log
maxretry = 3

[apache-auth]
enabled = true
port = http,https
filter = apache-auth
logpath = /var/log/apache*/*error.log
maxretry = 3
WordPress:
ini
[wordpress-auth]
enabled = true
port = http,https
filter = wordpress-auth
logpath = /var/log/auth.log
maxretry = 3
FTP:
ini
[proftpd]
enabled = true
port = ftp,ftp-data,ftps,ftps-data
filter = proftpd
logpath = /var/log/proftpd/proftpd.log
maxretry = 3
/etc/fail2ban/jail.local
中添加其他服务的规则(jail):
Nginx/Apache(HTTP认证):
ini
[nginx-http-auth]
enabled = true
port = http,https
filter = nginx-http-auth
logpath = /var/log/nginx/error.log
maxretry = 3

[apache-auth]
enabled = true
port = http,https
filter = apache-auth
logpath = /var/log/apache*/*error.log
maxretry = 3
WordPress:
ini
[wordpress-auth]
enabled = true
port = http,https
filter = wordpress-auth
logpath = /var/log/auth.log
maxretry = 3
FTP:
ini
[proftpd]
enabled = true
port = ftp,ftp-data,ftps,ftps-data
filter = proftpd
logpath = /var/log/proftpd/proftpd.log
maxretry = 3

Custom Ban Times

自定义封禁时长

Different ban times for different severity:
ini
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600      # 1 hour
findtime = 600      # 10 minutes

[sshd-aggressive]
enabled = true
port = ssh
filter = sshd-aggressive
logpath = /var/log/auth.log
maxretry = 1
bantime = 86400     # 24 hours
findtime = 3600     # 1 hour
针对不同严重程度设置不同封禁时长:
ini
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600      # 1小时
findtime = 600      # 10分钟

[sshd-aggressive]
enabled = true
port = ssh
filter = sshd-aggressive
logpath = /var/log/auth.log
maxretry = 1
bantime = 86400     # 24小时
findtime = 3600     # 1小时

Permanent Bans

永久封禁

For repeated offenders:
ini
[recidive]
enabled = true
filter = recidive
logpath = /var/log/fail2ban.log
bantime = 604800    # 1 week
findtime = 86400    # 1 day
maxretry = 3
针对多次违规的IP:
ini
[recidive]
enabled = true
filter = recidive
logpath = /var/log/fail2ban.log
bantime = 604800    # 1周
findtime = 86400    # 1天
maxretry = 3

Whitelist IPs

IP白名单

Never ban trusted IPs:
ini
[DEFAULT]
ignoreip = 127.0.0.1/8 ::1 203.0.113.10 192.168.1.0/24
永不封禁可信IP:
ini
[DEFAULT]
ignoreip = 127.0.0.1/8 ::1 203.0.113.10 192.168.1.0/24

Email Notifications

邮件通知

Enable email alerts:
ini
[DEFAULT]
destemail = admin@example.com
sendername = Fail2Ban
mta = sendmail
启用邮件告警:
ini
[DEFAULT]
destemail = admin@example.com
sendername = Fail2Ban
mta = sendmail

Action with email

带邮件通知的动作

action = %(action_mwl)s
undefined
action = %(action_mwl)s
undefined

Fail2ban Management

Fail2ban 管理

Check Status

查看状态

bash
undefined
bash
undefined

Overall status

整体状态

sudo fail2ban-client status
sudo fail2ban-client status

Specific jail status

特定规则状态

sudo fail2ban-client status sshd
undefined
sudo fail2ban-client status sshd
undefined

View Banned IPs

查看已封禁IP

bash
undefined
bash
undefined

List banned IPs for SSH

查看SSH规则下的封禁IP

sudo fail2ban-client status sshd
sudo fail2ban-client status sshd

List all banned IPs

查看所有封禁IP

sudo fail2ban-client banned
undefined
sudo fail2ban-client banned
undefined

Unban IP Address

解封IP地址

bash
undefined
bash
undefined

Unban specific IP from specific jail

从特定规则中解封指定IP

sudo fail2ban-client set sshd unbanip 203.0.113.100
sudo fail2ban-client set sshd unbanip 203.0.113.100

Unban from all jails

从所有规则中解封IP

sudo fail2ban-client unban 203.0.113.100
undefined
sudo fail2ban-client unban 203.0.113.100
undefined

Manually Ban IP

手动封禁IP

bash
sudo fail2ban-client set sshd banip 203.0.113.100
bash
sudo fail2ban-client set sshd banip 203.0.113.100

Test Filter

测试过滤器

Test if a filter matches log lines:
bash
fail2ban-regex /var/log/auth.log /etc/fail2ban/filter.d/sshd.conf
测试过滤器是否匹配日志行:
bash
fail2ban-regex /var/log/auth.log /etc/fail2ban/filter.d/sshd.conf

Monitoring and Logs

监控与日志

Fail2ban Logs

Fail2ban 日志

bash
undefined
bash
undefined

View fail2ban log

查看fail2ban日志

sudo tail -f /var/log/fail2ban.log
sudo tail -f /var/log/fail2ban.log

View recent bans

查看近期封禁记录

sudo grep "Ban" /var/log/fail2ban.log
sudo grep "Ban" /var/log/fail2ban.log

View unbans

查看解封记录

sudo grep "Unban" /var/log/fail2ban.log
undefined
sudo grep "Unban" /var/log/fail2ban.log
undefined

Check Firewall Rules

检查防火墙规则

Fail2ban adds rules to iptables/UFW:
bash
undefined
Fail2ban会向iptables/UFW添加规则:
bash
undefined

View iptables rules

查看iptables规则

sudo iptables -L -n
sudo iptables -L -n

View fail2ban chains

查看fail2ban规则链

sudo iptables -L fail2ban-sshd -n
sudo iptables -L fail2ban-sshd -n

View UFW status

查看UFW状态

sudo ufw status numbered
undefined
sudo ufw status numbered
undefined

Statistics

统计信息

bash
undefined
bash
undefined

Count bans by jail

按规则统计封禁次数

sudo fail2ban-client status | grep "Jail list"
sudo fail2ban-client status | grep "Jail list"

Count current bans

查看当前封禁数量

sudo fail2ban-client status sshd | grep "Currently banned"
sudo fail2ban-client status sshd | grep "Currently banned"

Total bans

查看总封禁数量

sudo fail2ban-client status sshd | grep "Total banned"
undefined
sudo fail2ban-client status sshd | grep "Total banned"
undefined

Configuration Files

配置文件说明

Main Configuration Files

主配置文件

/etc/fail2ban/fail2ban.conf      # Main fail2ban configuration
/etc/fail2ban/fail2ban.local     # Local fail2ban config (create if needed)
/etc/fail2ban/jail.conf          # Default jail configurations (don't edit!)
/etc/fail2ban/jail.local         # Local jail overrides (edit this!)
/etc/fail2ban/jail.d/            # Additional jail configs
/etc/fail2ban/fail2ban.conf      # Fail2ban主配置文件
/etc/fail2ban/fail2ban.local     # Fail2ban本地配置文件(按需创建)
/etc/fail2ban/jail.conf          # 默认规则配置文件(请勿编辑!)
/etc/fail2ban/jail.local         # 本地规则覆盖配置文件(编辑此文件!)
/etc/fail2ban/jail.d/            # 额外规则配置目录

Filters and Actions

过滤器与动作

/etc/fail2ban/filter.d/          # Log file filters
/etc/fail2ban/action.d/          # Ban actions (iptables, ufw, etc.)
/var/log/fail2ban.log            # Fail2ban log file
/etc/fail2ban/filter.d/          # 日志文件过滤器目录
/etc/fail2ban/action.d/          # 封禁动作目录(iptables、ufw等)
/var/log/fail2ban.log            # Fail2ban日志文件

Creating Custom Filters

创建自定义过滤器

Create a custom filter for your application:
  1. Create filter file
    /etc/fail2ban/filter.d/myapp.conf
    :
ini
[Definition]
failregex = ^.*Failed login attempt from <HOST>.*$
            ^.*Invalid user .* from <HOST>.*$
ignoreregex =
  1. Create jail in
    /etc/fail2ban/jail.local
    :
ini
[myapp]
enabled = true
port = 8080
filter = myapp
logpath = /var/log/myapp/access.log
maxretry = 5
bantime = 3600
  1. Test the filter:
bash
fail2ban-regex /var/log/myapp/access.log /etc/fail2ban/filter.d/myapp.conf
  1. Reload fail2ban:
bash
sudo systemctl reload fail2ban
为你的应用创建自定义过滤器:
  1. 创建过滤器文件
    /etc/fail2ban/filter.d/myapp.conf
ini
[Definition]
failregex = ^.*Failed login attempt from <HOST>.*$
            ^.*Invalid user .* from <HOST>.*$
ignoreregex =
  1. /etc/fail2ban/jail.local
    中添加对应规则:
ini
[myapp]
enabled = true
port = 8080
filter = myapp
logpath = /var/log/myapp/access.log
maxretry = 5
bantime = 3600
  1. 测试过滤器:
bash
fail2ban-regex /var/log/myapp/access.log /etc/fail2ban/filter.d/myapp.conf
  1. 重新加载fail2ban:
bash
sudo systemctl reload fail2ban

Restart and Reload

重启与重新加载

Restart Service

重启服务

bash
undefined
bash
undefined

Restart fail2ban

重启fail2ban

sudo systemctl restart fail2ban
sudo systemctl restart fail2ban

Check status

检查状态

sudo systemctl status fail2ban
undefined
sudo systemctl status fail2ban
undefined

Reload Configuration

重新加载配置

bash
undefined
bash
undefined

Reload without restarting (keeps existing bans)

重新加载配置(不重启服务,保留现有封禁)

sudo fail2ban-client reload
sudo fail2ban-client reload

Reload specific jail

重新加载特定规则

sudo fail2ban-client reload sshd
undefined
sudo fail2ban-client reload sshd
undefined

Security Best Practices

安全最佳实践

  1. Start with conservative settings - Don't ban too aggressively
  2. Whitelist trusted IPs - Add your office/home IP to ignoreip
  3. Monitor logs - Regularly check
    /var/log/fail2ban.log
  4. Test filters - Use fail2ban-regex to test before deploying
  5. Combine with SSH hardening - Fail2ban is not a replacement for proper SSH config
  6. Set reasonable ban times - Too short is ineffective, too long may ban legitimate users
  7. Enable recidive jail - Catch repeated offenders
  8. Keep fail2ban updated - Update regularly for new attack patterns
  1. 初始使用保守设置 - 不要过于激进地封禁IP
  2. 添加可信IP到白名单 - 将办公/家庭IP添加到ignoreip
  3. 监控日志 - 定期查看
    /var/log/fail2ban.log
  4. 测试过滤器 - 部署前使用fail2ban-regex测试
  5. 配合SSH加固 - Fail2ban不能替代完善的SSH配置
  6. 设置合理封禁时长 - 过短无效,过长可能误封合法用户
  7. 启用recidive规则 - 拦截多次违规的IP
  8. 保持fail2ban更新 - 定期更新以应对新攻击模式

Troubleshooting

故障排除

Fail2ban Not Starting

Fail2ban无法启动

bash
undefined
bash
undefined

Check for syntax errors

检查语法错误

sudo fail2ban-client -t
sudo fail2ban-client -t

View error logs

查看错误日志

sudo journalctl -u fail2ban -n 50
sudo journalctl -u fail2ban -n 50

Check configuration

检查配置

sudo fail2ban-client -d
undefined
sudo fail2ban-client -d
undefined

Jails Not Working

规则不生效

bash
undefined
bash
undefined

Check jail status

检查规则状态

sudo fail2ban-client status
sudo fail2ban-client status

View jail configuration

查看规则配置

sudo fail2ban-client get sshd maxretry sudo fail2ban-client get sshd bantime
sudo fail2ban-client get sshd maxretry sudo fail2ban-client get sshd bantime

Test filter against log

测试过滤器与日志匹配度

fail2ban-regex /var/log/auth.log /etc/fail2ban/filter.d/sshd.conf
undefined
fail2ban-regex /var/log/auth.log /etc/fail2ban/filter.d/sshd.conf
undefined

Log File Not Found

日志文件未找到

Check log paths in jail configuration:
bash
undefined
检查规则配置中的日志路径:
bash
undefined

Ubuntu/Debian SSH logs

Ubuntu/Debian SSH日志路径

/var/log/auth.log
/var/log/auth.log

CentOS/RHEL SSH logs

CentOS/RHEL SSH日志路径

/var/log/secure
/var/log/secure

Nginx logs

Nginx日志路径

/var/log/nginx/error.log /var/log/nginx/access.log
undefined
/var/log/nginx/error.log /var/log/nginx/access.log
undefined

Accidentally Banned

被误封

bash
undefined
bash
undefined

Unban your IP

解封你的IP

sudo fail2ban-client set sshd unbanip YOUR.IP.ADDRESS
sudo fail2ban-client set sshd unbanip YOUR.IP.ADDRESS

Or stop fail2ban temporarily

或临时停止fail2ban

sudo systemctl stop fail2ban
undefined
sudo systemctl stop fail2ban
undefined

Common Mistakes to Avoid

常见错误规避

  • ❌ Editing
    jail.conf
    instead of creating
    jail.local
  • ❌ Not whitelisting your own IP address
  • ❌ Setting maxretry too low (banning legitimate users)
  • ❌ Not testing filters before deployment
  • ❌ Forgetting to restart after configuration changes
  • ❌ Using fail2ban as sole security measure (combine with other hardening!)
  • ❌ Not monitoring fail2ban logs
  • ❌ 直接编辑
    jail.conf
    而非创建
    jail.local
  • ❌ 未将自己的IP添加到白名单
  • ❌ maxretry设置过低(误封合法用户)
  • ❌ 部署前未测试过滤器
  • ❌ 配置变更后忘记重启服务
  • ❌ 将fail2ban作为唯一安全措施(需配合其他加固手段!)
  • ❌ 未监控fail2ban日志

Additional Resources

额外资源

See references/fail2ban-filters.md for common filter patterns.
See scripts/setup-fail2ban.sh for automated setup script.
查看references/fail2ban-filters.md获取常见过滤器模式。
查看scripts/setup-fail2ban.sh获取自动化部署脚本。

Related Skills

相关技能

  • ssh-hardening
    - Harden SSH before adding fail2ban
  • firewall-configuration
    - Fail2ban works with UFW/iptables
  • auto-updates
    - Keep fail2ban updated
  • ssh-hardening
    - 配置fail2ban前先加固SSH
  • firewall-configuration
    - Fail2ban可与UFW/iptables配合使用
  • auto-updates
    - 保持fail2ban更新