ogf=adZdZdZddlZddlZddlZddlZ ddlmZddl m Z ddl m Z mZdd lmZdd lmZdd lmZmZmZdd lmZdd lmZddlmZddlmZeeZ GddeeZ!y#e $r ddl mZY^wxYw)z Cyril Jaquierz Copyright (c) 2004 Cyril JaquierGPLN)Mapping) OrderedDict) BanManager BanTicket)IPAddr) JailThread) ActionBase CommandAction CallingMap)MyTime) Observers)Utils) getLoggerceZdZdZdZedZd dZd!dZdZ dZ d Z d Z d Z d Zd ZdZdZd"dZdZd#dZd$dZdZGddeZdZd%dZd$dZd&dZdZd$dZd'dZd&dZ d(dZ!y))ActionsaHandles jail actions. This class handles the actions of the jail. Creation, deletion or to actions must be done through this class. This class is based on the Mapping type, and the `add` method must be used to add new actions. This class also starts and stops the actions, and fetches bans from the jail executing these bans via the actions. Parameters ---------- jail: Jail The jail of which the actions belongs to. Attributes ---------- daemon ident name status active : bool Control the state of the thread. idle : bool Control the idle state of the thread. sleeptime : int The time the thread sleeps for in the loop. ctj|d|jz||_t |_t |_d|_d|_ d|_ |jdz|_ y)Nzf2b/a.)namer r) r __init__r_jailr_actionsr banManagerbanEpoch _Actions__lastConsistencyCheckTM banPrecedence unbanMaxCount)selfjails 9/usr/lib/python3/dist-packages/fail2ban/server/actions.pyrzActions.__init__Ns^ d$))!34$*-$-L$/$-"#$$))A-$ctj|}t|dstd|zt |j t s%t|d|j jd|S)NActionz&%s module does not have 'Action' classz module z$ does not implement required methods)rload_python_modulehasattr RuntimeError issubclassr%r __name__) pythonModulemods r"_load_python_modulezActions._load_python_module\sg   .# h  ,|; == cjj* - 3::&&( )) *r#Nc|||jvrW|std|z|j|}t|dr,t|dr|j||j|<y|t |j |}n/|j|}|j|j |fi|}||j|<y)aAdds a new action. Add a new action if not already present, defaulting to standard `CommandAction`, or specified Python module. Parameters ---------- name : str The name of the action. pythonModule : str, optional Path to Python file which must contain `Action` class. Default None, which means `CommandAction` is used. initOpts : dict, optional Options for Python Action, used as keyword arguments for initialisation. Default None. Raises ------ ValueError If action name already exists. RuntimeError If external Python module does not have `Action` class or does not implement necessary methods as per `ActionBase` abstract class. zAction %s already existsreloadclearAllParamsN) r ValueErrorr'r0_reload_actionsr rr-r%)r rr+initOptsr/actioncustomActionModules r"addz Actions.addis6 T]]  /$6 77 MM$ 6 fhv'( "*T$  $**d +600> %  % %djj$ C( C6$--r#c|rt_ytdrjjD]7\}}|jvsj|j di|r|ni9t fdjjD}t|r&jd|dj|tdyy) z@ Begin or end of reloading resp. refreshing of all parameters r2c3HK|]\}}|jvr||fywN)r2).0rr4r s r" z!Actions.reload..s.*\T6 D((( .*s"FT)dbactionsstopr=N) dictr2r'itemsrr/rlen_Actions__flushBan stopActionsdelattr)r beginrr3delactss` r"r/zActions.reloads &4 d%&..446Ch   dmmD  BHbBC*T]]=P=P=R**G 7| __wT_: g& D#$'r#cX |j|S#t$rtd|zwxYwNzInvalid Action name: %srKeyErrorr rs r" __getitem__zActions.__getitem__s64 --  4 +d2 334s)cV |j|=y#t$rtd|zwxYwrJrKrMs r" __delitem__zActions.__delitem__s34 }}T 4 +d2 334s (c,t|jSr9)iterrr s r"__iter__zActions.__iter__s dmm r#c,t|jSr9)rCrrSs r"__len__zActions.__len__s T]] r#cyNFr@)r others r"__eq__zActions.__eq__s r#ct|Sr9)idrSs r"__hash__zActions.__hash__s D/r#ctj|}|jj|tj d|zy)Nz banTime: %s)r str2secondsr setBanTimelogSysinfo)r values r"r`zActions.setBanTimes5   U #%//U#++o%&r#c6|jjSr9)r getBanTimerSs r"rezActions.getBanTimes  # # %%r#c|jj}|s|St|dk(r |d|vrdSdS|Dcgc] }||vrdnd c}Scc}wNrr)r getBanListrC)r idslstips r" getBannedzActions.getBanneds[ ""$# :X]1v}!#!#*- .BrSy!a  .. .sAc<|jjd|S)zkReturns the list of banned IP addresses. Returns ------- list The list of banned IP addresses. T)orderedwithTime)rrh)r ros r"rhzActions.getBanLists  # #D8 # DDr#ctjt|tr fd|D}n t |f}|j |S)zBan an IP or list of IPs.c36K|]}t|ywr9)r)r:rkunixTimes r"r;z&Actions.addBannedIP..s 3"iH% 3s)rtime isinstancelistr_Actions__checkBan)r rkticketsrrs @r" addBannedIPzActions.addBannedIPsB [[](D 3 37H% '7  !!r#cD||j|St|ttfr4g}d}|D]} ||j |||z }|rt d|z|S|rF|jj0|jjj|j||jj|}||j|yt|tsct|}|jsLtt|j |jj#} | r|j | ||Sd|z} t$j't(j*| |ryt | #t $r|s|j |YnwxYw)aORemoves banned IP calling actions' unban method Remove a banned IP now, rather than waiting for it to expire, even if set to never expire. Parameters ---------- ip : list, str, IPAddr or None The IP address (or multiple IPs as list) to unban or all IPs if None Raises ------ ValueError If `ip` is not banned rznot banned: %rz%s is not bannedr)rDrtrutupleremoveBannedIPr1appendrdatabasedelBanr getTicketByID_Actions__unBanr isSinglefiltercontainsrhralogloggingMSG) r rkr<ifexistsmissedcntiticketipaipsmsgs r"r{zActions.removeBannedIPsx"Z //" T5M" 6 3 qD  2x 00S  %. // :DJJ   +::djj"- ?? ( ( ,& <<  R *C << s||T__%?%?%AB CS  b( 33 b 3 ::gkk3 C9   mmAsE??FFc | |j}tt|jD]N\}} |j |j|=t jd|jj|Py#t $r[}t jd|jj||t jtjkYd}~d}~wwxYw)z>Stops the actions in reverse sequence (optionally filtered) Nz(Failed to stop jail '%s' action '%s': %sexc_infoz%s: action %s terminated)rreversedrurBr> ExceptionraerrorrrgetEffectiveLevelrDEBUGdebug)r r=rr4es r"rEzActions.stopActions/s _ ]]7tGMMO45CldF9 KKM  }}T <<*DJJOOTBC 9 LL; ZZ__dA&&('--7999sB C' AC""C'c d}jjD]\}} |jjr jrPtjdtjfddj tjdjd}t#j j$j&t)j*z }tj-d d |j tjfd |rj/}||z }|r|j0k\rjrs|d z}tj-d d |r|j2kr|n j2|j2j5|r|j2kr|n j2d}jrj7dj9y#t$r\}tj dj j||tjtjkYd}~7d}~wwxYw#t$rZ}tj dj j|tjtjkYd}~d}~wwxYw)zMain loop for Threading. This function is the main loop of the thread. It checks the jail queue and executes commands when an IP address is banned. Returns ------- bool True when the thread exits nicely. rz)Failed to start jail '%s' action '%s': %srNzActions: enter idle modec<j xs j Sr9)activeidlerSsr"zActions.run..Vs O<499}r#cyrXr@r@r#r"rzActions.run..Wsr#zActions: leave idle modez1Actions: wait for pending tickets %s (default %s)cNj xsjjSr9)rrhasFailTicketsrSsr"rzActions.run..^s$++oJ1J1Jr#rz+Actions: check-unban %s, bancnt %s, max: %sz*[%s] unhandled error in actions thread: %sT)r>)rrBstartrrarrrrrrrrrrwait_for sleeptimeminr_nextUnbanTimerrsrrvrr_Actions__checkUnBanrDrE)r rrr4rbancntwts` r"runz Actions.run?sG #mm))+9ldF9 LLN9 9 yy \\,- ^^<T^^% \\,- F T^^T__;;fkkmK LB JJqEr4>>Z ~~JBOooVF]S SD...  kf jjAVX^aeasasXs6y}zLzLNTVZVhVhi &Vd6H6H-HdN`N`a S- 8//t/ E 9 LL< ZZ__dA&&('--79996 9 LL= ZZ__a&&('--7999s9G5AI!D#I5 I>AII K&AJ;;KceZdZdZidddddddd d d d d dddddddddddd0ddddddd d!d"d#d$d%d&d'd(d)Zej d*zZdd+efd,Zd-Zd.Z d1d/Z y)2Actions.ActionInfo)fid raw-ticketrkc6|jjSr9)_ActionInfo__ticketgetIPrSs r"rzActions.ActionInfo.w,,.r#familyc |djSNrk) familyStrrSs r"rzActions.ActionInfo.xsDJ00r#zip-revc*|djdS)Nrk)getPTRrSs r"rzActions.ActionInfo.ys4:,,R0r#zip-hostc(|djSr)getHostrSs r"rzActions.ActionInfo.zs4:--/r#rc6|jjSr9)rgetIDrSs r"rzActions.ActionInfo.{rr#failuresc6|jjSr9)r getAttemptrSs r"rzActions.ActionInfo.|sDMM446r#rsc6|jjSr9)rgetTimerSs r"rzActions.ActionInfo.}s$--//1r#bantimec"|jSr9) _getBanTimerSs r"rzActions.ActionInfo.~sD,,.r#bancountc6|jjSr9)r getBanCountrSs r"rzActions.ActionInfo.sT]]668r#matchescTdj|jjSN )joinr getMatchesrSs r"rzActions.ActionInfo.s499T]]%=%=%?@r#restoredc6|jjrdSdSrg)rrrSs r"rzActions.ActionInfo.s$--"8"8Qar#zF-*Nc8|jj|Sr9)rgetData)r tags r"rzActions.ActionInfo.s4==#8#8#=r# ipmatchesc^dj|jdjS)NrTr_mi4iprrSs r"rzActions.ActionInfo.s!tyyT):)E)E)GHr# ipjailmatchesc\dj|jjSrrrSs r"rzActions.ActionInfo.s4;;=+C+C+E!Fr# ipfailuresc@|jdjSNTrrrSs r"rzActions.ActionInfo.s D 1 < < >r#ipjailfailuresc>|jjSr9rrSs r"rzActions.ActionInfo.s$++-":":"<r#rc,t|jSr9)reprrrSs r"rzActions.ActionInfo.sT]] 3r#c^|jjjjSr9)_ActionInfo__jailr=rsizerSs r"rzActions.ActionInfo.sT[[%8%8%C%C%H%H%Jr#c^|jjjjSr9)rr=r getBanTotalrSs r"rzActions.ActionInfo.sT[[%8%8%C%C%O%O%Qr#c^|jjjjSr9)rr failManagerrrSs r"rzActions.ActionInfo.sT[[%7%7%C%C%H%H%Jr#c^|jjjjSr9)rrr getFailTotalrSs r"rzActions.ActionInfo.sT[[%7%7%C%C%P%P%Rr#)z jail.bannedzjail.banned_totalz jail.foundzjail.found_total)__ticket__jail__mi4ipTcZ||_||_t|_||_||_yr9)rrrAstorage immutabledata)r rr!rrs r"rzActions.ActionInfo.__init__s'4=4;&4<4>49r#c|j|j|j|j|jj Sr9) __class__rrrrcopyrSs r"rzActions.ActionInfo.copys. .. T^^TYY^^EU VVr#c|jj}|$|jjj}t |Sr9)rrerr=int)r btimes r"rzActions.ActionInfo._getBanTimes: == # # %5 mT[[00;;=U e*r#c Ht|dsi|_|j}|rdnd}||vr||||S|jS |j}|d}d||<|js |jS|r |jj |||<n |jj ||||<||||S|jS#t $rQ}tjd|j|tjtjk Yd}~kd}~wwxYw) aGets bans merged once, a helper for lambda(s), prevents stop of executing action by any exception inside. This function never returns None for ainfo lambdas - always a ticket (merged or single one) and prevents any errors through merging (to guarantee ban actions will be executed). [TODO] move merging to observer - here we could wait for merge and read already merged info from a database Parameters ---------- overalljails : bool switch to get a merged bans : False - (default) bans merged for current jail only True - bans merged for all jails of current ip address Returns ------- BanTicket merged or self ticket only rallr!Nrk)rk)rkr!z+Failed to get %s bans merged, jail '%s': %sr) r'_ActionInfo__mi4iprrr} getBansMergedrrarrrrr)r overalljailsmiidxr!rkrs r"rzActions.ActionInfo._mi4ips& $ "DL 2F3 Rig)2c7% &<' *3+ .KQJR5 ':""%FF)"&$WW (.'s3)/&$ ??W-- - f~)/s*-r?z"Banned %s / %s, %s ticket(s) in %r)/_Actions__getFailTicketsrrwraprerrr addBanTicketrMainrr6rranoticerrrBgetattrrresetbanrrrrrbannedrgetrbrNOTICEWARNINGrrrsrvaluesr'rrA_Actions__reBanrrr)r rwr rebanactsrrrkrrrr4rdiftmllrs @r" __checkBanzActions.__checkBans| #   " "4#5#5 67)>"f ^^F #7   T__779 :5 2   w '5 6 oo""76":1HC~~!'*:*:^^ GTZZ? MM/4::??w?O?ORU_bde ++- ; f ;   gflEB __ekkm jj ;GN }} W zz)Q [[2DJJOORH jj7+G~~ ^^  1 1U #QY'--"RZ'.. // ZZ,djjoorBDMM)eai 6;;=4+H+H1+LL'-{{}t$]]))+#6 6- .  "# 4==( D)/*.--*=*=*?)/%/  T\\'9\ 55cDLL !!S}>"B  <<4cOO!4??#7#7#94::??L *a ; ll zzeQ((*GMM9 ;;;sP*-P Q>!AQ99Q>c |xs |j}|j}|j|}|rYtj d|j j |t|dk(rdt|jdznd|jD]_\}} tjd|j j |||js|j|j|ad |_|j*r|j*|_y#t$r]}tj!d|j j |||tj#t$j&kYd }~yd }~wwxYw) zRepeat bans for the ticket. Executes the actions in order to reban the host given in the ticket. Parameters ---------- ticket : Ticket Ticket to reban z[%s] Reban %s%srz , action %rrrz[%s] action %r: reban %sz;Failed to execute reban jail '%s' action '%s' info '%r': %srNT)rrrrarrrrCrukeysrBrrrrebanrrrrrr r) r rr=rrkrrr4rs r"__reBanzActions.__reBan4s;  $t}}' ||~"   f %% =="DJJOORehipequvev-$w||~J^_`Ja:a|~Ammo  ldF   LL+TZZ__dBG ??EKKM LL  &- ]]]]6?    LL ZZ__dE1&&('--7 9  s$AD$$ F -AFF c $|jj|syd}|jjD]m\}} |jrt |ddr!|j s.||j|}|js|j|j|oy#t$r\}tjd|jj|||tj!t"j$kYd}~d}~wwxYw)NrFrr)r _inBanListrrBrr _prolongablerrrprolongrrarrrrrr)r rrrr4rs r" _prolongBanzActions._prolongBanVs  # #F +V %mm))+9ldF9 76<?     }   (U ??EKKM NN59 9 LL ZZ__dE1&&('--7 999s&B* B*'AB** D3AD  Dc4|jjtj|}|D]}|j |t |}|rDt jd||jj|jj|S)zKCheck for IP address to unban. Unban IP addresses which are outdated. zUnbanned %s, %s ticket(s) in %r) r unBanListrrsrrCrarrrr)r maxCountrjrrs r" __checkUnBanzActions.__checkUnBanmsw !!&++-:#f<< C# <<1   2 *r#c  d}|0tjd|jj}nd}t |j}d}i}||n |j j D]\} t drXt tr jrsr" _beforeRepairz)Actions.__flushBan.._beforeRepairs% gf&=tD ||BC r#z Unban tickets each individualyz Flush jail in database)r=rrz! Unbanned %s, %s ticket(s) in %r)rarr flushBanListrRrrBr'rtr actionflushrrrr8rrrrrrbrr}r~rr) r r<r=r>rrjr unbactionsrrr;rr4s ` @r" __flushBanzActions.__flushBan{s # _ <<"#  % % '3 3 doo 3 #*")"5w4==OOQldFvwFM)JfN`N` ]]14::??DI  <<23:d+, 'DJJ   + <<*+::djj) f<<S<1!83  ,,2 1 *9   LLD ZZ__dA&&('--79 KK9:v)*  ]+ + s7A#F;; IB IIc v| |j}n|}|j}|j|}|r+tj d|j j ||jD]_\}} tjd|j j |||js|j|j|ay#t$r\} tjd|j j ||| tjtj kYd} ~ d} ~ wwxYw)zUnbans host corresponding to the ticket. Executes the actions in order to unban the host given in the ticket. Parameters ---------- ticket : FailTicket Ticket of failures of which to unban Nz [%s] Unban %sz[%s] action %r: unban %sz;Failed to execute unban jail '%s' action '%s' info '%r': %sr)rrrrarrrrBrrrunbanrrrrr) r rr=rr>rkrrr4rs r"__unBanzActions.__unBans _ :: ||~"   f %% ==$**//26 &&( 9ldF 9 LL+TZZ__dBG ??EKKM LL 9 9 LL ZZ__dE1&&('--7 999s7AC D8AD33D8c$gd}|||vrtjd|d||dk7r&|jj}t |}n|jj }d|fd|jj fg}|dk7r|dfgz }|dk(rs|jj}|d |jj|fd |jj|fd |jj|fgz }|S) zEStatus of current and total ban counts and current banned IP list. )shortbasiccymruz(Unsupported extended jail status flavor z . Supported: rDzCurrently bannedz Total bannedzBanned IP listrFzBanned ASN listzBanned Country listzBanned RIR list) rawarningrrhrCrrgetBanListExtendedCymruInfogeBanListExtendedASNgeBanListExtendedCountrygeBanListExtendedRIR)r flavorsupported_flavorsr rret cymru_infos r"statuszActions.statuss2 ^v%66 >>QWYjkl w OO & & (6 V3    3 c "t2245 7# w f % &&3 w;;=:==jIJT__EEjQR==jIJLL3 *r#)NNF)Tr)NTFr9)dr)FNF)rE)"r*rr__doc__r staticmethodr-r6r/rNrPrTrVrZr]r`rerlrhrxr{rErr rrrrvr%r2rrDrrPr@r#r"rr2s6 .    ,\%*4 4 '&/E "7 t C 1fZ<*Z r#r)" __author__ __copyright__ __license__rossysrscollections.abcr ImportError collectionsr banmanagerrripdnsr jailthreadr r4r r r mytimerobserverrutilsrhelpersrr*rarr@r#r"rcsz. 2   !$$-"99 8 u  j'u  #! !sA// A=<A=