ogf@wdZdZdZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z  ddl mZddlmZdd lmZdd lmZdd lmZd d lmZmZmZmZmZmZm Z ee!Z"e jFZ$ejJZ&ejNdZ(dZ)ejNdZ*dddZ+dddZ,e,j[e+Gddee.Z/Gdde.e Z0dddZ1Gdd e0Z2y#e$r ddlmZYwxYw)!z'Cyril Jaquier and Fail2Ban Contributorsz>Copyright (c) 2004 Cyril Jaquier, 2011-2012 Yaroslav HalchenkoGPLN)ABCMeta)MutableMapping) mapTag2Opt)DNSUtils)MyTime)Utils) getLogger_merge_copy_dicts splitwordssubstituteRecursiveTags uni_stringTAG_CREMAX_TAG_REPLACE_COUNTz)inet4inet6z^(\w+)\?(family)=(.*)$c@ttjdS)NTfqdnstrr getHostname8/usr/lib/python3/dist-packages/fail2ban/server/action.pyr?sH00d;<rc@ttjdS)NFrrrrrrr@sH00e<=r)z fq-hostnamez sh-hostname  )brspcjeZdZdZdZdZdZddZddZeZ ddZ d Z d Z d Z d Zd ZdZdZdZy) CallingMapa"A Mapping type which returns the result of callable values. `CallingMap` behaves similar to a standard python dictionary, with the exception that any values which are callable, are called and the result is returned as the value. No error handling is in place, such that any errors raised in the callable will raised as usual. Actual dictionary is stored in property `data`, and can be accessed to obtain original callable values. Attributes ---------- data : dict The dictionary data which can be accessed to obtain items uncalled r)datastorage immutable __org_datacPt|_d|_t|i||_y)NT)dictr'r(r&)selfargskwargss r__init__zCallingMap.__init___s#$,$.D#F#$)rct|_ |j|_||_y#t$r Y||_ywxYwN)r+r'_CallingMap__org_datar&AttributeErrorr()r,r(s rresetzCallingMap.resetds?$,49$. $.s * ==cb|jjd|j|tdS)N()) __class____name___asdictr)r, calculateds r_asreprzCallingMap._asreprls"^^,,dll:s.K LLrNc:tjfij}|s"tfd|jDSt |jD]2\}}t |s j |}|r|||||<4|S#Y;xYw)Nc3^K|]$\}}t|r|jvr||f&ywr1)callable CM_REPR_ITEMS).0nvr,s r z%CallingMap._asdict..us431 A;!t111!u3s*-)r+r&r'itemslistr? __getitem__)r,r;checkerdrBrCs` rr:zCallingMap._asdictrs 499% %!  3 3 33 !'')_  caqk  ! Q QqT   (  s 2 BBcd |j|}|S#t$r|j|}Y|SwxYwr1)r'KeyErrorr&r,keyvalues r getRawItemzCallingMap.getRawItems? << 5 ,  99S>5 ,s //c |j|}t|r@t |dr|j j r||n|}||j|<|S#t$r|j|}YgwxYw)N__code__)r'rKr&r?hasattrrQ co_argcountrLs rrGzCallingMap.__getitem__ss << 5e_!%49S9S5;Y^Y`54<< ,  99S>5sAA98A9c|jrV|jj|_|j|_|jj|_d|_||j|<yNF)r(r'copyr&r2rLs r __setitem__zCallingMap.__setitem__sO ^^,,##%4<YY4?yy~~494>$,,srctd|z)NzKey %r was deleted)rKr,rMs r __unavailablezCallingMap.__unavailables%+,,rc|jrV|jj|_|j|_|jj|_d|_ |j|=|j|=y#t $rYwxYwrU)r(r'rVr&r2rKrYs r __delitem__zCallingMap.__delitem__ss ^^,,##%4<YY4?yy~~494> ||C iin s$ A?? B  B c,t|jSr1)iterr&r,s r__iter__zCallingMap.__iter__s diirc,t|jSr1)lenr&r_s r__len__zCallingMap.__len__s TYYrc`|jt|j|jSr1)r8r r&r'r_s rrVzCallingMap.copys! )$))T\\B CCr)T)F)FN)r9 __module__ __qualname____doc__r@ __slots__r/r4r<__repr__r:rOrGrW_CallingMap__unavailabler\r`rcrVrrrr%r%JsZ <$ M  $ - Drr%cTeZdZdZedZdZdZdZdZ dZ e dZ d Z y ) ActionBaseaAn abstract base class for actions in Fail2Ban. Action Base is a base definition of what methods need to be in place to create a Python based action for Fail2Ban. This class can be inherited from to ease implementation. Required methods: - __init__(jail, name) - start() - stop() - ban(aInfo) - unban(aInfo) Called when action is created, but before the jail/actions is started. This should carry out necessary methods to initialise the action but not "start" the action. Parameters ---------- jail : Jail The jail in which the action belongs to. name : str Name assigned to the action. Notes ----- Any additional arguments specified in `jail.conf` or passed via `fail2ban-client` will be passed as keyword arguments. cFd}|D]}tt||dryy)N)startstopbanrebanunbanFT)r?getattr)clsCrequiredmethods r__subclasshook__zActionBase.__subclasshook__s3(f 71fd+ ,  rcn||_||_td|jjz|_y)Nz fail2ban.%s)_jail_namer r8r9_logSys)r,jailnames rr/zActionBase.__init__s+$*$*=4>>+B+BBC$,rcy)z,Executed when the jail/action is started. Nrr_s rrnzActionBase.startrcy)z,Executed when the jail/action is stopped. Nrr_s rrozActionBase.stoprrcy)Executed when a ban occurs. Parameters ---------- aInfo : dict Dictionary which includes information in relation to the ban. Nrr,aInfos rrpzActionBase.banrc$|j|S)r)rprs rrqzActionBase.rebans %rcyrUrr_s r _prolongablezActionBase._prolongable s rcy)zExecuted when a ban expires. Parameters ---------- aInfo : dict Dictionary which includes information in relation to the ban. Nrrs rrrzActionBase.unbanrrN)r9rerfrg classmethodrxr/rnrorprqpropertyrrrrrrrlrlsN<  D       rrl) metaclass str2secondsignore)timeoutbantimeceZdZdZedZdZfdZedZ dZ e Z dZ e dZe d Zd Zd Zgd fd Ze dZe dZe dZdZd(dZd)dZe dZdZdZdZdZdZd*dZdZ d*dZ!e"jFdZ$edZ%ed+dZ&e"jFd Z$e"jFd!Z'ed*d"Z(e d#Z)d$Z*d,d%Z+d*d&Z,e-d-d'Z.xZ/S). CommandActionaA action which executes OS shell commands. This is the default type of action which Fail2Ban uses. Default sets all commands for actions as empty string, such no command is executed. Parameters ---------- jail : Jail The jail in which the action belongs to. name : str Name assigned to the action. Attributes ---------- actionban actioncheck actionreban actionreload actionrepair actionstart actionstop actionunban timeout )matches ipmatches ipjailmatchescd|_ d|_d|_d|_d|_d|_d|_d|_d|_d|_ d|_ d|_y#d|_wxYw)z8 Clear all lists/dicts parameters (used by reloading) r<rN) _CommandAction__initr actionstart actionban actionreban actionunban actioncheck actionrepair actionflush actionstop actionreloadr_s rclearAllParamszCommandAction.clearAllParams>sl$+4<44>444444?44;4;s AA A ctt| ||d|_d|_i|_i|_|j|jjd|jzy)Nrz Created %s) superrr/r_CommandAction__properties_CommandAction__started_CommandAction__substCacherr|debugr8)r,r}r~r8s rr/zCommandAction.__init__XsY t%dD1$+$$.$,,\DNN23rctSr1)NotImplemented)rtrus rrxzCommandAction.__subclasshook__as rcX|jds|js~t|sstj |}|dk(ry|dk(rt j |}d|_|jj|jjd||||j|<y)N_rrz Set %s = %r) startswithrr?WRAP_CMD_PARAMSgetr rrrclearr|r__dict__)r,r~rNwrps r __setattr__zCommandAction.__setattr__es  dkk(5/   T "3 Xo  }   u %E4<<otU3$--rc|jds=d|_|jj|jj d||j |=y)Nrz Unset %s)rrrrr|rr)r,r~s r __delattr__zCommandAction.__delattr__wsH  4<<lD) mmDrcj jStfdtD_jS)z`A dictionary of the actions properties. This is used to substitute "tags" in the commands. c3K|]8}|jds%tt|s|t|f:yw)rN)rr?rs)rArMr,s rrDz,CommandAction._properties..s? .. hwtS/A&Bs s>A)rr+dirr_s`r _propertieszCommandAction._propertiessI "   $i$   rc|jSr1)rr_s r _substCachezCommandAction._substCaches  rc|j||j|rd|znd|j}|rd|vr|S|j|d|i}|S)Nfamily=r conditionalcache<family) replaceTagrrreplaceDynamicTags)r,tagrcmds r _getOperationzCommandAction._getOperationsa T--$* &     # 3c>#: hv%67# *rcTd|f}t|s|t|s+|jj|ij|S|jj|ij Dcgc]\}}||s|c}}S|d}|r |j|}|||<y |j|}|j |}t|j D]\}}||k(s ||=ycc}}w#t $rix}|j|<YtwxYw#t $rYywxYw)z? Get, set or delete command of operation considering family. __eOpCmdrN)rbr?rrrErKpoprF) r,rrr-rMfrCrfamds r_operationExecutedz CommandAction._operationExecuteds2 C# T 6     b ) - -f 55**..sB7==? MA6!91 MM Q#'   S !D4<   S !D ((6 C$**,'  S v, N '$&&D4  S !'   s73C5C5C;*AD/D;DD D'&D'Nc Ld}d}|s/|jjDcgc] \}}|s | }}}|D] |j|} d} | r| |j|fdvr| } |jrt |jj dd} | sF|jj jd} t|jj d| tj| d<| d<|j| | } |j| |j} || z}|r || |j|| r| nd|s+td |d |jd |j d ||Scc}}w#t$r} d}| }Yd} ~ ed} ~ wwxYw) zExecutes the operation commands (like "actionstart", "actionstop", etc). Replace the tags in the action command with actions properties and executes the resulting command. Tz Script errorc|k7Sr1r)rfamopers rrz1CommandAction._executeOperation..s gr actionInfoNtimerFzError z action /z: )rrErrrzrsactions_getActionInfosetattrr rr executeCmdr ValueError RuntimeErrorr{)r,r operationr afterExecreserrrrCrretrealCmdres ` r_executeOperationzCommandAction._executeOperations ## (,(<(<(> D'!!W D6 D g   S' *C C s$11#7MNNW djj((,=e zz!!006utzz!!<7kkmeFmeHo''U3g ??7DLL 1SCZS)GS)C#$?) 0 Y DJJX[\ ]] *7 E,  C C s" FFDF  F#FF#c|jjd}||Sd}|jD]}tj|sd}n||jd<|S)N__hasCondSectionFT)rrCONDITIONAL_FAM_REmatch)r,rCrBs r_hasCondSectionzCommandAction._hasCondSectionsk -.!] 8 !    aq! A  *+$%& (rc"|jjd}|r|S|jjd}|r"t|ttfs t |}n!|j rtrddgndg}ndg}||jd<|S)N __familiesfamiliesrrr)rr isinstancerFsetrr allowed_ipv6r,rCs r _familieszCommandAction._familiess <(!q :&!z!d3Z(!}1 )^'1 t1#$$< (rcz|jjd}||S|j}||jd<|S)z1Checks the action depends on family (conditional)actionstart_on_demand)rrrrs r_startOnDemandzCommandAction._startOnDemandsF 23!] 8 !./$*+ (rc"|jS)Executes the "actionstart" command. Replace the tags in the action command with actions properties and executes the resulting command. )_startr_s rrnzCommandAction.start s rcjr|sy|sjj|ry||gn j}fd}j dd||}|S)rTcP|r#jd|ddj|<yy)N r)rrrrr,s r_startedz&CommandAction._start.._starteds+ NFD9DNN6 r startingrr)rrrrr)r,r forceStartrrs` rrzCommandAction._startsc    $..,,V4 )F8t~~&  6U]^# *rc4|jdd}|jr.|jj|s|j|d|j ||st d|z|jj|ddz|j|<y) a)Executes the given command ("actionban" or "actionreban"). Replaces the tags in the action command with actions properties and ban information, and executes the resulting command. Parameters ---------- aInfo : dict Dictionary which includes information in relation to the ban. rrTrzError banning %(ip)srN)rrrr _processCmdr)r,rrrs rrpzCommandAction.ban%s 99Xr "&  ..  V $KK4K(  #u % ,u4 55>>--fa81<$..rct|dxr2|jxr$t|jj S)N actionprolong)rRrrisspacer_s rrzCommandAction._prolongable;s= $ ( -T-?-? - t!! " * * ,,.rcD|jd|std|zy)aExecutes the "actionprolong" command. Replaces the tags in the action command with actions properties and ban information, and executes the resulting command. Parameters ---------- aInfo : dict Dictionary which includes information in relation to the ban. zzError prolonging %(ip)sN)rrrs rprolongzCommandAction.prolong@s+   +U 3 /%7 88 4rc|jdd}|jj|ddzr!|jd|std|zyy)aExecutes the "actionunban" command. Replaces the tags in the action command with actions properties and ban information, and executes the resulting command. Parameters ---------- aInfo : dict Dictionary which includes information in relation to the ban. rrrr zError unbanning %(ip)sN)rrrr)r,rrs rrrzCommandAction.unbanOsX 99Xr "& ^^"Q&   ?E 2 /%7 88 3'rcJ|j||jrdSdS)aDExecutes the "actionreban" command if available, otherwise simply repeat "actionban". Replaces the tags in the action command with actions properties and ban information, and executes the resulting command. Parameters ---------- aInfo : dict Dictionary which includes information in relation to the ban. z )rprrs rrqzCommandAction.reban`s% %D,<,< PP- PPrcjjDcgc]\}}|dzdk(s|}}}|syfd}jdd||Scc}}w)aExecutes the "actionflush" command. Command executed in order to flush all bans at once (e. g. by stop/shutdown the system), instead of unbanning of each single ticket. Replaces the tags in the action command with actions properties and executes the resulting command. rTcr|r4jj|rj|xxdzcc<yyy)N)rrrs r _afterFlushz(CommandAction.flush.._afterFlush}s2 dnn  (NN6b )crz flushingr)rrEr)r,rrCrrs` rflushzCommandAction.flushos` >>//1 @%1QQUaZA @& @ "   FVa  bb As AAc"|jS)Executes the "actionstop" command. Replaces the tags in the action command with actions properties and executes the resulting command. )_stopr_s rrozCommandAction.stops rc|:jjDcgc] \}}|s | }}}|syi_n j|xxdzcc<|g}fd}jdd||Scc}}w#t$rYywxYw)rTrc2|rjd|dyy)Nr)rrs r_stoppedz%CommandAction._stop.._stoppeds OVT: rrstoppingr)rrErKr)r,rrrCrs` rrzCommandAction._stops ^ NN002 85AaaQ 86 8 4>NN6aXF;    6U]  ^^ 9  s A3A3A99 BBc &|jddS)zExecutes the "actionreload" command. Parameters ---------- kwargs : dict Currently unused, because CommandAction do not support initOpts Replaces the tags in the action command with actions properties and executes the resulting command. z reloading)r)r,r.s rreloadzCommandAction.reloads    0+ >>rcd}|jrht|jjD]B\}}|s |j ||rd|j|<|j d|d|dz}D|S)zFExecutes the invariant check with repair if expected (conditional). TrrNF)rrFrrE_invariantCheckr)r, beforeRepairrrstarteds rconsistencyCheckzCommandAction.consistencyChecksz #  !5!5!78t++FLAT^^F _fd;E\S  *rz[\\#&;`|*?~<>^()\[\]{}$'"\n\r]cTdddfd}|jj||}|S)a5Escape characters which may be used for command injection. Parameters ---------- value : str A string of which characters will be escaped. Returns ------- str `value` with certain characters escaped. Notes ----- The following characters are escaped:: \#&;`|*?~<>^()[]{}$'" rBr)r  cN|j}dj||zS)N\)groupr)mc_map2cs r substCharz*CommandAction.escapeTag..substChars$wwy1 Aq! !!r) ESCAPE_CREsub)rtrNr+r*s @r escapeTagzCommandAction.escapeTags1*S !&" ..  Y .% ,rc d|vr|S| |f} ||St|t}| |s|| |<| S#t$rYwxYw#t$rYwxYw) zReplaces tags in `query` with property values. Parameters ---------- query : str String with tags. aInfo : dict Tags(keys) and associated values for substitution in query. Returns ------- str `query` string with tags replaced. rNz subst-tags)raddreplc|jd}d}rj|dzz}|3j|}| j||jSt|}|jvrj |}|S)Nr?)r'rr _escapedTagsr.)r(rrNADD_REPL_TAGS_CMrtrsubInfos rsubstValz*CommandAction.replaceTag..substVals 3 5 KKc K/ 0E m KK E }  aggi 00 e 5 S   MM% E \^\(\)\[\]{}$'"\n\r]z\Wc(tsfdttfd}tj||}d|vr1j dsifd}t j ||}rtj|}|S)a%Replaces dynamical tags in `query` with property values. **Important** ------------- Because this tags are dynamic resp. foreign (user) input: - values should be escaped (using "escape" as shell variable) - no recursive substitution (no interpolation for >) - don't use cache Parameters ---------- query : str String with tags. aInfo : dict Tags(keys) and associated values for substitution in query. Returns ------- str shell script as string or array with tags replaced (direct or as variables). cjj|r)djjd|z}||<d|z}|S)Nzf2bV_%sr$)r,search ESCAPE_VN_CREr-)rrNrtvarsDicts r escapeValz3CommandAction.replaceDynamicTags..escapeValSsK ~~U# s((,,S#6 6SXc] WU Lrc|jd} |}t|}||S#t$r#j||jcYSwxYw)Nr)r'rKrr)r(rrNr4rrDs rr6z2CommandAction.replaceDynamicTags..substValasa 30 #JE e 5 C  0   QWWY //0s-)AArzF-*ct|jd} t|}d|z|S#t$rYywxYw)NrrF_)rr'rrK)r(rrNrDtickDatas rsubstTagz2CommandAction.replaceDynamicTags..substTagssO QWWQZ C  &U T#Xu %%  s7 AA) r+r%r8rr-r FCUSTAG_CREr buildShellCmd) rtrrrDr6rIr4rHrCs ` `` @@@rrz CommandAction.replaceDynamicTags8s0V(   .   KK' *' G^ii8 rH&__Xw /7  ( 37 .rct|ddS)N _banEpochr)rsr_s rbanEpochzCommandAction.banEpochs {A &&rc|jD|jjjdzx|_|jj_y|jdz|_y)zIncrements ban epoch of jail and this action, so already banned tickets would cause a re-ban for all tickets with previous epoch.Nr)rzrrNrMr_s rinvalidateBanEpochz CommandAction.invalidateBanEpochsM ZZ26**2D2D2M2MPQ2QQ4>DJJ&&/MMA%4>rc|s|||jvry|jd|}|r|j||jry|r|sy|jj d|j |jd|}|rW|j||js+d|j|<|jjdyd|j|<n4 |j||j||xs |j |jj|r8|j||js|jjdyy#t$rYwxYw) z0Executes a substituted `actioncheck` command. rz zrzUnable to restore environmentr) rrrrr|errorrPcriticalrrrrr)r,rrrcheckCmd repairCmds rrzCommandAction._invariantChecksL *vT^^/K    8( T__Xt||< ,. ,,AC  !16:) //)T\\ 2DNN6LL9: 4>>& JJv;;v*"GD4G4G0G;H ^^$,,(O<<89   s&E-- E98E9cdk(rjjdy |d}d} |r/jr#fd}j ||dk7}|d k7ry j j|rd |zndj }|j||}n}j|j}|d z }|s|d kDr|S#ttf$rd}YwxYw) aExecutes a command with preliminary checks and substitutions. Before executing any commands, executes the "check" command first in order to check if pre-requirements are met. If this check fails, it tries to restore a sane environment before executing the real command. Parameters ---------- cmd : str The command to execute. aInfo : dictionary Dynamic properties. Returns ------- bool True if the command succeeded. r Nothing to doTrrc~dk(r7jjdsjjdyy)Nr actionrepair_on_unbanz,Invariant check failed. Unban is impossible.FT)rrr|rS)rr,sr _beforeRepairz0CommandAction._processCmd.._beforeRepairs8 t'7'7';';>BrU)r r1)rNN)NNT)r)0r9rerfrgrr3rr/rrxrrWrrrrrrrrrrrnrrprrrrrqrrorrr!recompiler,r.rrBrrNrPrr staticmethodr __classcell__)r8s@rrr s6=>44         457$% N                 (>, . . 99" Qc&_. ?  bjj>? 8WWrbjjABE" GGR ' '&& P=~QQrr)3 __author__ __copyright__ __license__rdosrhsignal subprocesstempfile threadingrabcrcollections.abcr ImportError collections failregexripdnsrmytimer utilsr helpersr r rrrrrr9rbLockrg IPv6IsAllowedrrirJ COND_FAMILIESr DYN_REPL_TAGSr8updateobjectr%rlrrrrrrs2(7 P    (+"QQQ 8  INN  %% bjj./ " RZZ 9: ==    ]#lDlD^_7_F   r QJr Q{('(sC00 C>=C>