CSF防火墙简介与安装
近期遭遇恶意代理请求激增,尽管服务器已返回403 Forbidden状态码,但庞大的请求量仍导致带宽与系统资源严重消耗。此前采用的方法失效,鉴于仅依靠Apache设置IP黑名单较为繁琐,决定深入研究防火墙机制。虽然iptables或ufw等工具具备管理能力,但需逐条添加规则,操作效率低下。
经搜索发现一款便捷工具——CSF(ConfigServer & Security Firewall)。该工具不仅便于管理IP黑名单,经适当配置后还能提供一定程度的DDoS攻击防护能力。
CSF工具可从其官方网站获取下载包。
解压后参考install.txt中的说明文档进行安装,文档内容简洁详尽,安装时注意赋予相应执行权限即可。需指出的是,CSF底层依然基于iptables构建,主要优势在于对命令进行了封装简化。
关于DDoS防护配置
依据readme.txt描述,DDoS防护功能主要由/etc/csf/csf.conf配置文件控制,核心参数为PORTFLOOD。通常建议按如下格式进行设置:
#Syntax for the PORTFLOOD setting:
#PORTFLOOD is a comma separated list of:
port;protocol;hit count*;interval seconds
#So, a setting of PORTFLOOD = "22;tcp;5;300,80;tcp;20;5" means:
#1. If more than 5 connections to tcp port 22 within 300 seconds, then block
#that IP address from port 22 for at least 300 seconds after the last packet is
#seen, i.e. there must be a "quiet" period of 300 seconds before the block is
#lifted
#2. If more than 20 connections to tcp port 80 within 5 seconds, then block
#that IP address from port 80 for at least 5 seconds after the last packet is
#seen, i.e. there must be a "quiet" period of 5 seconds before the block is
#lifted
具体阈值可根据实际业务需求进行调整。
关于黑名单管理
黑名单文件位于/etc/csf/csf.deny,支持多种书写格式,文件头部注释中有详细说明:
###############################################################################
# Copyright 2006-2026, Way to the Web Limited
# URL: http://www.configserver.com
# Email: sales@waytotheweb.com
###############################################################################
# The following IP addresses will be blocked in iptables
# One IP address per line
# CIDR addressing allowed with a quaded IP (e.g. 192.168.254.0/24)
# Only list IP addresses, not domain names (they will be ignored)
#
# Note: If you add the text "do not delete" to the comments of an entry then
# DENY_IP_LIMIT will ignore those entries and not remove them
#
# Advanced port+ip filtering allowed with the following format
# tcp/udp|in/out|s/d=port|s/d=ip
#
# See readme.txt for more information regarding advanced port filtering
#
简而言之,每行可定义单个IP、CIDR网段,也可添加注释,甚至能指定特定端口和协议。修改完成后,务必执行csf -r命令使配置生效。
针对恶意代理请求的自动化防护方案
本方案旨在彻底解决恶意代理占用带宽的问题。借助CSF工具,可按以下思路轻松实现控制:
- 首先,检索Apache日志文件(/var/log/apache2/access.log),筛选出所有应被屏蔽的请求条目(此处特指所有产生403状态的请求)。
- 接着,从每条日志记录中提取对应的客户端IP地址。
- 对提取结果进行排序并去重,生成最终的黑名单列表。
- 将生成的黑名单写入csf.deny文件中。
- 重启CSF防护服务以加载新规则。
整个实现过程极为简便:
复制代码 代码如下: root@server:~# cat /var/log/apache2/access.log |grep \ 403\ |awk '{print $1}'|sort|uniq >> /etc/csf/csf.deny
建议手动检查输出结果是否正确,确认无误后即可通过csf -r命令重启服务。
以上内容即为本次分享的全部要点,希望能对各位的学习有所帮助,同时也欢迎多多支持本站。