结合fail2ban屏蔽nginx攻击

本文介绍了如何在Linux系统中安装、配置fail2ban,包括设置nginx日志、自定义filter、启用服务、查看状态、添加白名单和规则,以及使用iptables进行HTTP错误404访问限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安装fail2ban

#yum install fail2ban -y
#systemctl start fail2ban
#systemctl enable fail2ban

开启nginx日志

1. /soft/tengine/conf/nginx.conf

    log_format  main  ' $remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_x_forwarded_for" "$http_referer" '
                      '"$http_user_agent"  "$upstream_addr" "$http_tenant" "$http_istest"';
    access_log  logs/access.log  main;

2、/soft/tengine/conf/vhosts/password.wanyanzhenjiang.com.conf

    error_log /var/log/nginx/password/error.log error;
    access_log /var/log/nginx/password/access.log main  ;

fail2ban配置文件

1、创建配置文件

#cp /etc/fail2ban/jail.conf  /etc/fail2ban/jail.local

2、新增自定义配置(/etc/fail2ban/jail.local)

[nginx]
enabled = true
port = http,https
filter = nginx
logpath = /var/log/nginx/password/access.log
action = iptables-multiport[name=404, port="http,https", protocol=tcp]
maxretry = 5
findtime = 30
bantime = 7200

3、开启白名单ip地址(/etc/fail2ban/jail.conf )

ignoreip = 127.0.0.1/8 183.128.80.212/32

4、创建自定义规则(/etc/fail2ban/filter.d/nginx.conf)

[Definition]
failregex = ^<HOST>.*"(GET|POST).*" (404|444|403|400) .*$
ignoreregex =

fail2ban服务管理

1、重启服务

#systemctl restart fail2ban
#systemctl status fail2ban
● fail2ban.service - Fail2Ban Service
   Loaded: loaded (/usr/lib/systemd/system/fail2ban.service; enabled; vendor preset: disabled)
   Active: active (running) since 五 2023-09-15 13:38:24 CST; 6s ago
     Docs: man:fail2ban(1)
  Process: 22894 ExecStop=/usr/bin/fail2ban-client stop (code=exited, status=0/SUCCESS)
  Process: 22897 ExecStartPre=/bin/mkdir -p /run/fail2ban (code=exited, status=0/SUCCESS)
 Main PID: 22899 (fail2ban-server)
    Tasks: 5
   Memory: 9.5M
   CGroup: /system.slice/fail2ban.service
           └─22899 /usr/bin/python2 -s /usr/bin/fail2ban-server -xf start

9月 15 13:38:24 sso-172.16.61.197-hz systemd[1]: Starting Fail2Ban Service...
9月 15 13:38:24 sso-172.16.61.197-hz systemd[1]: Started Fail2Ban Service.
9月 15 13:38:24 sso-172.16.61.197-hz fail2ban-server[22899]: Server ready

2、防护状态查看

#fail2ban-client status nginx
Status for the jail: nginx
|- Filter
|  |- Currently failed:	0
|  |- Total failed:	0
|  `- File list:	/var/log/nginx/password/access.log
`- Actions
   |- Currently banned:	0
   |- Total banned:	0
   `- Banned IP list:

3、fail2ban日志查看

#tail  -100f /var/log/fail2ban.log
2023-09-15 11:15:28,217 fail2ban.database       [10926]: INFO    Connection to database closed.
2023-09-15 11:15:28,217 fail2ban.server         [10926]: INFO    Exiting Fail2ban
2023-09-15 11:15:28,319 fail2ban.server         [12250]: INFO    --------------------------------------------------
2023-09-15 11:15:28,319 fail2ban.server         [12250]: INFO    Starting Fail2ban v0.11.2
2023-09-15 11:15:28,319 fail2ban.observer       [12250]: INFO    Observer start...
2023-09-15 11:15:28,323 fail2ban.database       [12250]: INFO    Connected to fail2ban persistent database '/var/lib/fail2ban/fail2ban.sqlite3'
2023-09-15 11:18:14,725 fail2ban.transmitter    [12250]: WARNING Command ['status', 'nginx-http-auth'] has failed. Received UnknownJailException('nginx-http-auth',)
2023-09-15 11:20:28,808 fail2ban.server         [12250]: INFO    Shutdown in progress...
2023-09-15 11:20:28,808 fail2ban.observer       [12250]: INFO    Observer stop ... try to end queue 5 seconds
2023-09-15 11:20:28,854 fail2ban.observer       [12250]: INFO    Observer stopped, 0 events remaining.
2023-09-15 11:20:28,888 fail2ban.server         [12250]: INFO    Stopping all jails
2023-09-15 11:20:28,889 fail2ban.database       [12250]: INFO    Connection to database closed.
2023-09-15 11:20:28,889 fail2ban.server         [12250]: INFO    Exiting Fail2ban

检查日志匹配情况

#fail2ban-regex  /var/log/nginx/password/access.log /etc/fail2ban/filter.d/nginx.conf

Running tests
=============

Use   failregex filter file : nginx, basedir: /etc/fail2ban
Use         log file : /var/log/nginx/password/access.log
Use         encoding : UTF-8


Results
=======

Failregex: 0 total

Ignoreregex: 0 total

Date template hits:
|- [# of hits] date format
|  [119] Day(?P<_sep>[-/])MON(?P=_sep)ExYear[ :]?24hour:Minute:Second(?:\.Microseconds)?(?: Zone offset)?
`-

Lines: 119 lines, 0 ignored, 0 matched, 119 missed
[processed in 0.05 sec]

