deserts
大客部
级别: 总版主
精华:
0
发帖: 622
威望: 2 点
金钱: 1096 RMB
贡献值: 0 点
在线时间:1766(小时)
注册时间:2006-01-01
最后登录:2026-07-26
|
linux自动屏蔽IP工具
另存为 firewall.sh 给执行的权限
G8`q-B}q R!xs;|] #!/bin/sh [!{*
)4$6 # this program is used to check tcp/ip connections daBu<0\ # and block those ip with excessive connections ".| 9h ~Dr/+h:^\ # my version zQxZR}' myver="1.0RC1" JGZ,5RTq4- io
cr # wake up every 120s if last check found abuse client xkl'Y * wakeup_time_min=120 ZeK*MPxQ n6WSTh # wake up every 300s if last check found no abuse client r6]r+!63" wakeup_time_max=300 cl2@p@av O:q}<ljp # rule timeout 3600s AEK * w4 rule_timeout=3600 uf`o\wqU z>k6 T4( # check port list _h_;nS.Y portlist="80" PiI ):B> F=B>0Q5 # max established connection per ip qYIBP?`g max_active_conn=8 %k
NkDI j]J2,J # iptables chain name ?C.C?h6F5B iptables_chain_name="RH-Lokkit-0-50-INPUT" )rhKWg -J!F((jt # log facility 4_PMl6qo log_facility="local0" F.?:Gd1 UOF5&>MLb # Block policy 2b1LC!'U ipchains_block_policy="DENY" l/LRr.x iptables_block_policy="REJECT" :@_CQc*yB |Y/iq9l
# myself @[zPN[z. myself=`basename $0` HJBUN1n A &w)@DOe mylogger_info() w
\0=L=J { HtY\!_Ea logger -p $log_facility.info -t $myself $@ 2>/dev/null :BMU c-[ } PhKJ#DRbr %~Nf, mylogger_debug() o,bV.O.W { ?ZlwRjB\ logger -p $log_facility.debug -t $myself $@ 2>/dev/null 3m7$$N| } 'y-IE#!5 qK|r+}g|& mylogger_notice() a;*&q/{o { _z,/!>J logger -p $log_facility.notice -t $myself $@ 2>/dev/null p4{?Rhb6 } sS5#Q =5dv38 dotimeout() *XtZ;os] { +|#sF,,X4g mylogger_info "reset firewall when timeout arrives" lt,x(2 case "$firewall" in ,Hy
s9I ipchains) _?q\tyf3 /etc/init.d/ipchains restart 1>/dev/null 2>/dev/null G-"#3{~2 if [ $? = 0 ] ; then dUjdQ mylogger_info "ipchains restarted" ml?+JbLg0 else qViky=/- mylogger_notice "ipchains restart failed" y0(k7D|\ fi vNE91 ;; iy$]9Wf6=@ iptables) P.;B
V", /etc/init.d/iptables restart 1>/dev/null 2>/dev/null mhlJzGr*q if [ $? = 0 ] ; then B>?. Nr mylogger_info "iptables restarted" o6vm(I% else |:H[Y"$1; mylogger_notice "iptables restart failed" DeXnE$XH fi t~
U:{g~ ;; >xP $A{ *) ^{~y+1lt' mylogger_notice "neither ipchains nor iptables" sF|<m)Kt{W ;; Iupk+x> esac h ?p^DPo 2@e<II2ha8 } NaVZ) <'GI<Hc blockclient() Q3oVl^q { fep#Kb%"e if [ -z "$1" ] || [ -z "$2" ]; then \f{C2d/6j mylogger_notice "blockclient() missing client or port to block" 25YJH1x return dAAE2}e fi Keof{>V=CA local ip port VnIJ$5Y 39m# ip=$1 @@# G. port=$2 YtIJJH iY*Xm,# case "$firewall" in \>I&UFfH)4 ipchains) Yq;S%. mylogger_notice "blocking $1 to $2 via ipchains" i[jAAr$ found=`ipchains -nL | egrep "^$ipchains_block_policy.*[[:space:]]+$ip[[:space:]]+.*[[:space:]]+\->[[:space:]]+$port"` -?e~S\JH if [ -z "$found" ] ; then ?}lCS7& cmd="ipchains -I input 1 -p tcp -s $ip -d 0/0 $port -j $ipchains_block_policy 1>/dev/null 2>/dev/null" AK[9fxrE mylogger_debug "cmd: $cmd" NTVG'3o `ipchains -I input 1 -p tcp -s $ip -d 0/0 $port -j $ipchains_block_policy 1>/dev/null 2>/dev/null` o.k#|q if [ $? != 0 ] ; then =<33( mylogger_notice "$cmd call failed" teM&[U return 5IMh$!/uc fi B>~E6j7[Mp new_block=1 jkPXkysm ever_block=1 q:nYUW o else ;%U`lE0 mylogger_info "$ip already blocked to $port" qtgj"4,:` fi ]HCt%5 ;; >xH3*0Lp iptables) 0>.'w\,87B mylogger_notice "blocking $1 to $2 via iptables" $'[(
DwLS found=`iptables -nL | egrep "^$iptables_block_policy.*[[:space:]]+$ip[[:space:]]+.*[[:space:]]+dpt:$port[[:space:]]+"` #UGbSOoCtn if [ -z "$found" ] ; then 8SKDL[rN 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" zHx
?-Q&3 mylogger_debug "cmd: $cmd" xp,H5
m% `iptables -I $iptables_chain_name 1 -p tcp -m tcp -s $ip --dport $port -j $iptables_block_policy 1>/dev/null 2>/dev/null` e=_*\`/CN if [ $? != 0 ] ; then s'5
jvlG mylogger_notice "$cmd call failed" }*0%wP return g\6(ezUF* fi {O!fV<Vx 9 new_block=1 L(X:=)
!K0 ever_block=1 n}._Nb
5 else cLB"<mG mylogger_info "$ip already blocked to $port"
ozGK
-$ fi 3EzI~Zsx ;; =8<SKY&\X *) 47t^{WrT mylogger_notice "neither ipchains nor iptables" oR3$A :!P= ;; UkeW2l`: esac a:P%
r } ."=Bx2 1FY^_dvH restartservice() _<5>
E { 2#|Q=rWB local service )~!Gs/w6 if [ -z "$1" ] ; then 9BHl2<&V mylogger_notice "no port given to see which service to be restart" m~X
:KwK4 return Ba@UX(t fi !5p01]7 HW{+THNj case "$1" in !f"@pR6 80) <v0 d8 service="httpd" jQ`cfE$sV ;; Dwwh;B 25) iiO4.@nT service="postfix" w'cZ\<N[ ;; zJtYy4jI) 110) 'fZHtnmc0 service="courier-pop3d" _L&C4 <e' ;; Rrk3
EL 21) /S P^fB*y service="muddleftpd" <!4'?K -N ;; +vZ-o{}.jO 53) ? NVN&zD] service="named" C2bN<K ;; Tpkm\_ 3306) b+3{ bE service="mysqld" lZE x0 ;; Pm
V:J9 esac !a4pKN`qLY if [ ! -z "$service" ] ; then 7
2luTR Q /etc/init.d/$service restart 1>/dev/null 2>/dev/null
,9 if [ $? = 0 ] ; then NcFHvK mylogger_notice "$service restarted" x!gu&AA<* else Smg,1,= mylogger_notice "$service restart failed" \%rX~UhZ= fi -:>Mi5/ s fi 0FHN
} A"i40 @+ "J7=3$CA docheckport() t"JfqD E { |a/"7B|?\ mylogger_info "do check port $1" jSpmE
local port last_client count client total_count n$B=Vt, :J}L| `U9 if [ -z "$1" ] ; then #k5Nnv#(J mylogger_notice "docheckport() port not given" x4R[Q&:M return 7s1FJm=Y/ fi $oe:km1-D XwE(&ZCf'b port=$1 >>F E?@ h@@2vs2 clientlist=`netstat -an --tcp| grep ESTABLISHED | awk "{ if ( index(\\$4,\":$port\") ) print \\$5}" | awk -F ':' '{print $1}'|sort` @e3O=_m- if [ $? != 0 ] ; then FE" ksi 9 mylogger_notice "netstat call failed" M7BJ$fA0E return ?tV $o,11 fi Ae;>
@k/|= #echo $clientlist o.*8$$ # reset new_block fu"#C}{ new_block=0 &X
}GJLC3 count=0
4&&((H
total_count=0 pa`"f&JO last_client="" LlrUJ-uC7 for client in $clientlist 48Vmz do 294
0M4 #echo "client is $client" u|BD=4* if [ -z "$last_client" ] ; then T/X[q7O~~4 count=$((count+1)) eR$qw#%c* total_count=$((total_count+1)) B>AmH%f/ last_client=$client j(AN]g: else ]p:s5Q if [ "$client" = "$last_client" ] ; then ?h2!Z{[0b count=$((count+1)) ?>92OuG%W? total_count=$((total_count+1)) f!|7j}3 else ]+u`E mylogger_debug "$last_client $count connections" 2_'{f1bVxz if [ $count -ge $max_active_conn ] ; then nYhI0q mylogger_notice "client $last_client connection $count >= $max_active_conn" 7O',X Y blockclient $last_client $port F=?0:2P0bD fi x|g>Zd/n count=1 o
EXN$SIs total_count=$((total_count+1)) ixm-wZI last_client=$client E4idEQ}H fi GTgG0Ifeh fi #e|G!'wdj done <H03i"Z/S # check the last client kG 7]<^Os3 if [ ! -z "$client" ] ; then YflM*F` count=$((count+1)) 9f1,E98w_ total_count=$((total_count+1)) Wwo'pke
mylogger_debug "$client $count connections" @#m@ . if [ $count -ge $max_active_conn ] ; then \JjZ _R mylogger_notice "client $client connection $count >= $max_active_conn" ' b1k0 9' blockclient $client $port jNV)=s^ed[ fi <vS3[( fi '&v.h#< mylogger_info "total connections on port $port: $total_count" K{DsGf, 2aj9:S if [ $new_block = 1 ] ; then R2K{vs restartservice $port 5AFy6Ab fi f0Wbc\L[ } EGJ d:>k b&]_5 GGc docheckall() H 5\k`7R { gu:8+/W8L # reset wakeup_time X"hdCY% wakeup_time=$wakeup_time_max 9feVy\u
for port in $portlist
yn`P:[v do Ov<EOK+^ docheckport $port kxvzAKz~ if [ $new_block = 1 ] ; then #M/^n0E # set wakeup_time shorter cause we found some abuse client P6G&3yPt wakeup_time=$wakeup_time_min zvEofK fi cpLlkR O done <A~a|A-QFR }
vIzREu|5 "/ 9EUbca if [ -z "$firewall" ] && [ -f /etc/sysconfig/ipchains ] ; then ,y>Sq
+ firewall="ipchains" ctk~}(1# fi (i 2R1HCa ^osXM` if [ -z "$firewall" ] && [ -f /etc/sysconfig/iptables ] ; then A.YXK%A% firewall="iptables" Vf*Z }' fi iY[+BI: Bz+zEXBC if [ -z "$firewall" ] ; then BG&XCn5g| echo "Error: This machine does not have ipchains or iptables firewall support" ,h<xL- exit 1 {wL30D^ fi s;!_'1pi@ ,%=SO 82W mylogger_info "firewall.sh v$myver ValueOf.com starting" :HiAjaA1pg mylogger_info "Firewall is: $firewall" d!P3<:+R[ mylogger_info "Port protected: $portlist" KkJrh@lk mylogger_info "Max connection per ip: $max_active_conn" '$q=r x mylogger_info "Min time to check: $wakeup_time_min""s" Vu=e|A# mylogger_info "Max time to check: $wakeup_time_max""s" ! 'qY mylogger_info "Timeout circle: $rule_timeout""s" \#(tI3 mylogger_info "Output is logged to: $log_facility" +x(~!33[G A||,|He~ # if new ip blocked at this check run? AY x*Ngn new_block=0 u
mo<9Y # if new ip blocked at this timeout run? *ufVZzP( ever_block=0 DQI
b57j # reset wakeup_time Z<IN>:l wakeup_time=$wakeup_time_max I<+i
87= +bDBc?HZ{$ lasttime=`date +%s` {9Ug9e{
~ sS{!z@\Lf while [ 1 ] 4.e0k<]N` do 1=L5=uz1d: curtime=`date +%s` =kP|TR!o- timediff=$((curtime-lasttime)) UFzC8 #echo "timediff: $timediff" w!|jL
$5L if [ $timediff -ge $rule_timeout ] && [ $ever_block = 1 ] ; then +R2+?v6 lasttime=$curtime >[0t@Tu,D ever_block=0 vdaG?+_o dotimeout M .oH,Kd6 fi H8!)zZ docheckall OK" fFv mylogger_info "sleep for $wakeup_time""s" 34F;mr"yp sleep $wakeup_time !nDiAjj done V\nj7Gr:sF >&YUV.mLY mW=9WV 85:KlBe%+ 1. 说明 Y(&rlL(sPK firewall.sh是一个shell脚本程序,每隔一段时间检查tcp连接的统计信息,如果来自某个ip对某个端口的活动连接超过规定的最大数量, _;mA(j 则自动将该IP对该端口的访问屏蔽,并重新启动相应的服务。再每隔一段时间,会重设防火墙到初始状态。 b6NGhkr'\ 该程序可以同时保护多个端口 0[ZB ^ $1y8X K7r 2. 安装 }2hU7YWt tar zxf firewall-1.0b.tar.gz 37b6w6{D cd firewall-1.0b i`}!<{k install -m 700 firewall.sh /usr/prima/sbin/firewall.sh jG`,k*eUrJ wx8Qz,Z 3. 配置
WH_
W: 主要配置项目如下: watTV\b # 最小检查周期,缺省为120秒 '{w[).c. wakeup_time_min=120 ?vP6~$*B y!c<P,Lt3f # 最大检查周期,缺省为300秒 .*B@1q
wakeup_time_max=600 N~ajrv}kd eD|"?@cE # 重设防火墙状态的时间,缺省为3600秒 I7HGV( rule_timeout=3600 !0_/=mA^ yqC158 P # 保护的端口列表,缺省为80和25,支持的其他端口包括21(ftp), 110(pop3), 53(named), 3306(mysql) sI6I5 # 一般的网络攻击都是针对80和25,又以80居多 ^^g u portlist="80 25" h_Ssm{C\ D?FmlDTr[ # 每个ip可占用的最大活动(Established)连接数 *v$j n max_active_conn=8 [A'e
7Do%' V4&a+MJ@ # iptables防火墙规则链名称,必须和/etc/sysconfig/iptables中一致 y eam-8 # 如果用的是ipchains,可以忽略此项 Pk;1q?tGw iptables_chain_name="RH-Lokkit-0-50-INPUT" ^{YK'60
9g|99Z # 日志输出目标 m%nRHT0KAf log_facility="local0" W$<Y**y9m gnYo/q=K **** 关于检查周期 **** 2FY]o~@ 程序定义了两个检查周期,如果上次检查中屏蔽了某个IP,则程序会更频繁地检查连接情况,反之则等待更长时间。通过检查周期 \Xe{vlo>h 的动态调整,可以有效调度在遭受攻击和正常状态下程序的运行次数。 Tb!FO"o ;oO_5[,M **** ipchains vs iptables **** A-, hm=? 目前该程序支持ipchains和iptables两种软件防火墙,使用何种是由程序启动时自动检测的。如果/etc/sysconfig/ipchains和 B.!&z-)# /etc/sysconfig/iptables都没有检测到,则报错退出。
h;@>E:4Tg SW5n?Qj3- **** 日志输出 **** d)0|Q 程序的输出信息记录在系统日志中,目标是local0。如果没有特殊配置,可以在/var/log/messages中看到。建议在/etc/syslog.conf P4LiU2C 中加入一条: e jR_3K^ local0.* /var/log/firewall.log mi1^hl'2 然后重新启动syslog qDqy9u:g /etc/init.d/syslog restart "$P/ek 这样,可以将firewall.sh输出的日志单独记到文件/var/log/firewall.log里。 A%X=yqY Z;[xaP\S 4. 运行 z "z /usr/prima/sbin/firewall.sh & f@q.kD21 6@"E*-z$ 范例输出: 8kC$
Z ) *** firewall.sh v1.0b ValueOf.com*** HXX9D&c4R Firewall is: ipchains 76]Z~^Y Port protected: 80 25 A-d<[@d0 Max connection per ip: 8 k2fJ Min time to check: 120s S(^YTb7 Max time to check: 300s BS?i!Bm 7 Timeout circle: 3600s cP4C<UG Output is logged to: local0 e&E7_ Aar
]eY\ 察看/var/log/firewall.log,可以看到: &gW<v\6, Oct 16 14:08:55 server firewall.sh: do check port 80 // 检查80端口 !T2{xmHKv$ Oct 16 14:08:55 server firewall.sh: 192.168.0.60 2 connections // 有两个来自192.168.0.60的连接 {=,G>p Oct 16 14:08:55 server firewall.sh: total connections on port 80: 2 // 80端口总共2个连接 rP,| Oct 16 14:08:55 server firewall.sh: do check port 25 // 检查25端口 ;#+I"Ow Oct 16 14:08:55 server firewall.sh: total connections on port 25: 0 // 25端口没有连接 SL/'UoYm< Oct 16 14:08:55 server firewall.sh: sleep for 300s // 等待300秒 X"mPRnE330 ,L<x=Dg 5. 停止 2Dt^W.! 先用ps命令察看firewall.sh进程的进程号,然后用kill命令将其终止,如
DZ4gp # ps auxww|grep firewall.sh D=Nt0y root 27932 0.0 0.5 2312 1060 pts/2 S 12:38 0:00 /bin/sh /usr/prima/sbin/firewall.sh P)XR9&o': root 27967 0.0 0.3 1732 592 pts/2 S 12:39 0:00 grep firewall.sh /|#2ehE 第一行即firewall.sh的进程,用kill命令: hN*v|LFf1 # kill 27932 .r&CIL> [1] Terminated /usr/prima/sbin/firewall.sh 65VTKlDD 即将其终止
|
常州电信/网通机房,100M共享/10M独享/1000M共享/100M独享/电信+网通双线路服务器托管
Tel:0519-89991155 企业QQ:4006023839 5y6s Inc.
|
|
[楼 主]
|
Posted: 2008-01-26 02:12 |
| |