5

利用 firewalld ipset 禁止 Linux 服务器被暴力破解登录

 8 months ago
source link: https://www.51cto.com/article/777289.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

利用 firewalld ipset 禁止 Linux 服务器被暴力破解登录

作者:Harry 2023-12-21 23:14:07
为了禁止Linux服务器被暴力破解登录,我想到了使用firewalld来禁止这些ip地址通过ssh连接,从而阻断服务器被远程暴力破解,以下是详细步骤。

不知道之前是哪位同事心大,居然把一台Linux主机在防火墙上做了主机映射,结果这台主机完全暴露在公网上,关键是sshd服务端口也没改。一查日志,全是暴力登录的记录,真担心哪天密码被暴力破解了。

2763cb207335f2e1ee636661e6237f35e3cb1c.png

为了解决这个问题,想到了使用firewalld来禁止这些ip地址通过ssh连接,从而阻断服务器被远程暴力破解,以下是详细步骤。

1.定义firewalld ipset

firewall-cmd --permanent --new-ipset=blacklist --type=hash:ip

2.定义firewalld规则调用ipset

firewall-cmd --permanent --add-rich-rule 'rule family="ipv4" source ipset=blacklist port protocol="tcp" port=22 drop'

3.将日志中的ip添加到ipset中

因为日志中ip很多,而且会不断更新,不可能手动添加,于是打算写个shell脚本,通过定时任务添加到ipset中。shell脚本内容如下:

#!/bin/bash
# Author: Harry
# Description: 使用root账号登录错误大于10次的IP被加入到黑名单中
for ip in `grep -i 'Failed password for root' /var/log/secure | awk '{print $11}' | sort -n | uniq -c | sort -k1nr | awk '{if ($1>10) print $2}'`; do
    firewall-cmd --permanent --ipset=blacklist --add-entry="${ip}";
done;
firewall-cmd --reload;

4.定时任务

0 * * * * /opt/blockips.sh >/dev/null 2>&1

说明:任务每小时执行一次

此时可以用如下方法查询被禁止的IP地址:

使用firewall-cmd命令查看已经被进入黑名单的IP地址

firewall-cmd --permanent --info-ipset=blacklist
firewall-cmd --ipset=blacklist --get-entries

经过查询,居然有这么多IP,由此可见服务器暴露在公网上是有多不安全。

图片

查看ipset配置文件blacklist.xml

cat /etc/firewalld/ipsets/blacklist.xml

注意,这里使用的firewalld ipset 是指 firewalld 与 ipset 工具的集成,而不是独立的ipset工具,如果使用ipset命令创建IP地址集合,firewalld将无法与之关联。

责任编辑:赵宁宁 来源: IT人家

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK