fail2ban-setup
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseFail2ban 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 -ybash
sudo apt update
sudo apt install fail2ban -yCentOS/RHEL
CentOS/RHEL
bash
sudo yum install epel-release -y
sudo yum install fail2ban -ybash
sudo yum install epel-release -y
sudo yum install fail2ban -yVerify Installation
验证安装
bash
sudo systemctl status fail2banbash
sudo systemctl status fail2banBasic Configuration
基础配置
Step 1: Create Local Configuration
步骤1:创建本地配置文件
CRITICAL: Never edit directly. It gets overwritten on updates!
jail.confCreate a local configuration file:
bash
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.localEdit 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.localStep 2: Configure Global Settings
步骤2:配置全局设置
Find and update these settings in :
jail.localini
[DEFAULT]在中找到并更新以下设置:
jail.localini
[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
undefinedundefinedStep 3: Configure SSH Protection
步骤3:配置SSH防护
Find the section and configure:
[sshd]ini
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
findtime = 600For 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 = 3Step 4: Enable and Start Fail2ban
步骤4:启用并启动Fail2ban
bash
sudo systemctl enable fail2ban
sudo systemctl start fail2banVerify it's running:
bash
sudo systemctl status fail2banbash
sudo systemctl enable fail2ban
sudo systemctl start fail2ban验证服务运行状态:
bash
sudo systemctl status fail2banAdvanced Configuration
高级配置
Multiple Service Protection
多服务防护
Add jails for other services in :
/etc/fail2ban/jail.localNginx/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 = 3WordPress:
ini
[wordpress-auth]
enabled = true
port = http,https
filter = wordpress-auth
logpath = /var/log/auth.log
maxretry = 3FTP:
ini
[proftpd]
enabled = true
port = ftp,ftp-data,ftps,ftps-data
filter = proftpd
logpath = /var/log/proftpd/proftpd.log
maxretry = 3在中添加其他服务的规则(jail):
/etc/fail2ban/jail.localNginx/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 = 3WordPress:
ini
[wordpress-auth]
enabled = true
port = http,https
filter = wordpress-auth
logpath = /var/log/auth.log
maxretry = 3FTP:
ini
[proftpd]
enabled = true
port = ftp,ftp-data,ftps,ftps-data
filter = proftpd
logpath = /var/log/proftpd/proftpd.log
maxretry = 3Custom 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 = 3Whitelist 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/24Email Notifications
邮件通知
Enable email alerts:
ini
[DEFAULT]
destemail = admin@example.com
sendername = Fail2Ban
mta = sendmail启用邮件告警:
ini
[DEFAULT]
destemail = admin@example.com
sendername = Fail2Ban
mta = sendmailAction with email
带邮件通知的动作
action = %(action_mwl)s
undefinedaction = %(action_mwl)s
undefinedFail2ban Management
Fail2ban 管理
Check Status
查看状态
bash
undefinedbash
undefinedOverall status
整体状态
sudo fail2ban-client status
sudo fail2ban-client status
Specific jail status
特定规则状态
sudo fail2ban-client status sshd
undefinedsudo fail2ban-client status sshd
undefinedView Banned IPs
查看已封禁IP
bash
undefinedbash
undefinedList 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
undefinedsudo fail2ban-client banned
undefinedUnban IP Address
解封IP地址
bash
undefinedbash
undefinedUnban 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
undefinedsudo fail2ban-client unban 203.0.113.100
undefinedManually Ban IP
手动封禁IP
bash
sudo fail2ban-client set sshd banip 203.0.113.100bash
sudo fail2ban-client set sshd banip 203.0.113.100Test 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.confMonitoring and Logs
监控与日志
Fail2ban Logs
Fail2ban 日志
bash
undefinedbash
undefinedView 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
undefinedsudo grep "Unban" /var/log/fail2ban.log
undefinedCheck Firewall Rules
检查防火墙规则
Fail2ban adds rules to iptables/UFW:
bash
undefinedFail2ban会向iptables/UFW添加规则:
bash
undefinedView 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
undefinedsudo ufw status numbered
undefinedStatistics
统计信息
bash
undefinedbash
undefinedCount 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"
undefinedsudo fail2ban-client status sshd | grep "Total banned"
undefinedConfiguration 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:
- Create filter file :
/etc/fail2ban/filter.d/myapp.conf
ini
[Definition]
failregex = ^.*Failed login attempt from <HOST>.*$
^.*Invalid user .* from <HOST>.*$
ignoreregex =- 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- Test the filter:
bash
fail2ban-regex /var/log/myapp/access.log /etc/fail2ban/filter.d/myapp.conf- Reload fail2ban:
bash
sudo systemctl reload fail2ban为你的应用创建自定义过滤器:
- 创建过滤器文件:
/etc/fail2ban/filter.d/myapp.conf
ini
[Definition]
failregex = ^.*Failed login attempt from <HOST>.*$
^.*Invalid user .* from <HOST>.*$
ignoreregex =- 在中添加对应规则:
/etc/fail2ban/jail.local
ini
[myapp]
enabled = true
port = 8080
filter = myapp
logpath = /var/log/myapp/access.log
maxretry = 5
bantime = 3600- 测试过滤器:
bash
fail2ban-regex /var/log/myapp/access.log /etc/fail2ban/filter.d/myapp.conf- 重新加载fail2ban:
bash
sudo systemctl reload fail2banRestart and Reload
重启与重新加载
Restart Service
重启服务
bash
undefinedbash
undefinedRestart fail2ban
重启fail2ban
sudo systemctl restart fail2ban
sudo systemctl restart fail2ban
Check status
检查状态
sudo systemctl status fail2ban
undefinedsudo systemctl status fail2ban
undefinedReload Configuration
重新加载配置
bash
undefinedbash
undefinedReload without restarting (keeps existing bans)
重新加载配置(不重启服务,保留现有封禁)
sudo fail2ban-client reload
sudo fail2ban-client reload
Reload specific jail
重新加载特定规则
sudo fail2ban-client reload sshd
undefinedsudo fail2ban-client reload sshd
undefinedSecurity Best Practices
安全最佳实践
- Start with conservative settings - Don't ban too aggressively
- Whitelist trusted IPs - Add your office/home IP to ignoreip
- Monitor logs - Regularly check
/var/log/fail2ban.log - Test filters - Use fail2ban-regex to test before deploying
- Combine with SSH hardening - Fail2ban is not a replacement for proper SSH config
- Set reasonable ban times - Too short is ineffective, too long may ban legitimate users
- Enable recidive jail - Catch repeated offenders
- Keep fail2ban updated - Update regularly for new attack patterns
- 初始使用保守设置 - 不要过于激进地封禁IP
- 添加可信IP到白名单 - 将办公/家庭IP添加到ignoreip
- 监控日志 - 定期查看
/var/log/fail2ban.log - 测试过滤器 - 部署前使用fail2ban-regex测试
- 配合SSH加固 - Fail2ban不能替代完善的SSH配置
- 设置合理封禁时长 - 过短无效,过长可能误封合法用户
- 启用recidive规则 - 拦截多次违规的IP
- 保持fail2ban更新 - 定期更新以应对新攻击模式
Troubleshooting
故障排除
Fail2ban Not Starting
Fail2ban无法启动
bash
undefinedbash
undefinedCheck 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
undefinedsudo fail2ban-client -d
undefinedJails Not Working
规则不生效
bash
undefinedbash
undefinedCheck 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
undefinedfail2ban-regex /var/log/auth.log /etc/fail2ban/filter.d/sshd.conf
undefinedLog File Not Found
日志文件未找到
Check log paths in jail configuration:
bash
undefined检查规则配置中的日志路径:
bash
undefinedUbuntu/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
undefinedAccidentally Banned
被误封
bash
undefinedbash
undefinedUnban 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
undefinedsudo systemctl stop fail2ban
undefinedCommon Mistakes to Avoid
常见错误规避
- ❌ Editing instead of creating
jail.confjail.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.confjail.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
相关技能
- - Harden SSH before adding fail2ban
ssh-hardening - - Fail2ban works with UFW/iptables
firewall-configuration - - Keep fail2ban updated
auto-updates
- - 配置fail2ban前先加固SSH
ssh-hardening - - Fail2ban可与UFW/iptables配合使用
firewall-configuration - - 保持fail2ban更新
auto-updates