前言
暴露公网ip端口能显著提高访问效率,代价是容易被端口扫描无差别攻击。
虽说关闭了password actuation查看认证日志/var/log/auth.log
还是挺闹心的……
Aug 21 23:52:01 localhost sshd[3282]: Invalid user xiao from 159.89.178.62 port 38156
Aug 21 23:52:01 localhost sshd[3282]: input_userauth_request: invalid user xiao [preauth]
Aug 21 23:52:01 localhost sshd[3276]: Received disconnect from 159.89.178.62 port 38048:11: Normal Shutdown, Thank you for playing [preauth]
Aug 21 23:52:01 localhost sshd[3276]: Disconnected from 159.89.178.62 port 38048 [preauth]
Aug 21 23:52:01 localhost sshd[3278]: Received disconnect from 159.89.178.62 port 38066:11: Normal Shutdown, Thank you for playing [preauth]
Aug 21 23:52:01 localhost sshd[3278]: Disconnected from 159.89.178.62 port 38066 [preauth]
Aug 21 23:52:01 localhost sshd[3242]: Received disconnect from 159.89.178.62 port 37454:11: Normal Shutdown, Thank you for playing [preauth]
Aug 21 23:52:01 localhost sshd[3242]: Disconnected from 159.89.178.62 port 37454 [preauth]
Aug 21 23:52:01 localhost sshd[3281]: Received disconnect from 159.89.178.62 port 38138:11: Normal Shutdown, Thank you for playing [preauth]
Aug 21 23:52:01 localhost sshd[3281]: Disconnected from 159.89.178.62 port 38138 [preauth]
Aug 21 23:52:01 localhost sshd[3248]: Received disconnect from 159.89.178.62 port 37292:11: Normal Shutdown, Thank you for playing [preauth]
Aug 21 23:52:01 localhost sshd[3248]: Disconnected from 159.89.178.62 port 37292 [preauth]
为过滤此类端口扫描,安装网上推荐的fail2ban作基本的sshd爆破防御。
原理
fail2ban本质上是一个python脚本,内置了很多攻击防护规则(jail)。
基本原理是定时扫描指定log文件,使用正则表达式获取关注fail信息并提取ip地址。
当某一ip再限定时间段内fail次数达到上限则调用iptables规则对ip进行阻止(ban)。
部署
Ubuntu/Debian系统使用apt进行包管理
sudo apt install fail2ban
调用官方自带的jail规则已默认开启sshd
sudo cp /etc/fail2ban.{conf,local}
修改规则sudo vi /etc/fail2ban.local
# 封禁时间默认为600建议延长,单位sec
bantime = 43200
# action默认值iptables-multiport会产生iptables错误,表现为加入banlist的ip依然能够访问
banaction = iptables-allports
reload规则生效并查看sshd状态
sudo fail2ban-client reload
sudo fail2ban-client status sshd
正常工况状态如下
Status for the jail: sshd
|- Filter
| |- Currently failed: 21
| |- Total failed: 21
| `- File list: /var/log/auth.log
`- Actions
|- Currently banned: 1
|- Total banned: 1
`- Banned IP list: 159.89.178.62
参考
Fail2ban Configuration for Secure Servers: One Step at a Time
linux - fail2ban keeps saying already banned but it didn't actually ban - Unix & Linux Stack Exchange