deserts
大客部
级别: 总版主
精华:
0
发帖: 607
威望: 2 点
金钱: 1061 RMB
贡献值: 0 点
在线时间:1761(小时)
注册时间:2006-01-01
最后登录:2025-02-11
|
linux自动屏蔽IP工具
另存为 firewall.sh 给执行的权限 h
pJ-r m4yL@d,Yw #!/bin/sh 6`-jPR # this program is used to check tcp/ip connections bYPKh # and block those ip with excessive connections .>nRzgo ],v=]+R # my version s|ITsz0,td myver="1.0RC1" 4'Zp-k?5` V470C@ # wake up every 120s if last check found abuse client Xs?o{]Fe wakeup_time_min=120 C'X!\}f.b/ Oc; G(l( # wake up every 300s if last check found no abuse client 40<mrVl wakeup_time_max=300 IaXeRq?< O7IJ%_A& # rule timeout 3600s E@3aI
Axh rule_timeout=3600 -
D$8 #1G:lhkC # check port list >e"#'K0?\ portlist="80" DDH:)=;z !GGkdg*-*9 # max established connection per ip {Dmjm{
max_active_conn=8 :4%k9BGAj" >oe]$r # iptables chain name :[!j?)%> iptables_chain_name="RH-Lokkit-0-50-INPUT" Nu7
!8[?r* 5o8EC"
0 # log facility tC9n
k5~ log_facility="local0" N'`A?&2ru 7x4PaX( # Block policy sp*v?5lW ipchains_block_policy="DENY" R!N%o~C2- iptables_block_policy="REJECT" l2P=R)@{ p"ZG%Ow5Q] # myself 1HZO9cXJ myself=`basename $0` =rCIumqD-} Ak"m 85B mylogger_info() 5,6"&vU, { ah+iZ}E% logger -p $log_facility.info -t $myself $@ 2>/dev/null
O+Y6N } 1Z~FCJz b7?h
I mylogger_debug() 8C9-_Ng` { <;Zmjeb+# logger -p $log_facility.debug -t $myself $@ 2>/dev/null I75DUJqy] } zv,jM0- o!ebs0 mylogger_notice() @8r pD"x { D!-g&HBTC logger -p $log_facility.notice -t $myself $@ 2>/dev/null Ks`J([(W& } xBi' X ")XHak.JX dotimeout() G^4hd i3@ {
MC.)2B7 mylogger_info "reset firewall when timeout arrives" V7fq4O^: case "$firewall" in 2?ez,*-[ ipchains) P%&0]FCx /etc/init.d/ipchains restart 1>/dev/null 2>/dev/null c?[I?ytl if [ $? = 0 ] ; then Ata:^qI mylogger_info "ipchains restarted" %oa-WmWm else }"%?et( mylogger_notice "ipchains restart failed" SdxDa fi 94.DHZqh ;; BdblLUGK# iptables) k(7&N0V%zz /etc/init.d/iptables restart 1>/dev/null 2>/dev/null .P%bkD6M if [ $? = 0 ] ; then Nk VK mylogger_info "iptables restarted" ]i ,{ else VfC<WVYiZ mylogger_notice "iptables restart failed" ][h%UrV fi $f=J2&D,Cz ;; s.N/2F&*W *) q{I%Q)t)gU mylogger_notice "neither ipchains nor iptables" Ed,~1GanY ;; 1&evG-#<: esac ujq=F Eo
g0TQ+* } u4F5h PO] >j(_[z|v3 blockclient() (\hx` Yh=> { q#ClnG* if [ -z "$1" ] || [ -z "$2" ]; then |w1Bq mylogger_notice "blockclient() missing client or port to block" }`QUHIF return tip+q d fi zrL$]Oy}x local ip port [OV"}<V i,E{f ip=$1 rc>4vB_ha port=$2 &(G\[RWp\
bv9i*] case "$firewall" in ?U5{Wa85D ipchains) T/Gz94c mylogger_notice "blocking $1 to $2 via ipchains" [.8BTj1% found=`ipchains -nL | egrep "^$ipchains_block_policy.*[[:space:]]+$ip[[:space:]]+.*[[:space:]]+\->[[:space:]]+$port"` YpZ+n*&+ if [ -z "$found" ] ; then t?ZI".> cmd="ipchains -I input 1 -p tcp -s $ip -d 0/0 $port -j $ipchains_block_policy 1>/dev/null 2>/dev/null" YEs& mylogger_debug "cmd: $cmd" 4 \K7xM! `ipchains -I input 1 -p tcp -s $ip -d 0/0 $port -j $ipchains_block_policy 1>/dev/null 2>/dev/null` *1
]uH e if [ $? != 0 ] ; then oMD>Ywc- mylogger_notice "$cmd call failed" 5k3n\sqZA return 3n1;G8Nf fi m
)zUU new_block=1 +EAsW(F1 ever_block=1 =wHVsdNCN else t#/YN.@r mylogger_info "$ip already blocked to $port" P[#e/qnXu| fi V>%rv'G8 ;; Ovt.!8 iptables) 9J*\T(W mylogger_notice "blocking $1 to $2 via iptables" }[};IqVaK found=`iptables -nL | egrep "^$iptables_block_policy.*[[:space:]]+$ip[[:space:]]+.*[[:space:]]+dpt:$port[[:space:]]+"` N/'b$m5=
S if [ -z "$found" ] ; then BB$>h} 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" GR.^glG?6 mylogger_debug "cmd: $cmd" Z{Qu<vy_ `iptables -I $iptables_chain_name 1 -p tcp -m tcp -s $ip --dport $port -j $iptables_block_policy 1>/dev/null 2>/dev/null` >,Ci?[pf if [ $? != 0 ] ; then fZzoAzfv2 mylogger_notice "$cmd call failed" E`0
? return r1m]HFN fi qQ/^@3tXL new_block=1 )VS=E7[ ever_block=1 k&q;JyUi else B=T'5
& mylogger_info "$ip already blocked to $port" 4qh?,^Dq fi #n#}s ;; 8f4b&ah *) LTCb@L{^i mylogger_notice "neither ipchains nor iptables" wn, KY$/ ;; SC!RbW@3 esac 4JXeV&5Qk' } *NaB#;+|k` 0c]/bs{} restartservice() ,vawzq[oSy { a=1@*ID local service =.U[$~3q% if [ -z "$1" ] ; then <CiSK! mylogger_notice "no port given to see which service to be restart" ^Za-`8#`L return P[ck84F/ fi {.|CdqwY TnA-;Ha case "$1" in j#x
6
80) fk>aqm7D! service="httpd" )
7@ `ut ;; \fdv]f 25) eA?RK.e service="postfix" aCj&O:]= ;; vF+7V*< 110) vX"*4m>b?+ service="courier-pop3d" 1#2
I ;; @ioJ]$o7 21) Bahm]2 service="muddleftpd" KqJs?Won ;; s`8= 3]w 53)
69NeQ$]( service="named" }C?'BRX ;; 7U"g3a)= 3306) q:0N<$63 service="mysqld" >\#*P'y`d ;; @n /nH?L esac $( kF# if [ ! -z "$service" ] ; then #q$HQ&k /etc/init.d/$service restart 1>/dev/null 2>/dev/null `UaD6Mc<Mz if [ $? = 0 ] ; then ]Q1yNtN mylogger_notice "$service restarted" ;`{H!w[D else |aS.a&vwR mylogger_notice "$service restart failed" 4e7-0}0 fi #gN&lY:CFn fi _J#zY-j } /Cr%{'Pzk o:'MpKm docheckport() *:7rdzn { V2EUW!gn
2 mylogger_info "do check port $1" R) h#Vc( local port last_client count client total_count };zFJ6I8 Dx?,=~W9 if [ -z "$1" ] ; then Bkc
4TO mylogger_notice "docheckport() port not given" &6!)jIWJ return nR~@#P\ fi FD
#8mg PFjL1=7I port=$1 :3Ox~o
M|h3Wt~7 clientlist=`netstat -an --tcp| grep ESTABLISHED | awk "{ if ( index(\\$4,\":$port\") ) print \\$5}" | awk -F ':' '{print $1}'|sort` "&u@d~`-n if [ $? != 0 ] ; then Bsvr?|L\ mylogger_notice "netstat call failed" "(O>=F& return (?c"$|^J fi dZ@63a>>@ #echo $clientlist 2%m BK # reset new_block DyQy^G'%l new_block=0 <%eG:n,# count=0 d7upz]K9g total_count=0 tyFzSrfc last_client="" va@Lz&sAE% for client in $clientlist \R_C&= do 6H$FhJF #echo "client is $client" O^
yG?b if [ -z "$last_client" ] ; then q0vQa count=$((count+1)) u6JM]kR total_count=$((total_count+1)) }Sv:`9= last_client=$client DTL.Bsc-. else kl:Bfs)b if [ "$client" = "$last_client" ] ; then
f]CXu3w(J count=$((count+1)) ;e*!S}C, total_count=$((total_count+1)) Q;rX;p^W else Wne@<+mX mylogger_debug "$last_client $count connections" 26h21Z16q if [ $count -ge $max_active_conn ] ; then b\2
ds, mylogger_notice "client $last_client connection $count >= $max_active_conn"
;i+jJ4 blockclient $last_client $port z2GY:<s fi 1yhDrpm count=1 s$j,9uRr total_count=$((total_count+1)) dy[X3jQB last_client=$client 6'f;-2 fi mC#>33{ fi y:uE3Apm done ;$g?T~v7 # check the last client f/?P514h if [ ! -z "$client" ] ; then sW\!hW1*x count=$((count+1)) dR]m8mdqc1 total_count=$((total_count+1)) y6BAH mylogger_debug "$client $count connections" Ny/MJ#Lq if [ $count -ge $max_active_conn ] ; then )^hbsMhO mylogger_notice "client $client connection $count >= $max_active_conn" J{G?-+` blockclient $client $port d<Tc7vg4|U fi :ShT|n7 fi aN3;`~{9 mylogger_info "total connections on port $port: $total_count" J'r^/ B9S@(/"7 if [ $new_block = 1 ] ; then A=0'Ks restartservice $port (QB2T2x fi )+Pus~w } \~wMfP8 G3v5KmT docheckall() Y_P!B^z3 { ,/unhfs1q # reset wakeup_time ],].zlN wakeup_time=$wakeup_time_max -UT}/:a for port in $portlist ;dhQN}7 do `M6)f?|$. docheckport $port 0{SL&<& if [ $new_block = 1 ] ; then C7AUsYM # set wakeup_time shorter cause we found some abuse client e96k{C`j0 wakeup_time=$wakeup_time_min akQ7K fi [Vt\$ done v &+R^iLE } QmIBaMI# U/BR*Zn]* if [ -z "$firewall" ] && [ -f /etc/sysconfig/ipchains ] ; then T[j,UkgGo firewall="ipchains" 3+bt~J0 fi <9
;!3xG ig &Y if [ -z "$firewall" ] && [ -f /etc/sysconfig/iptables ] ; then !f6
(Zho firewall="iptables" Y
nZiTe@ fi 4X|zmr:A T]p-0?=4vv if [ -z "$firewall" ] ; then pD+k* echo "Error: This machine does not have ipchains or iptables firewall support" L8 @1THY exit 1 S21,VpW\ fi POR\e|hRT] _<2E"PrT mylogger_info "firewall.sh v$myver ValueOf.com starting" ?G&ikxl mylogger_info "Firewall is: $firewall" Z EO WO mylogger_info "Port protected: $portlist" dC4'{n|7 mylogger_info "Max connection per ip: $max_active_conn" >yh2Lri mylogger_info "Min time to check: $wakeup_time_min""s" ^zgo#J5O mylogger_info "Max time to check: $wakeup_time_max""s" 'A[dCc8O mylogger_info "Timeout circle: $rule_timeout""s" G
vlS% mylogger_info "Output is logged to: $log_facility" 76` .Y 5
rUdv}. # if new ip blocked at this check run? @ur+;IK$ new_block=0 aFIw=c(nP # if new ip blocked at this timeout run? #LN`X8Wz' ever_block=0 .w,q0<} # reset wakeup_time 9Lfv^V0 wakeup_time=$wakeup_time_max G9vpt M *k>n<p3dd lasttime=`date +%s` sFTy(A/ RY*U"G0#w while [ 1 ] f'3$9x do rk)`\=No curtime=`date +%s` y$R_.KbO timediff=$((curtime-lasttime)) Mh
7DV #echo "timediff: $timediff" -RK- Fu<e if [ $timediff -ge $rule_timeout ] && [ $ever_block = 1 ] ; then 9k[9P;"F: lasttime=$curtime n@[O|?S ever_block=0 `x%>8/ dotimeout zs#@j v$ fi &XUiKnNW docheckall >~+ELVB& mylogger_info "sleep for $wakeup_time""s" K)k<Rh[< sleep $wakeup_time t9IW/Q done U_c*6CK yyy|Pw4:Z &~U ]~;@ ('p5:d 1. 说明 R0 firewall.sh是一个shell脚本程序,每隔一段时间检查tcp连接的统计信息,如果来自某个ip对某个端口的活动连接超过规定的最大数量, {3vNPQJ 则自动将该IP对该端口的访问屏蔽,并重新启动相应的服务。再每隔一段时间,会重设防火墙到初始状态。 0%I=d 该程序可以同时保护多个端口 ,UdVNA Y% 5eZ=z 2. 安装 jsi!fx2Rm tar zxf firewall-1.0b.tar.gz w_u\sSQ`! cd firewall-1.0b
kX2rp?{ install -m 700 firewall.sh /usr/prima/sbin/firewall.sh YLn?.sV{[0 }U5yQ%N 3. 配置 UU0,!?o4 主要配置项目如下: x{WD;$J # 最小检查周期,缺省为120秒 fPW@{~t wakeup_time_min=120 -_eLf#3 mUF,@>o # 最大检查周期,缺省为300秒 <B8!.|19 wakeup_time_max=600 K:30_l<
@/-\k*T # 重设防火墙状态的时间,缺省为3600秒 fNZ__gO
!% rule_timeout=3600 !ff&W1@ RF0HjgP # 保护的端口列表,缺省为80和25,支持的其他端口包括21(ftp), 110(pop3), 53(named), 3306(mysql) =
6\^% # 一般的网络攻击都是针对80和25,又以80居多 o`N9!M portlist="80 25" 6ar
c.F6~IHu7 # 每个ip可占用的最大活动(Established)连接数 s(q_
o max_active_conn=8 &m:uO^
-D I,@6J(9 # iptables防火墙规则链名称,必须和/etc/sysconfig/iptables中一致 .gOL1`b* # 如果用的是ipchains,可以忽略此项 aM0f/"-_ iptables_chain_name="RH-Lokkit-0-50-INPUT" ~|xA4u5LG u.Tcg^v # 日志输出目标 yFlm[K5YD log_facility="local0"
oc0G| PGV/ h **** 关于检查周期 **** oJ|j#+Ft 程序定义了两个检查周期,如果上次检查中屏蔽了某个IP,则程序会更频繁地检查连接情况,反之则等待更长时间。通过检查周期 eb"5-
0 的动态调整,可以有效调度在遭受攻击和正常状态下程序的运行次数。 ptxbDzOz bTs?!~q **** ipchains vs iptables **** %
0+j?>#X 目前该程序支持ipchains和iptables两种软件防火墙,使用何种是由程序启动时自动检测的。如果/etc/sysconfig/ipchains和 !LN?PKJ /etc/sysconfig/iptables都没有检测到,则报错退出。 g:Xhw$x9 ls:w8&`* **** 日志输出 **** p/@smke 程序的输出信息记录在系统日志中,目标是local0。如果没有特殊配置,可以在/var/log/messages中看到。建议在/etc/syslog.conf p\aaJ 中加入一条: mg.kr: local0.* /var/log/firewall.log G`BU=Fi 然后重新启动syslog iaE^a^* /etc/init.d/syslog restart ktBj|-'> 这样,可以将firewall.sh输出的日志单独记到文件/var/log/firewall.log里。 @Y<bwv x%!s:LVX 4. 运行 c*L\_Vx+ /usr/prima/sbin/firewall.sh & EkNunCls jeH~<t{ 范例输出: (~wqa 3 *** firewall.sh v1.0b ValueOf.com*** g+>(dnX Firewall is: ipchains };jN\x?&q Port protected: 80 25 eMY<uqdw Max connection per ip: 8 xQXXC
|T Min time to check: 120s RA'M8:$ Max time to check: 300s >$7v
;Q Timeout circle: 3600s >A"v ed8 Output is logged to: local0 T)TfB( ?6un4EVL{ 察看/var/log/firewall.log,可以看到: ^!ZC?h!rG Oct 16 14:08:55 server firewall.sh: do check port 80 // 检查80端口 J1I ;Jgql( Oct 16 14:08:55 server firewall.sh: 192.168.0.60 2 connections // 有两个来自192.168.0.60的连接 p#?7w Oct 16 14:08:55 server firewall.sh: total connections on port 80: 2 // 80端口总共2个连接 :f}9($ Oct 16 14:08:55 server firewall.sh: do check port 25 // 检查25端口 +|'c>,?2H Oct 16 14:08:55 server firewall.sh: total connections on port 25: 0 // 25端口没有连接 W~~7C,! Oct 16 14:08:55 server firewall.sh: sleep for 300s // 等待300秒 W=
Mb 6S*exw 5. 停止 B9$jSD 先用ps命令察看firewall.sh进程的进程号,然后用kill命令将其终止,如 }v*G_}^ # ps auxww|grep firewall.sh o9%)D<4M root 27932 0.0 0.5 2312 1060 pts/2 S 12:38 0:00 /bin/sh /usr/prima/sbin/firewall.sh w2Jf^pR root 27967 0.0 0.3 1732 592 pts/2 S 12:39 0:00 grep firewall.sh ~yfNxH~k 第一行即firewall.sh的进程,用kill命令: hjB@o#S # kill 27932 "UG
Y2skf; [1] Terminated /usr/prima/sbin/firewall.sh uK$9Ll{lk 即将其终止
|
常州电信/网通机房,100M共享/10M独享/1000M共享/100M独享/电信+网通双线路服务器托管
Tel:0519-89991155 企业QQ:4006023839 5y6s Inc.
|
[楼 主]
|
Posted: 2008-01-26 02:12 |
| |