我在 /var/log/auth.log 中看到类似这样的内容
sshd[2173]: Unable to negotiate with 218.92.0.205 port 21029: no matching host key type found. Their offer: ssh-rsa,ssh-dss [preauth]
sshd[1964]: Unable to negotiate with 218.92.0.205 port 26342: no matching host key type found. Their offer: ssh-rsa,ssh-dss [preauth]
sshd[3031]: Unable to negotiate with 218.92.0.205 port 25903: no matching host key type found. Their offer: ssh-rsa,ssh-dss [preauth]
fail2ban 不会过滤这些问题。
供参考我的jail.local配置:
[sshd]
enabled = true
filter = sshd
port = 0:65535
banaction = ufw
bantime = -1
maxretry = 1
logpath = %(sshd_log)s
backend = %(sshd_backend)s
我想我需要更新我的正则表达式,我该如何阻止这些垃圾邮件?
答案1
当查看时,/etc/fail2ban/filter.d/sshd.conf
希望能有针对Unable to negotiate with
日志条目的正则表达式。
sshd
在模式下运行normal
,为了检测ddos
(另外有extra
和aggressive
),模式必须在中定义jail.local
。
对于您指出的情况,情况如下extra
:
[sshd]
mode = extra
# same as filter with argument
# filter = sshd[mode=extra]
# ... rest of your configuration, findtime, maxretry ...
除此之外,还可以定义具有不同设置的另一个监狱:
[sshd-custom]
enabled = true
filter = sshd[mode=extra]
# ... rest of your configuration, findtime, maxretry ...
答案2
注意:务必以 root 身份运行
这个理论非常简单:
- 读取 /var/secure/log 并过滤 ssh 密码不匹配的情况(需要 root)
- 创建一个 Python 脚本,能够根据阈值(硬编码)创建“iptables ban”命令
如果你安装了 python(并且安装了 fail2ban),你可以运行这个简单的脚本
import sys
import re
# Save the input data into a string
raw = sys.stdin.read().strip()
BAN_COUNT = 3
# Split the lines of the log
data = raw.split("\n")
to_ban = {}
# Iterate the lines
for item in data:
# Extract IP
ip = re.findall(r"[0-9]+(?:\.[0-9]+){3}", item)
# Due to the filter, we can have only 1 IP
if len(ip) == 1:
# print("Found IP to BAN -> {}".format(ip[0]))
# If IP alredy found increase counter
if ip[0] in to_ban:
to_ban[ip[0]] += 1
# First time that we encounter the IP, create new entry in dict
else:
to_ban[ip[0]] = 1
# Create iptables mask for ban
for keys in to_ban.keys():
if to_ban[keys] >= BAN_COUNT:
# BAN MASK
# Use this for ban
# ban_mask = 'iptables -A INPUT -s {} -j DROP'.format(keys)
# Use this for test purpouse
ban_mask = 'echo "iptables -A INPUT -s {} -j DROP"'.format(keys)
print(ban_mask)
现在我们有了一个 python 脚本,它可以获取输入行、提取 ip、计算它们在文本中比较的次数并打印 iptables 命令来禁止该 ip,我们就可以解析日志了secure
。
将脚本另存为ban.py
cat /var/log/secure | egrep 'Failed password for' | python ban.py | xargs command