Missed line(s): too many to print.  Use --print-all-missed to print all 119 lines
[root@sso-172.16.61.197-hz fail2ban]#fail2ban-regex  /var/log/nginx/password/access.log /etc/fail2ban/filter.d/nginx.conf ^C
[root@sso-172.16.61.197-hz fail2ban]#cat  /etc/fail2ban/filter.d/nginx.conf
[Definition]
failregex =  ^<HOST>.*"(GET|POST).*" (403|404) .*$
ignoreregex =

开启DUGUG模式

#fail2ban-client -d
['set', 'syslogsocket', 'auto']
['set', 'loglevel', 'INFO']
['set', 'logtarget', '/var/log/fail2ban.log']
['set', 'dbfile', '/var/lib/fail2ban/fail2ban.sqlite3']
['set', 'dbmaxmatches', 10]
['set', 'dbpurgeage', '1d']
['add', 'nginx', 'auto']
['set', 'nginx', 'usedns', 'warn']
['set', 'nginx', 'addfailregex', '^<HOST>.*"(GET|POST).*" (403|404) .*$']
['set', 'nginx', 'maxmatches', 5]
['set', 'nginx', 'maxretry', 5]
['set', 'nginx', 'addignoreip', '127.0.0.1/8', '183.128.80.212/32', '115.216.2.142/32']
['set', 'nginx', 'logencoding', 'auto']
['set', 'nginx', 'ignorecommand', '']
['set', 'nginx', 'findtime', '30']
['set', 'nginx', 'bantime', '7200']
['set', 'nginx', 'addlogpath', '/var/log/nginx/password/access.log', 'head']
['set', 'nginx', 'addaction', 'iptables-multiport-404']
['multi-set', 'nginx', 'action', 'iptables-multiport-404', [['actionunban', '<iptables> -D f2b-404 -s <ip> -j <blocktype>'], ['actionflush', '<iptables> -F f2b-404'], ['actionstop', '<iptables> -D INPUT -p tcp -m multiport --dports http,https -j f2b-404\n<iptables> -F f2b-404\n<iptables> -X f2b-404'], ['actionstart', '<iptables> -N f2b-404\n<iptables> -A f2b-404 -j RETURN\n<iptables> -I INPUT -p tcp -m multiport --dports http,https -j f2b-404'], ['actionban', '<iptables> -I f2b-404 1 -s <ip> -j <blocktype>'], ['actioncheck', "<iptables> -n -L INPUT | grep -q 'f2b-404[ \\t]'"], ['iptables', 'iptables <lockingopt>'], ['lockingopt', '-w'], ['blocktype?family=inet6', 'REJECT --reject-with icmp6-port-unreachable'], ['protocol', 'tcp'], ['name', '404'], ['chain', 'INPUT'], ['returntype', 'RETURN'], ['iptables?family=inet6', 'ip6tables <lockingopt>'], ['blocktype', 'REJECT --reject-with icmp-port-unreachable'], ['actname', 'iptables-multiport-404'], ['port', 'http,https']]]
['start', 'nginx']

nginx可以通过以下方式来防范DDoS攻击: 1. 使用nginx的http_limit_conn模块来限制单个IP的连接数。这个模块可以设置每个IP允许的最大连接数,超过限制的连接将被拒绝。这样可以有效地防止CC攻击。配置方法如下[^1]: ```nginx http { limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m; server { location / { limit_conn conn_limit_per_ip 10; # 其他配置项 } } } ``` 2. 使用nginx的http_limit_req模块来限制单个IP每秒的请求数。这个模块可以设置每个IP允许的最大请求数,超过限制的请求将被拒绝。这样可以有效地防止请求过载攻击。配置方法如下: ```nginx http { limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=10r/s; server { location / { limit_req zone=req_limit_per_ip burst=20 nodelay; # 其他配置项 } } } ``` 3. 使用fail2ban来分析nginx的日志,并根据规则判断是否使用iptables拦截攻击者的IP。fail2ban可以根据日志中的异常行为(如频繁访问、错误请求等)来判断是否有DDoS攻击,并自动屏蔽攻击者的IP。配置方法如下: - 安装fail2ban:`sudo apt-get install fail2ban` - 配置fail2ban:编辑`/etc/fail2ban/jail.local`文件,添加以下内容: ```shell [nginx-ddos] enabled = true filter = nginx-ddos action = iptables[name=nginx-ddos, port=http, protocol=tcp] logpath = /var/log/nginx/access.log maxretry = 100 findtime = 60 bantime = 600 ``` - 创建fail2ban的过滤规则:创建`/etc/fail2ban/filter.d/nginx-ddos.conf`文件,添加以下内容: ```shell [Definition] failregex = ^<HOST> .* "GET /.*" ignoreregex = ``` - 重启fail2ban服务:`sudo service fail2ban restart` 4. 使用DDoS Deflate来通过netstat判断IP连接数,并使用iptables屏蔽攻击者的IP。DDoS Deflate是一个脚本工具,可以根据连接数来判断是否有DDoS攻击,并自动屏蔽攻击者的IP。配置方法如下: - 下载DDoS Deflate脚本:`wget https://github.com/jgmdev/ddos-deflate/archive/master.zip` - 解压脚本:`unzip master.zip` - 进入解压后的目录:`cd ddos-deflate-master` - 安装脚本:`./install.sh` - 启动脚本:`./ddos-deflate.sh` 这些方法可以帮助nginx有效地防范DDoS攻击
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

完颜振江

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值