feat(security): 添加fail2ban集成防止暴力破解登录

- 新增fail2ban过滤器和监狱配置文件
- 修改登录视图记录客户端IP和认证失败日志
- 更新日志配置添加syslog处理器用于fail2ban检测
- 在README中添加fail2ban配置和使用文档
This commit is contained in:
2026-01-28 22:44:36 +08:00
parent f7692a6db6
commit ae95844177
5 changed files with 411 additions and 9 deletions

View File

@@ -0,0 +1,20 @@
# Fail2Ban filter for diary-family Django application
# 用于检测家庭日报系统登录失败的规则
[Definition]
# 匹配登录失败的日志行
# 日志格式: django.security.login: WARNING Authentication failure for username: xxx from IP: xxx.xxx.xxx.xxx
failregex = ^.*Authentication failure for username: .* from IP: <HOST>.*$
# 可选:匹配其他认证失败模式(如被禁用的用户)
# failregex = ^%(__prefix_line)s.*Authentication failure for username: .* from IP: <HOST>.*$
# ^%(__prefix_line)s.*Invalid login attempt from IP: <HOST>.*$
# 忽略正则(可选)
# ignoreregex =
[Init]
# 日期格式(如果需要)
# datepattern = %%Y-%%m-%%d %%H:%%M:%%S

View File

@@ -0,0 +1,62 @@
# Fail2Ban jail configuration for diary-family Django application
# 家庭日报系统 fail2ban 监狱配置
[diary-family]
# 启用该监狱
enabled = true
# 监狱名称和过滤器
filter = diary-family
# 要监控的日志文件路径
# 如果使用syslog可以设置为 /var/log/syslog 或 /var/log/messages
# 如果使用文件日志,设置为 Django 项目的 auth.log 路径
logpath = /var/log/syslog
/var/www/diary-family/logs/auth.log
# 触发封禁前的最大失败次数
maxretry = 5
# 封禁时间(秒)- 默认1小时3600秒
# 可以设置为:
# - 3600 = 1小时
# - 86400 = 1天
# - 604800 = 1周
# - -1 = 永久封禁
bantime = 3600
# 检测时间窗口(秒)- 在多长时间内计算失败次数
# 例如findtime = 600 表示在10分钟内失败 maxretry 次则封禁
findtime = 600
# 忽略的IP地址白名单
# 可以添加本地网络、办公网络等不需要封禁的IP
ignoreip = 127.0.0.1/8 ::1
# 192.168.1.0/24 # 本地网络示例
# 10.0.0.0/8 # 内网示例
# 使用的封禁动作
# 默认使用 iptables 封禁所有端口
# 可选动作:
# - iptables-allports: 封禁所有端口
# - iptables-multiport: 封禁指定端口
# - nftables-allports: 使用 nftables 封禁
# - ufw: 使用 UFW 防火墙
# - cloudflare: 封禁 Cloudflare 上的IP
banaction = iptables-allports
# 发送邮件通知(可选)
# 需要配置邮件服务器
# destemail = admin@example.com
# sender = fail2ban@example.com
# mta = sendmail
# action = %(action_mwl)s # 发送邮件并记录日志
# 后端选择
# - auto: 自动选择(推荐)
# - systemd: 使用 systemd journal
# - polling: 轮询模式
backend = auto
# 端口(用于 multiport 动作)
port = 80,443,8000