2011年5月27日 星期五

防 ssh 暴力攻擊 使用iptables & shell @ CentOS

Owen's: [轉錄][Linux] 防 ssh 暴力攻擊 使用iptables & shell @ CentOS: "原則上 ssh port 能不要全部開啟事最好的,如果一定要開啟的話,必需要作些防護措施, port 22 一旦開啟後最容易遇到的就是會有人不斷的try密碼 設計原理: 1. 抵擋 ssh 暴力攻擊 2. 如果連續攻擊3次以上則抵擋 3. 利用 TCP-Wrapper 偵測是否有登入失敗 ,有失敗才執行shell mkdir /etc/firewall/ touch /etc/firewall/sshd.sh chmod 755 /etc/firewall/sshd.sh vi /etc/firewall/sshd.sh 寫入以下資料 #!/bin/bash # 檔案存放的路徑 basedir='/etc/firewall' # log 存放的地方 sshlog='/var/log/auth.log' # mail for mailfor='root' # 登入錯誤訊息 faildMsg='sshd.*Failed password' faildMsgInvalid='sshd.*Failed password for invalid user' # 登入幾次失敗 就擋掉 loginCountFail=3 # 計算前 XXXX 行是否有登入失敗的狀況 failcount=`/usr/bin/tail -n 50 '$sshlog' | /bin/grep '$faildMsg' | wc -l` #cat '$sshlog' | grep 'sshd.*Failed password for' | grep -v 'invalid' | cut -d ' ' -f11 #cat '$sshlog' | grep 'sshd.*Failed password for invalid user' | cut -d ' ' -f13 # 如果有登入失敗的話 if [ '$failcount' -gt '0' ]; then # 建立 登入失敗 暫存檔 #cat /var/log/auth.log | grep 'sshd.*Failed password for' | grep -v 'invalid' cat '$sshlog' | grep 'sshd.*Failed password for' | grep -v 'invalid' > /tmp/ssh_tmp.log #cat /var/log/auth.log | grep 'sshd.*Failed password for' | grep -v 'invalid' cat '$sshlog' | grep 'sshd.*Failed password for invalid user' > /tmp/ssh_tmp2.log # 建立 登入失敗 IP 暫存檔 #cat '$sshlog' | grep '$faildMsg' | cut -d ' ' -f13 | sort | uniq > /tmp/ssh_ip_tmp.log cat /tmp/ssh_tmp.log | cut -d ' ' -f11 > /tmp/ssh_ip_tmp.log cat /tmp/ssh_tmp2.log | cut -d ' ' -f13 >> /tmp/ssh_ip_tmp.log # 取得要封鎖的IP位址 #blockip=`cat /tmp/ssh_ip_tmp.log` blockip=`cat /tmp/ssh_ip_tmp.log | sort | uniq` # iptables中,找出定義的ruleexistchar中的ip。 #iptables -L INPUT -n | grep 'tcp dpt:22' | grep 'DROP' | awk '{print $4}' | sort | uniq ruleexistip=`iptables -L INPUT -n | grep 'tcp dpt:22' | grep 'DROP' | awk '{print $4}' | sort | uniq` blacklist=`cat '$basedir'/ssd_blacklist_d` for ip in $blacklist do `iptables -D INPUT -p TCP -s $ip --dport 22 -j DROP` > /dev/null done rm -rf '$basedir'/ssd_blacklist_d # 利用 for 迴圈去跑 drop IP for ip in $blockip do # 計算此IP登入幾次失敗 count=`cat /tmp/ssh_ip_tmp.log | grep '$ip' | wc -l` # 如果登入失敗次數大於 預設值 則執行 drop if [ '$count' -gt '$loginCountFail' ] ; then #echo $ip $count # 如果從secure找出的ip已存在於iptables,就不需要加這條rule了。 if [ '$ip' = '$ruleexistip' ]; then : else `iptables -I INPUT -p TCP -s $ip --dport 22 -j DROP` fi # if [ '$ip' = '$ruleexistip' ]; # 建立黑名單 echo '$ip' >> '$basedir'/ssd_blacklist_d cat '$basedir'/ssd_blacklist_d | sort | uniq > '$basedir'/ssd_blacklist_d fi # if [ '$count' -gt '$loginCountFail'] ; done # for loop done # 刪除暫存檔 rm -rf /tmp/ssh*.log mail -s 'ssh hacker 抵擋的IP位址' $mailfor < '$basedir'/ssd_blacklist_d fi # if [ '$failcount' -gt '0' ]; 然後在 vi /etc/hosts.allow 加入 sshd : ALL : spawn /etc/firewall/sshd.sh 參考資料: * http://www.andowson.com/posts/list/33.page * http://ssorc.tw/rewrite.php/read-93.html

- 已使用 Google 工具列寄出"

沒有留言:

張貼留言