生產環境中,其他管理員可能修改 hosts.allow 放行更多 IP。為統一管理,可在用戶登出時自動重置存取控制檔案,並自動允許本機配置的 IP 段登入。
test -f /root/.bash_logout && chattr -i /root/.bash_logout
cat > /root/.bash_logout << 'EOF'
export TERM=xterm
/usr/bin/chattr -i /etc/hosts.allow /etc/hosts.deny
# 產生 hosts.deny:拒絕所有,除本機網段
/bin/awk 'BEGIN{FS="[=.]";RS="\n"};/^IPADDR/{print "sshd:all EXCEPT "$2"."$3"."$4".0/255.255.255.0"}' /etc/sysconfig/network-scripts/ifcfg-* | grep -v 127.0.0 | uniq > /etc/hosts.deny
/bin/cat >> /etc/hosts.deny << 'iEOF'
sshd:all EXCEPT ip
iEOF
# 產生 hosts.allow:允許本機網段
/bin/awk 'BEGIN{FS="[=.]";RS="\n"};/^IPADDR/{print "sshd:"$2"."$3"."$4".0/255.255.255.0"}' /etc/sysconfig/network-scripts/ifcfg-* | grep -v 127.0.0 | uniq > /etc/hosts.allow
/bin/cat >> /etc/hosts.allow << 'iEOF'
sshd:ip (www.111cn.net)
iEOF
/usr/bin/chattr +i /etc/hosts.allow /etc/hosts.deny
clear
EOF
sh /root/.bash_logout 2>&1 >/dev/null
#!/bin/bash
# 檢測惡意 IP 登入並郵件報警(可搭配 139 郵箱實現簡訊通知)
Ldate=`which date`; Lawk=`which awk`; Llast=`which last`
Lgrep=`which grep`; Lsendmail=`which sendmail`; Lifconfig=`which ifconfig`
serverip=`$Lifconfig eth0|$Lgrep inet|$Lawk -F: '{print $2}'|$Lawk '{print $1}'`
cutdate=`$Ldate |$Lawk '{print $1" "$2" "$3}'`
hackerip=`$Llast|$Lgrep "$cutdate"|$Lawk '{print $3}'|$Lgrep -v 192.168.1x.xx`
if [ -z "$hackerip" ]; then exit; fi
for logip in $hackerip; do
echo "hacker ip is $logip already login $serverip" | mail -s "SOS" rocdk890@139.com
done
此腳本可排程執行,發現非預期 IP 登入即發送告警。