deserts
大客部
级别: 总版主
精华: 0
发帖: 315
威望: 2 点
金钱: 583 RMB
贡献值: 0 点
在线时间:277(小时)
注册时间:2006-01-01
|
linux自动屏蔽IP工具
另存为 firewall.sh 给执行的权限
>cw%ckE X;'H@GU0 #!/bin/sh hh#p=Y(f # this program is used to check tcp/ip connections y rH@:D/ # and block those ip with excessive connections 6
);8z!+ 4 ))Z Bq? # my version W-D{cU myver="1.0RC1" sBm)D=Kll |r['"6
# wake up every 120s if last check found abuse client ?te~[_oT wakeup_time_min=120 pT|l "q@ TAB'oLNp # wake up every 300s if last check found no abuse client ;-kC&GZf wakeup_time_max=300 "o)jB~:L m9
41 Y # rule timeout 3600s )s N}ClgJ rule_timeout=3600 WA((>D
af] L;h|Sk]{ # check port list []:&WA9N portlist="80" 0@yw#.j 2Q=I
`H_ # max established connection per ip zb3,2D+P max_active_conn=8 r17"i.n qr4.s$VGs* # iptables chain name @.)WS\Cv#E iptables_chain_name="RH-Lokkit-0-50-INPUT" sm Kp3_r 2q4-9vu # log facility m<sCRWa- log_facility="local0" ra;: $MqEM~^= # Block policy {4 {X`$ ipchains_block_policy="DENY" k%R(Qga iptables_block_policy="REJECT" ;b}cn!U] 3aw-fuuIb # myself =6a=`3r!I myself=`basename $0` 40a
D\S> RR2M+vQ mylogger_info() [9d\WPLC { 5/R
~<z logger -p $log_facility.info -t $myself $@ 2>/dev/null q'9; } ^HU>fkSk h.\p+Qw. mylogger_debug() X4L@|"ZI { drvz
[
9; logger -p $log_facility.debug -t $myself $@ 2>/dev/null &oE'|^G } kZ;Y/DH w\M"9T mylogger_notice() c_t7< { `a[
V_4wO logger -p $log_facility.notice -t $myself $@ 2>/dev/null b'I@TLE') } @YVla!5O@ N/[!$B0H@ dotimeout() a^Z=xlJ/uZ { `QZKW mylogger_info "reset firewall when timeout arrives" `4e| I.`^r case "$firewall" in mz<X$2]? ipchains)
hOYX /etc/init.d/ipchains restart 1>/dev/null 2>/dev/null VtMnLFMw if [ $? = 0 ] ; then YV'B*arIA mylogger_info "ipchains restarted" KO/#t~ else _Ea1;dJmq mylogger_notice "ipchains restart failed" p&\DG
fi ><$V:nsEO ;; ;&!QN#_ iptables) >;#rK@*& /etc/init.d/iptables restart 1>/dev/null 2>/dev/null [;l;kom if [ $? = 0 ] ; then EWq
<
B) mylogger_info "iptables restarted" ;Zc0imYL else ]
.Ra=^q mylogger_notice "iptables restart failed" Iu(]i?Y fi ^E)8Sb9t ;; /7ShE-.5# *) Fu% n8 mylogger_notice "neither ipchains nor iptables" q"WfKz!U ;; 69t6lB#;! esac
Hn/V*RzQ eT?vZH[N } e`+ej-o, E 0OHl blockclient() :.f(}sCS { ?;Da%VS3 if [ -z "$1" ] || [ -z "$2" ]; then uH7!)LE
# mylogger_notice "blockclient() missing client or port to block" Fh&USn" return _bv9/# tR fi |o^mg9 local ip port BQv*8Hg
B6 &o&}5Aba9 ip=$1 K.}jyhKIKi port=$2 };'~@%U]/ y>cT{ )E$ case "$firewall" in @Y ?p-& ipchains) 	HV mylogger_notice "blocking $1 to $2 via ipchains" B"`86qc found=`ipchains -nL | egrep "^$ipchains_block_policy.*[[:space:]]+$ip[[:space:]]+.*[[:space:]]+\->[[:space:]]+$port"` zs'Jgm.v if [ -z "$found" ] ; then Z}IuR|= cmd="ipchains -I input 1 -p tcp -s $ip -d 0/0 $port -j $ipchains_block_policy 1>/dev/null 2>/dev/null" hn$jI5*` mylogger_debug "cmd: $cmd" s-F3(mc( `ipchains -I input 1 -p tcp -s $ip -d 0/0 $port -j $ipchains_block_policy 1>/dev/null 2>/dev/null` +JB*1dz>8 if [ $? != 0 ] ; then }{[p<pU$C mylogger_notice "$cmd call failed" #?Ob->v return \.F|c fi 3'7X[{uBr new_block=1 awLSY:JI ever_block=1 j,1cb,}=^ else !3"Hn
mylogger_info "$ip already blocked to $port" )$O'L7I n& fi 1V]j8 ;; y)7;"3Q< iptables) QD
0p mylogger_notice "blocking $1 to $2 via iptables" zB6&),[,v found=`iptables -nL | egrep "^$iptables_block_policy.*[[:space:]]+$ip[[:space:]]+.*[[:space:]]+dpt:$port[[:space:]]+"` Nu><r if [ -z "$found" ] ; then Ft @ZK!'@ cmd="iptables -I $iptables_chain_name 1 -p tcp -m tcp -s $ip --dport $port -j $iptables_block_policy 1>/dev/null 2>/dev/null" pQ`S%]k.< mylogger_debug "cmd: $cmd" (V`ddP- `iptables -I $iptables_chain_name 1 -p tcp -m tcp -s $ip --dport $port -j $iptables_block_policy 1>/dev/null 2>/dev/null` 6h&i<-> if [ $? != 0 ] ; then 8]J lYe mylogger_notice "$cmd call failed" n%{oFTLCo return ?1H>k<Jp fi 92^Dn`g new_block=1 B,A\/%< ever_block=1 oXGP6# else wOR#sp& mylogger_info "$ip already blocked to $port" T{Yk/Z/}? fi !6*4^$i#o ;; U,,rB( *) nY?X@avo> mylogger_notice "neither ipchains nor iptables" {G _|gs ;; 'V*8'? esac L$}'6y/@ } OLDEB.@ +fq;o8q restartservice() s;:quM { eRIdN(pP local service l78:. if [ -z "$1" ] ; then *q(HW mylogger_notice "no port given to see which service to be restart" /Pa<I^-# return Bqb3[^;~ fi b]\V~ZaXG bqUQadDB case "$1" in "C [uz& 80) DT#Z6A service="httpd" D{s4Bo- ;; }i2d
XC/ 25) 7.xJ:r| service="postfix" nB86oQ/S ;; F6#U31Q= 110) 7j%sM& service="courier-pop3d" TZk.h8 ;; XY`2>7 21) WnC0T5S?U service="muddleftpd" _k.gVm ;; @?"t&h 53) ^o*$+DbC service="named" ;^:$O6J7T~ ;; x+5y287# 3306) _a=
f.I service="mysqld" YJ^TO\4WM ;; 6 _\j_$ esac yw)Ztg) if [ ! -z "$service" ] ; then 1
+'HKT} /etc/init.d/$service restart 1>/dev/null 2>/dev/null
XS/5y(W if [ $? = 0 ] ; then ,W/D 0 mylogger_notice "$service restarted" :j2_Jn4UP else p,w6D,h mylogger_notice "$service restart failed" +C !A@ fi W=~H_L?/ fi AFSFXPl
" } D0&{iZ( ,FPgbs docheckport() [Pt5c6 L: { PF(P"f.?D mylogger_info "do check port $1" t%AW0#TZ local port last_client count client total_count (IR'~:W ?D6rFUs9; if [ -z "$1" ] ; then Bv |Z)G%RR mylogger_notice "docheckport() port not given" >:`Y]6z return GJqSN
i} fi n.y72-&v $sO}l port=$1 ;r[=
q u\ .{-8gAh clientlist=`netstat -an --tcp| grep ESTABLISHED | awk "{ if ( index(\\$4,\":$port\") ) print \\$5}" | awk -F ':' '{print $1}'|sort` H2RNekck if [ $? != 0 ] ; then M
T#9x> mylogger_notice "netstat call failed" k 9Kv return Pwz^{*u] fi |_~BV&g,N #echo $clientlist ~%Yh`c
EP # reset new_block K"b vUH new_block=0 +.\JYH=yEr count=0 xyz-T1ib total_count=0 6aQ{EO-]'= last_client="" x)vYc36H for client in $clientlist =4 JVUu~Z do rT}d<cSf #echo "client is $client" q}BQu@'H if [ -z "$last_client" ] ; then 6x/ X8zu count=$((count+1)) 05pCgI}F> total_count=$((total_count+1)) {Y'_QW1:2 last_client=$client Cv$TNkP* else
nI_Zk.R if [ "$client" = "$last_client" ] ; then vlj|[joXw count=$((count+1)) ]r"{G*1Q
9 total_count=$((total_count+1)) X?7$JV-: else s9[v_(W mylogger_debug "$last_client $count connections" eIqj7UY_ if [ $count -ge $max_active_conn ] ; then {&h &: mylogger_notice "client $last_client connection $count >= $max_active_conn" &aF_y_f\ blockclient $last_client $port 9I.v?Tap fi h0^V!.-5 count=1 VJR'B={h total_count=$((total_count+1)) ap6Vmp last_client=$client "!Qhk3* fi {YGz=5 ^ fi xd .I5 done dIpt&nH&$ # check the last client 2Qy!Aa if [ ! -z "$client" ] ; then @`_j't, count=$((count+1)) Iiy:<c total_count=$((total_count+1)) rL,)Tc|" mylogger_debug "$client $count connections" U|Jo[4A if [ $count -ge $max_active_conn ] ; then AQiP2`? mylogger_notice "client $client connection $count >= $max_active_conn" Z956S$gS blockclient $client $port 5~44R@` fi 9nG] .@H fi |v1 K@ mylogger_info "total connections on port $port: $total_count" {//F>5~[ `-/l$A}
U if [ $new_block = 1 ] ; then xBZ9|2Y s restartservice $port ipzUF o<w fi L$Leo6<3a } j0%0yb{-^ I|j tpv} docheckall() O\LW
8\M { ~r!5d@f.6 # reset wakeup_time {4QOUqA u wakeup_time=$wakeup_time_max ^i8I 1@ = for port in $portlist n>E*g|a do AslH
V@K docheckport $port -PnC^
r0L$ if [ $new_block = 1 ] ; then I1myu Z # set wakeup_time shorter cause we found some abuse client p\{+l;` wakeup_time=$wakeup_time_min 0lRH
Yu fi 2&Byq done [\b_+s)eN } |w JZU X}*o[;2G if [ -z "$firewall" ] && [ -f /etc/sysconfig/ipchains ] ; then 4Z}bw# firewall="ipchains" BJ9sR.yX62 fi CJ?gjV6 s3-ktZ@ if [ -z "$firewall" ] && [ -f /etc/sysconfig/iptables ] ; then Uxemlp%%* firewall="iptables" QklNw6, fi %EGr0R( u-[t~-(a if [ -z "$firewall" ] ; then #Q3PzDfj echo "Error: This machine does not have ipchains or iptables firewall support" rh`.$/^ exit 1 ;x-H$OZX fi d_C4B
p%"yBpSK mylogger_info "firewall.sh v$myver ValueOf.com starting" F:J7|<J^F mylogger_info "Firewall is: $firewall" ZB[(Tv1 mylogger_info "Port protected: $portlist" YvruK:I mylogger_info "Max connection per ip: $max_active_conn" ]&:b<]K3 mylogger_info "Min time to check: $wakeup_time_min""s" oM<!I0"gC+ mylogger_info "Max time to check: $wakeup_time_max""s"
,<3uc mylogger_info "Timeout circle: $rule_timeout""s" NGD*ce"w mylogger_info "Output is logged to: $log_facility" N\q)LM !M ole|J # if new ip blocked at this check run? !\0F.* new_block=0 Vf0fT?/K # if new ip blocked at this timeout run? 7':f_] ever_block=0 xP/OsaxN # reset wakeup_time #9`r XEz wakeup_time=$wakeup_time_max ejklpa ./ A)hhnb0o lasttime=`date +%s` -|}%~0)/bH
)C
{h1
` while [ 1 ] [5Fd P0 do b]*X<,p curtime=`date +%s` x_==Ss
timediff=$((curtime-lasttime)) 5VR.o!h3I #echo "timediff: $timediff" l"J*)P if [ $timediff -ge $rule_timeout ] && [ $ever_block = 1 ] ; then j z~[5m}J lasttime=$curtime (*,8KLV_i ever_block=0 s`hav dotimeout q2e]3{l3 fi {-@~Q.&}v docheckall l'U1
01M>F mylogger_info "sleep for $wakeup_time""s" ^m*3&x8 sleep $wakeup_time ITyzs4"VV done v f`9*x F {odA[H +W
9]ED RqXi1<6j# 1. 说明 91up^ firewall.sh是一个shell脚本程序,每隔一段时间检查tcp连接的统计信息,如果来自某个ip对某个端口的活动连接超过规定的最大数量, -kl;!:'.3 则自动将该IP对该端口的访问屏蔽,并重新启动相应的服务。再每隔一段时间,会重设防火墙到初始状态。 d.`&0 该程序可以同时保护多个端口 &5u BNpH ibJl;sJ 2. 安装 lEHwZ<je tar zxf firewall-1.0b.tar.gz "tL2F*F"6X cd firewall-1.0b FI{AZb_' install -m 700 firewall.sh /usr/prima/sbin/firewall.sh UfR~%p>K )lh8
k{ 3. 配置 |3;(~a)% 主要配置项目如下: -`7$Qu2 # 最小检查周期,缺省为120秒 ;i\C]* wakeup_time_min=120 CWi8Fv 0|XKd24BN # 最大检查周期,缺省为300秒 tPU-1by$ wakeup_time_max=600 Q[PK`*2) Hx
%$X # 重设防火墙状态的时间,缺省为3600秒 Mvb':/M rule_timeout=3600 8o|P&q(v* ]^K;goQv # 保护的端口列表,缺省为80和25,支持的其他端口包括21(ftp), 110(pop3), 53(named), 3306(mysql) t> .
Fl- # 一般的网络攻击都是针对80和25,又以80居多 exDkq0u] portlist="80 25" +Ok%e.\ZM NTmi 2c # 每个ip可占用的最大活动(Established)连接数 cp6WMHLj max_active_conn=8 ?6P.b6m}0 <7)Fh*W@ # iptables防火墙规则链名称,必须和/etc/sysconfig/iptables中一致 T_;]fPajjD # 如果用的是ipchains,可以忽略此项 3`F) AWzdr iptables_chain_name="RH-Lokkit-0-50-INPUT" )TJS4? XOy2lJ/ # 日志输出目标 #E$X,[ZFo log_facility="local0" 6f)2 F<
7 `tEo]p **** 关于检查周期 **** +dW|^I{H} 程序定义了两个检查周期,如果上次检查中屏蔽了某个IP,则程序会更频繁地检查连接情况,反之则等待更长时间。通过检查周期 DN8}glVxV 的动态调整,可以有效调度在遭受攻击和正常状态下程序的运行次数。 TgfrI
T~xwo
**** ipchains vs iptables **** cYNV\b4- 目前该程序支持ipchains和iptables两种软件防火墙,使用何种是由程序启动时自动检测的。如果/etc/sysconfig/ipchains和 QM<y`cZ8 /etc/sysconfig/iptables都没有检测到,则报错退出。 gTf|^?vd BR5BJX **** 日志输出 **** HU ;#XU1 程序的输出信息记录在系统日志中,目标是local0。如果没有特殊配置,可以在/var/log/messages中看到。建议在/etc/syslog.conf Vb|#MNf) 中加入一条: 1zxq^BI local0.* /var/log/firewall.log d_z59 然后重新启动syslog 'gMfN /etc/init.d/syslog restart tt_o$D
~kg 这样,可以将firewall.sh输出的日志单独记到文件/var/log/firewall.log里。 jXg b~m2tC=AW 4. 运行 |N /G'>TS /usr/prima/sbin/firewall.sh & =EP13J
/ |r
' 范例输出: TUK"nKSZ`. *** firewall.sh v1.0b ValueOf.com*** 4u;9J*r4 Firewall is: ipchains r=uN9ro Port protected: 80 25 ZP\M9J
a Max connection per ip: 8 Dim>
7Wbh Min time to check: 120s ||7x;2e Max time to check: 300s OR1DYHHT/1 Timeout circle: 3600s G3P&{.v Output is logged to: local0 >et-{(G g#]" hn 察看/var/log/firewall.log,可以看到: H9XvO Oct 16 14:08:55 server firewall.sh: do check port 80 // 检查80端口 tc;'oMUP Oct 16 14:08:55 server firewall.sh: 192.168.0.60 2 connections // 有两个来自192.168.0.60的连接 olB)p$aH# Oct 16 14:08:55 server firewall.sh: total connections on port 80: 2 // 80端口总共2个连接 VZr>U*J[: Oct 16 14:08:55 server firewall.sh: do check port 25 // 检查25端口 !%+2Yifna Oct 16 14:08:55 server firewall.sh: total connections on port 25: 0 // 25端口没有连接 (/d5UIM{& Oct 16 14:08:55 server firewall.sh: sleep for 300s // 等待300秒 Bs+(L [Z f),TO 5. 停止 @+vXMJ $ 先用ps命令察看firewall.sh进程的进程号,然后用kill命令将其终止,如 EF7+ *Q9 # ps auxww|grep firewall.sh h!~3Dw>,N root 27932 0.0 0.5 2312 1060 pts/2 S 12:38 0:00 /bin/sh /usr/prima/sbin/firewall.sh :P,sxDlG) root 27967 0.0 0.3 1732 592 pts/2 S 12:39 0:00 grep firewall.sh ^'CPM6J 第一行即firewall.sh的进程,用kill命令: O RGD # kill 27932 7Dzui
i?1 [1] Terminated /usr/prima/sbin/firewall.sh ~\ ,w { 即将其终止
|
常州五颜六色网络技术有限公司(5y6s Inc.) 旗下网站:5y6s Inc. | 五颜六色网 | 常州人社区
常州电信/网通机房,100M共享/10M独享/1000M共享/100M独享/电信+网通双线路服务器托管
Tel:0519-86605212 QQ:8732391 5y6s Inc.
|
|
[楼 主]
Posted:2008-01-26 02:12| |
| |