文章轉載自:https://mp.weixin.qq.com/s/oktVy09zJAAH_MMKdXjtIA
由於業務需要將Linux服務器映射到公網訪問,SSH 端口已經修改,但還是發現有很多IP進行暴力破解,嘗試將異常IP阻止非法訪問,實現方式①SSH黑名單 ②Firewalld防火牆添加drop規則;
SSH 黑名單實現思路
①通過lastb獲取一小時區間非法登錄系統的IP並通過AWK 統計>10次的IP;
②FOR 循環 實現SSH 黑名單添加;
③將SHELL 腳本添加到系統計划任務中。
客戶端IP發起登錄,Linux的檢查策略是先看/etc/hosts.allow中是否允許,如果允許直接放行;如果沒有,則再看/etc/hosts.deny中是否禁止。
#!/bin/bash
DATE=$(date +"%a %b %e %H")
DROP_IP=$(lastb |grep "$DATE" |awk '{a[$3]++}END{for(i in a)if(a[i]>10)print i}')
for IP in $DROP_IP; do
if [ $(cat /etc/hosts.deny |grep -c "$IP") -eq 0 ]; then
echo "sshd:$IP:deny" >> /etc/hosts.deny
fi
done
Firewalld實現思路
①通過lastb獲取一小時區間非法登錄系統的IP並通過AWK 統計>10次的IP;
②FOR 循環 實現fFirewalld防火牆添加drop規則並重新加載防火牆配置;
③將SHELL 腳本添加到系統計划任務中。
#!/bin/bash
DATE=$(date +"%a %b %e %H")
DROP_IP=$(lastb |grep "$DATE" |awk '{a[$3]++}END{for(i in a)if(a[i]>10)print i}')
for ip in $DROP_IP; do
if [ $(firewall-cmd --list-all |grep drop |grep -c "$ip") -eq 0 ]; then
firewall-cmd --permanent --add-rich-rule="rule family="ipv4" source address="$ip" drop" >> /dev/null
firewall-cmd --reload >>/dev/null
fi
done
計划任務
[root@ecs-01 opt]# crontab -e
#每5分鍾執行一次
*/5 * * * * /usr/bin/bash /opt/fwdrop.sh
*/5 * * * * /usr/bin/bash /opt/sshdrop.sh
Firewall 配置
查看 rich-rule
firewall-cmd --list-rich-rules --zone=public
允許 rich-rule ip
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.10.8" accept'
禁止 rich-rule ip
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.10.8" drop'
刪除 rich-rule ip
firewall-cmd --permanent --remove-rich-rule='rule family="ipv4" source address="192.168.10.8" drop'
允許 rich-rule ip + port
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.10.8" port protocol="tcp" port="22" accept'
禁止 rich-rule ip + port
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.10.8" port protocol="tcp" port="22" drop'
刪除 rich-rule ip + port
firewall-cmd --permanent --remove-rich-rule='rule family="ipv4" source address="192.168.10.8" port protocol="tcp" port="22" drop'
禁止 rich-rule icmp
firewall-cmd --permanent --add-rich-rule='rule protocol value=icmp drop'
刪除rich-rule icmp
firewall-cmd --permanent --remove-rich-rule='rule protocol value=icmp drop'