deserts
大客部
级别: 总版主
精华:
0
发帖: 607
威望: 2 点
金钱: 1061 RMB
贡献值: 0 点
在线时间:1761(小时)
注册时间:2006-01-01
最后登录:2025-02-11
|
linux自动屏蔽IP工具
另存为 firewall.sh 给执行的权限 60ciI
,_` ci2Z_JA+ #!/bin/sh 6!itr" # this program is used to check tcp/ip connections ..BP-N)V) # and block those ip with excessive connections \5j}6Wj w8$>
2 # my version \I}EWI myver="1.0RC1" K8[Um!( ]n"RPktx # wake up every 120s if last check found abuse client x3U>5F@ wakeup_time_min=120 <ty]z!B `x >6
Wk1 # wake up every 300s if last check found no abuse client 0,@^<G8? wakeup_time_max=300 /joY? T a%kvC#B # rule timeout 3600s R)SY#*Y rule_timeout=3600 -L6CEe eGpKoq7a # check port list 0&CXR=U5 portlist="80" [~\]<;;\ Z'!ORn#M # max established connection per ip 0&Ftx%6% max_active_conn=8 9v-Y*\!w. +|X`cmnuU # iptables chain name FAM:; F30 iptables_chain_name="RH-Lokkit-0-50-INPUT" b.?;I7r
='qVwM
[' # log facility ibwV#6 log_facility="local0" 's5rl Q_iN/F # Block policy XSK<hr0m ipchains_block_policy="DENY" LA2/<: iptables_block_policy="REJECT" _Ds,91<muQ 6dz^%Ub # myself ao .vB']T myself=`basename $0` ~Sm6{L 9xzow,mi mylogger_info() |V{ Q { ZbdGI@ logger -p $log_facility.info -t $myself $@ 2>/dev/null |%F4`gz8KP } HB}rpiB sb8bCEm-\ mylogger_debug() Nz`v+sp { whHuV*K} logger -p $log_facility.debug -t $myself $@ 2>/dev/null &Q}%b7 } lfC]!=2%~8 y6[ le*T mylogger_notice() 2?Jw0Wq5D { 0}`-vOLd- logger -p $log_facility.notice -t $myself $@ 2>/dev/null Z~-N'Lt{ } >.K%W*t 4Nt4(3Kf dotimeout() /w5*R5B{ { 8u
H8) mylogger_info "reset firewall when timeout arrives" .7b%7dQ<\ case "$firewall" in mR
XRuK ipchains) Z^as ?k(iM /etc/init.d/ipchains restart 1>/dev/null 2>/dev/null N_iy4W(NU if [ $? = 0 ] ; then Udn Rsp9S mylogger_info "ipchains restarted" g\
.$4N else $*%, mylogger_notice "ipchains restart failed" Khc^q*|C) fi zi
xG}' ;; C5TV}Bq\ iptables) Fc \]* /etc/init.d/iptables restart 1>/dev/null 2>/dev/null U1)Zh-aR if [ $? = 0 ] ; then 5BXku=M mylogger_info "iptables restarted" <anKw| else _]4p51r0 mylogger_notice "iptables restart failed" -wg}X-'z0 fi m<>BxX ;; J-d
B *) C]5 kQ1Og mylogger_notice "neither ipchains nor iptables" Q#SQ@oUzD ;; !R\FCAW[x esac R3|4|JlGR O |P<s+ } C7NSmZ 0: hv6Ge^ blockclient() llX ` { [tfB*m
5 if [ -z "$1" ] || [ -z "$2" ]; then lm;hW&O9 mylogger_notice "blockclient() missing client or port to block" 4l
%W]' return o68i0aFW fi a6DR' BC local ip port X7L:cVBg KU` *LB: ip=$1 |JYb4J4Ni port=$2 JJ?rVq1g ..u{v}4& case "$firewall" in 7mMGH
( ipchains) ZuGd{p$ mylogger_notice "blocking $1 to $2 via ipchains" <.4(#Ebd found=`ipchains -nL | egrep "^$ipchains_block_policy.*[[:space:]]+$ip[[:space:]]+.*[[:space:]]+\->[[:space:]]+$port"` 2Wluc37 if [ -z "$found" ] ; then oxc;DfJ_ cmd="ipchains -I input 1 -p tcp -s $ip -d 0/0 $port -j $ipchains_block_policy 1>/dev/null 2>/dev/null" B1nm?E 0i mylogger_debug "cmd: $cmd" MBA?, |9Q# `ipchains -I input 1 -p tcp -s $ip -d 0/0 $port -j $ipchains_block_policy 1>/dev/null 2>/dev/null` [%dsq`b# if [ $? != 0 ] ; then }BlyEcw'aN mylogger_notice "$cmd call failed" gUx}vE- return 63u%=-T%a
fi %`5(SC]. new_block=1 iG6]Pr|;e ever_block=1 zT,@PIC( else
OmWEa mylogger_info "$ip already blocked to $port" E! NtD).=S fi hTn"/|_SW ;; L4/ns@e iptables) $"/l*H\h mylogger_notice "blocking $1 to $2 via iptables" ,#ZPg_x?1 found=`iptables -nL | egrep "^$iptables_block_policy.*[[:space:]]+$ip[[:space:]]+.*[[:space:]]+dpt:$port[[:space:]]+"` /OztkThx= if [ -z "$found" ] ; then :wIA.1bK} 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" V[/9?5pM mylogger_debug "cmd: $cmd" u$a K19K/ `iptables -I $iptables_chain_name 1 -p tcp -m tcp -s $ip --dport $port -j $iptables_block_policy 1>/dev/null 2>/dev/null` -6- sI if [ $? != 0 ] ; then W$hCI)m( mylogger_notice "$cmd call failed" 2v ~8fr4 return a^J(TW
/ fi #0<pRDXj new_block=1 j
"<?9/r ever_block=1 ^;PjO|mD
Z else M{24MF mylogger_info "$ip already blocked to $port" _$>);qIP4 fi I20~bW ;; mU4(MjP? *) 0<`qz |_h mylogger_notice "neither ipchains nor iptables" cF15Mm2 ;; #(614-r/ esac /Kli C\ } cN&Ebn *$0*5d7 restartservice() 3 twA5)v { k)>H=?mI local service n+=qT$w) if [ -z "$1" ] ; then Xf&YcHo mylogger_notice "no port given to see which service to be restart" j%'2^C8 return 9~~NxWY%x fi L-?ty@-i Jt]RU+TB case "$1" in tjThQ 80)
s*gqKQ; service="httpd" 'm*W< ;; Gz{%Z$A~o 25) Lm}.+.O~d service="postfix" _$$.5?4 ;; )=GPhC/sw 110) P,] ./m\J service="courier-pop3d" hA 5p'a+K ;; Y({
R\W| 21) %7mGMa/ service="muddleftpd" _s@PL59, ;; Vc5>I_ 53) (mP{A(kwJ service="named" nyPeN?- ;; P x Q] $w 3306) 8:c=h/fa
service="mysqld" ]CLM'$ ;; $$ *tK8# esac R4 eu,,J if [ ! -z "$service" ] ; then z0LspRaz
/etc/init.d/$service restart 1>/dev/null 2>/dev/null w.58=Pr if [ $? = 0 ] ; then j|pTbOgk% mylogger_notice "$service restarted" bj@sci(1? else #%QHb,lhl mylogger_notice "$service restart failed" \k=dqWBr7 fi o#6QwbU25 fi [c=P)t7
V } cdkEK "|I.j) docheckport() hO[_ _j8 { rkji#\_-FV mylogger_info "do check port $1" \azMF} mb local port last_client count client total_count kCEuzd=$V ;MNUT,U if [ -z "$1" ] ; then G@Z%[YNw mylogger_notice "docheckport() port not given" >?K=l]!(* return Ox#vW6;)
fi U&6A)SW,k ,Tar?&C: port=$1 .9e5@@VR 'cc8xC clientlist=`netstat -an --tcp| grep ESTABLISHED | awk "{ if ( index(\\$4,\":$port\") ) print \\$5}" | awk -F ':' '{print $1}'|sort` ``<#F3 if [ $? != 0 ] ; then }0\SNpVN mylogger_notice "netstat call failed" pLe4dz WA return MzUKp" fi Qq.$!$ #echo $clientlist hd'fWFWN # reset new_block a]fFR~OY new_block=0
@,1_CqV count=0 8D`+3 total_count=0 bC+ZR{M last_client="" Sak^J.~G[ for client in $clientlist kJ"rRsK do FJH>P\+ #echo "client is $client" Y>aVnixx< if [ -z "$last_client" ] ; then sryA(V
count=$((count+1)) U@).jpN total_count=$((total_count+1)) Dti-*LB1 last_client=$client ~SBW`=aP} else MVzj7~+ if [ "$client" = "$last_client" ] ; then Gi-pi=#&cs count=$((count+1)) gzi=+oJ|4 total_count=$((total_count+1)) >F^$
' b] else =%I[
o=6 mylogger_debug "$last_client $count connections" EwG+' nlE if [ $count -ge $max_active_conn ] ; then [V_mF mylogger_notice "client $last_client connection $count >= $max_active_conn" 5K9W5hA:D blockclient $last_client $port jA?[*HB fi 5YPIv- count=1 b/*QV0( total_count=$((total_count+1)) 3F;0a ;[ last_client=$client w7~]c,$y. fi ,[p?u']yZz fi yg}L,JJU< done =3h
Jti9[
# check the last client sCy.i/y if [ ! -z "$client" ] ; then =>Ae]mi7 count=$((count+1)) h\#4[/ total_count=$((total_count+1)) H4v%$R;K mylogger_debug "$client $count connections" :,H_
e!
X if [ $count -ge $max_active_conn ] ; then </<z7V,{ mylogger_notice "client $client connection $count >= $max_active_conn" `,pBOh|' blockclient $client $port _`QME r? fi gHUW1E fi 056yhB mylogger_info "total connections on port $port: $total_count" hHw1<! M nC/T$
#G if [ $new_block = 1 ] ; then coaJDg+ restartservice $port ')
F@em fi Np9Pae' } jkuNafp} ND9;%<80 docheckall() !5m~qet. { 'uUa|J1mu # reset wakeup_time z
SsogAx wakeup_time=$wakeup_time_max W#b++}S for port in $portlist _;(QMeR do \hzx? docheckport $port qj*
BV if [ $new_block = 1 ] ; then $[=`*m # set wakeup_time shorter cause we found some abuse client JLyFkV/
wakeup_time=$wakeup_time_min !})3Fb fi Pt;\]?LVrD done p-g@cwOu } Xw^:<Nx: K
e&fTK if [ -z "$firewall" ] && [ -f /etc/sysconfig/ipchains ] ; then tK <)A) firewall="ipchains" kS7T'[d fi ~0.@1zEXj ]}0+7Q if [ -z "$firewall" ] && [ -f /etc/sysconfig/iptables ] ; then R91u6r# firewall="iptables" n_] OYG>U fi ~Uz|sQ*G JeCEj=_Z if [ -z "$firewall" ] ; then `V0]t_*D echo "Error: This machine does not have ipchains or iptables firewall support" wY}+d0Ch exit 1 Y.Ew;\6U fi V'?nS&,i 9zd)[4%= mylogger_info "firewall.sh v$myver ValueOf.com starting" J.`.lQ$z mylogger_info "Firewall is: $firewall" veE8
N~0N. mylogger_info "Port protected: $portlist" }#u}{ mylogger_info "Max connection per ip: $max_active_conn" ^jhHaN]G^ mylogger_info "Min time to check: $wakeup_time_min""s" 2W~2Hk=0+% mylogger_info "Max time to check: $wakeup_time_max""s" ?,),%JQ mylogger_info "Timeout circle: $rule_timeout""s" IweQB} d mylogger_info "Output is logged to: $log_facility" z?YGE iR/} Ip1QmP # if new ip blocked at this check run? h/w- &7t new_block=0 -s!PO;qm # if new ip blocked at this timeout run? cE]kI,Fw,M ever_block=0 Hm^p^,}_x # reset wakeup_time *AN#D?X_ wakeup_time=$wakeup_time_max EX5kF },L[bDOV07 lasttime=`date +%s` r#~6FpFVK^ q
B2#EsZ while [ 1 ] xX
>448= do 4'8.f5 curtime=`date +%s` Ek.j@79 timediff=$((curtime-lasttime)) +[7u>RJ #echo "timediff: $timediff" wLbnsqa if [ $timediff -ge $rule_timeout ] && [ $ever_block = 1 ] ; then Stw6%T- lasttime=$curtime Q&\k"X 1 ever_block=0 ?d%}K76V< dotimeout )G|UB8] fi `'QPe42 docheckall [6tQv<}^ mylogger_info "sleep for $wakeup_time""s" $7*Ml)H!9 sleep $wakeup_time &Gt9a-ne done i\'N1S<D _8>"&1n /L
4WWQ5 ij),DbWd 1. 说明 6bn-NY:i firewall.sh是一个shell脚本程序,每隔一段时间检查tcp连接的统计信息,如果来自某个ip对某个端口的活动连接超过规定的最大数量, {Q"<q`c 则自动将该IP对该端口的访问屏蔽,并重新启动相应的服务。再每隔一段时间,会重设防火墙到初始状态。 StVv"YY 该程序可以同时保护多个端口 aU! UY( -wt2ydzos 2. 安装 $b$D[4 tar zxf firewall-1.0b.tar.gz {%Y7]*D cd firewall-1.0b Z-?9F`} install -m 700 firewall.sh /usr/prima/sbin/firewall.sh (!(bysi9 GXl?Zg 3. 配置 Id0F2 [ 主要配置项目如下: ~83P09\T% # 最小检查周期,缺省为120秒 +*q@= P, wakeup_time_min=120 J Nz0!wi L9@jmh*E # 最大检查周期,缺省为300秒 ){:aGGtko wakeup_time_max=600 ;=OH=+Rl (Wqhuw!u
# 重设防火墙状态的时间,缺省为3600秒 gib]#n1!p rule_timeout=3600 ^d*>P|n*@e V]}b3Y!( # 保护的端口列表,缺省为80和25,支持的其他端口包括21(ftp), 110(pop3), 53(named), 3306(mysql) as4NvZ@+r # 一般的网络攻击都是针对80和25,又以80居多 @El<"\ portlist="80 25" cIp h$@ A
h6x2(: # 每个ip可占用的最大活动(Established)连接数 [Bo$? max_active_conn=8 3D0I5LF& ^@2Vh*k # iptables防火墙规则链名称,必须和/etc/sysconfig/iptables中一致 mtHz
6+ # 如果用的是ipchains,可以忽略此项 HV.7IyBA^ iptables_chain_name="RH-Lokkit-0-50-INPUT" f,>i%. ]o$/xP # 日志输出目标 Pa +BE[z log_facility="local0" (xed(uFEK ~0|hobk **** 关于检查周期 **** ~*Qpv&y) 程序定义了两个检查周期,如果上次检查中屏蔽了某个IP,则程序会更频繁地检查连接情况,反之则等待更长时间。通过检查周期 1.uQ(>n 的动态调整,可以有效调度在遭受攻击和正常状态下程序的运行次数。 a7G2C oM8 Y;Gm, **** ipchains vs iptables **** |$2N$6\SP 目前该程序支持ipchains和iptables两种软件防火墙,使用何种是由程序启动时自动检测的。如果/etc/sysconfig/ipchains和 Vz]=J;`Mz /etc/sysconfig/iptables都没有检测到,则报错退出。 P*Sip?tdE FaE orQ **** 日志输出 **** El
s= :4 程序的输出信息记录在系统日志中,目标是local0。如果没有特殊配置,可以在/var/log/messages中看到。建议在/etc/syslog.conf NfF:[qwh 中加入一条: 79g>7<vp local0.* /var/log/firewall.log /ASI0h 然后重新启动syslog M) XQi/ /etc/init.d/syslog restart PSS/JFZ^ 这样,可以将firewall.sh输出的日志单独记到文件/var/log/firewall.log里。 I>Fh*2 XF$]KAL0 4. 运行 DW&')gfQ /usr/prima/sbin/firewall.sh & q.Z#7~6`3 fcXk]W 范例输出: b
CUh^#]x *** firewall.sh v1.0b ValueOf.com*** 6D"`FPC Firewall is: ipchains ]},Q`n>$ Port protected: 80 25 wg0.i?R-] Max connection per ip: 8 <SdJM1%Qo Min time to check: 120s {eN{Zh5" Max time to check: 300s ]V^.!=gh$ Timeout circle: 3600s l!V| T? Output is logged to: local0 i}F;fWZ` _|wY[YJ[ 察看/var/log/firewall.log,可以看到: Z)T@`B6
Oct 16 14:08:55 server firewall.sh: do check port 80 // 检查80端口 T-2p`b}hW Oct 16 14:08:55 server firewall.sh: 192.168.0.60 2 connections // 有两个来自192.168.0.60的连接 @<TZH Oct 16 14:08:55 server firewall.sh: total connections on port 80: 2 // 80端口总共2个连接 T^;Jz!e Oct 16 14:08:55 server firewall.sh: do check port 25 // 检查25端口 f<4q ]HCa Oct 16 14:08:55 server firewall.sh: total connections on port 25: 0 // 25端口没有连接 {^5<{j3e Oct 16 14:08:55 server firewall.sh: sleep for 300s // 等待300秒 V3~a!k -L
3
|
9k
5. 停止 Q*&aC|b& 先用ps命令察看firewall.sh进程的进程号,然后用kill命令将其终止,如
7a]Zws # ps auxww|grep firewall.sh pMZf!&tM root 27932 0.0 0.5 2312 1060 pts/2 S 12:38 0:00 /bin/sh /usr/prima/sbin/firewall.sh q
'{<c3& root 27967 0.0 0.3 1732 592 pts/2 S 12:39 0:00 grep firewall.sh
)P9{47 第一行即firewall.sh的进程,用kill命令: 1o~U+s_r # kill 27932 +'Y(V& [1] Terminated /usr/prima/sbin/firewall.sh Nw>T$RzS 即将其终止
|
常州电信/网通机房,100M共享/10M独享/1000M共享/100M独享/电信+网通双线路服务器托管
Tel:0519-89991155 企业QQ:4006023839 5y6s Inc.
|
[楼 主]
|
Posted: 2008-01-26 02:12 |
| |