Pik*_*ikk 5 networking iptables centos
我正在尝试使用这个解决方案。
我正在运行 Centos 7 和 iptables v1.4.21。
为什么我需要它? 我有几个 WordPress 博客。我每天都会收到 4000 到 20000 次暴力登录、不存在的文件,以及自动尝试查找易受攻击的插件和文件以供以后利用。他们都来自中国。其他国家也有,但每天不到1000个。因此,我想在安全性方面提供一点帮助,并在这些请求到达 Web 服务器或 PHP 引擎之前阻止这些请求,以节省硬件资源。我考虑过在 Security StackExchange 上提出问题,但我认为这里更好。但不知道。我想避免重复的问题。
我的脚本如下所示:
# Create the ipset list
ipset -N china hash:net
# remove any old list that might exist from previous runs of this script
rm cn.zone
# Pull the latest IP set for China
wget -P . http://www.ipdeny.com/ipblocks/data/countries/cn.zone
# Add each IP address from the downloaded list into the ipset 'china'
for i in $(cat /etc/cn.zone ); do ipset -A china $i; done
# Restore iptables
/sbin/iptables-restore < /etc/sysconfig/iptables
Run Code Online (Sandbox Code Playgroud)
规则文件如下所示(没有空格,没有新行):
[root@myserver etc]# cat /etc/sysconfig/iptables
-A INPUT -p tcp -m set --match-set china src -j DROP
[root@myserver etc]#
Run Code Online (Sandbox Code Playgroud)
当我运行脚本时,我收到这样的错误:
ipset v7.1: Element cannot be added to the set: it's already added
ipset v7.1: Element cannot be added to the set: it's already added
ipset v7.1: Element cannot be added to the set: it's already added
ipset v7.1: Element cannot be added to the set: it's already added
(a plenty of the same lines)
Run Code Online (Sandbox Code Playgroud)
在这里我看到两三个问题:
添加后,我看到了这一点 - 这似乎很好,但我仍然想解决上述问题:
# iptables -L
Chain INPUT (policy ACCEPT)
target prot opt source destination
DROP tcp -- anywhere anywhere match-set china src
Chain FORWARD (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
Run Code Online (Sandbox Code Playgroud)
ipset有一个子命令可以自动交换两个集合:swap( 或-W)。这允许填充新集,将其与旧集交换,并使用新名称删除现在无用的集。这比刷新集合(使用ipset flush china)更好,因为这会暂时使系统暴露,并且允许用不同的参数替换集合,而不必删除引用它的iptables规则(因为集合在仍然被引用时不能被销毁)。我还切换到ipset的较新语法,这是最近的联机帮助页中保留的唯一语法(两种语法都有效)。
# -exist for idempotence: don't trigger an error the 2nd time this script is run
ipset -exist create china hash:net
# old cn.zone will stay around if download fails
wget -O /etc/cn.zone.tmp http://www.ipdeny.com/ipblocks/data/countries/cn.zone && \
mv /etc/cn.zone.tmp /etc/cn.zone
ipset create china.tmp hash:net
sed 's/^/add china.tmp /' /etc/cn.zone | ipset -exist restore
ipset swap china china.tmp # new set atomically replaces older set
ipset destroy china.tmp
/sbin/iptables-restore < /etc/sysconfig/iptables
Run Code Online (Sandbox Code Playgroud)
将循环替换为(正确格式化的输入)ipset -exist restore将条目的加载提高了两个数量级(此处循环测试从约 6 秒缩短到约 0.06 秒)。-exist在这里,以防输入列表本身包含重复项,忽略它们并防止加载条目时过早中止。如果您认为输入列表可能具有无法解析的内容,则可以对其进行过滤以使其可解析(例如:删除任何空行)或恢复到循环,但最好for使用while read如下构造:
while read net; do
ipset -exist add china.tmp "$net"
done < /etc/cn.zone
Run Code Online (Sandbox Code Playgroud)
iptables-restore可以留在当前脚本中,也可以放在单独的脚本中(这取决于当前脚本,因为 iptables 的规则取决于已创建的集),以保持更新集和更新 iptables 规则的功能分开。
我确信该脚本可以进一步改进(尤其是加载cn.zone预计在启动时失败的文件,即使这不会影响整体结果。也许这也应该分开)。
| 归档时间: |
|
| 查看次数: |
760 次 |
| 最近记录: |