轉截請寫明出處,謝謝!
最近老同事的電子商務網站經常性的對手ab,無奈我花些時間google,發現有不少朋友用mod_dosevasive來對抗ddos攻擊(當然是小範圍的,如果沒有帶寬和硬件的保障效果會更好).
居體的安裝可以參看
關於Apache (httpd)服務器防DDOS模塊mod_evasive的使用說明
上面寫的夠詳細了。
下面是我的安裝過程
1.安裝apxs 即要有 apache開發版本的支持
#yum install httpd-devel
2.進入mod_evasive目錄
查看apxs在哪裏
#whereis apxs /* /usr/bin/apxs*/
#/usr/bin/apxs -i -a -c mod_dosevasive20.c
執行上面的命令後系統會在/etc/httpd/conf/httpd.conf中加入下面一行
LoadModule evasive20_module /usr/lib/httpd/modules/mod_evasive20.so
3.加入在被DDOS時的處理操作
手工在/etc/httpd/conf/httpd.conf最下方加入下面內容
<IfModule mod_evasive20.c>
DOSHashTableSize 3097
DOSPageCount 2
DOSSiteCount 50
DOSPageInterval 1
DOSSiteInterval 1
DOSBlockingPeriod 10
DOSSystemCommand "sudo iptables -A INPUT -s %s -p tcp --dport 80 -j DROP"
DOSLogDir "/tmp/lock/mod_evasive"
</IfModule>
針對上面的配置在mod_dosevasive目錄下面的REAME中有詳細說明。
做了上面的配置之後記得要重啓apache
4.重啓apache
#service httpd restart
4.測試
我用壓力測試工具ab
#ab -n 1000 -c 100 http://192.168.1.254/index.php
5.查看是否本機IP(192.168.1.100)是否被封
#iptables -nvL
顯示:
- Chain INPUT (policy ACCEPT 64628 packets, 6176K bytes)
- pkts bytes target prot opt in out source destination
- Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
- pkts bytes target prot opt in out source destination
- Chain OUTPUT (policy ACCEPT 49010 packets, 10M bytes)
- pkts bytes target prot opt in out source destination
結果顯示並沒有封着我的本機IP
分析原因是apache用戶執行sudo處沒有執行,因爲我把
DOSSystemCommand "sudo iptables -A INPUT -s %s -p tcp --dport 80 -j DROP"
改成了
DOSSystemCommand "/bin/touch /tmp/%s.log"
重啓apache沒有問題故可以判斷是sudo執行iptables的問題。因iptables命令是一定要root用戶才能執行的。
中間我還把相關的命令寫在了一個shell(/tmp/do.sh)中,並且把do.sh的權限改爲4755(該權限會改變文件執行的屬主爲root)
do.sh
- #!/bin/sh
- #相關的參數判斷自己來吧
- /sbin/iptables -A INPUT -s $1 -p tcp --dport 80 -j DROP
重啓apache再壓力測試。用iptables -nvL查看還是沒有看到策略中有被封的IP
針對上面的測試問題就在定位到了sudo 下面就是google.
最終找到相關的答案
Gentoo Sudo(ers)指南
簡單的步驟就是
#visudo
加入下面的內容
apache ALL=NOPASSWD: /sbin/iptables
然後用sudo -l可以查看apache用戶是否成功加入可以執行sudo的行列
重啓apache->壓力測試->查看防火牆策略->結果依舊(失敗)查看apache的error日誌顯示
sudo: sorry, you must have a tty to run sudo
意思就是apache運行sudo要求是終端模式,在做web服務器用sudo的時候肯定是不能用終端了。
經查看visudo的配置和google的結果顯示 我們需要將visudo中的
Defaults requiretty
註解掉
#Defaults requiretty
最終重複測試流程在
#iptables -nvL的命令下看到了被封堵的記錄
- Chain INPUT (policy ACCEPT 64543 packets, 6168K bytes)
- pkts bytes target prot opt in out source destination
- 836 39828 DROP tcp -- * * 192.168.1.100 0.0.0.0/0 tcp dpt:80
- Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
- pkts bytes target prot opt in out source destination
- Chain OUTPUT (policy ACCEPT 48945 packets, 10M bytes)
- pkts bytes target prot opt in out source destination