a =*f@w@stdZdZdZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z zddl mZWneyddlmZYn0ddlmZdd lmZdd lmZdd lmZd d lmZmZmZmZmZmZm Z ee!Z"e #Z$ej%Z&e'dZ(dZ)e'dZ*dddddZ+dddZ,e,-e+Gdddee.Z/Gddde.e dZ0dddZ1Gd d!d!e0Z2dS)"z'Cyril Jaquier and Fail2Ban Contributorsz>Copyright (c) 2004 Cyril Jaquier, 2011-2012 Yaroslav HalchenkoZGPLN)ABCMeta)MutableMapping) mapTag2Opt)DNSUtils)MyTime)Utils) getLogger_merge_copy_dicts splitwordssubstituteRecursiveTags uni_stringTAG_CREMAX_TAG_REPLACE_COUNTz)inet4inet6z^(\w+)\?(family)=(.*)$cCsttjddS)NTZfqdnstrrZ getHostnamerr:/usr/lib/python3.9/site-packages/fail2ban/server/action.py?rcCsttjddS)NFrrrrrrr@r)z fq-hostnamez sh-hostname  )brspc@seZdZdZdZdZddZdddZd d d ZeZ d!d dZ ddZ ddZ ddZ ddZddZddZddZddZd S)" 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 immutableZ __org_datacOs"t|_d|_t|i||_dS)NT)dictr r!r)selfargskwargsrrr__init___szCallingMap.__init__TcCs2t|_z |j|_Wnty&Yn0||_dSN)r"r _CallingMap__org_datarAttributeErrorr!)r#r!rrrresetds   zCallingMap.resetFcCsd|jj||tfS)Nz%s(%r)) __class____name___asdictr)r# calculatedrrr_asreprlszCallingMap._asreprNcstjfij}|s2tfdd|DSt|D]@\}}t|r>z"|}|rf|||||<Wq>Yq>0q>|S)Nc3s,|]$\}}t|r|jvr||fVqdSr')callable CM_REPR_ITEMS).0nvr#rr us z%CallingMap._asdict..)r"rr itemslistr0 __getitem__)r#r.Zcheckerdr3r4rr5rr-rs   zCallingMap._asdictcCs0z|j|}Wnty*|j|}Yn0|Sr')r KeyErrorrr#keyvaluerrr getRawItems  zCallingMap.getRawItemcCsbz|j|}Wnty*|j|}Yn0t|r^t|drN|jjrN||n|}||j|<|S)N__code__)r r;rr0hasattrr@ co_argcountr<rrrr9s   zCallingMap.__getitem__cCs:|jr,|j|_|j|_|j|_d|_||j|<dSNF)r!r copyrr(r<rrr __setitem__s   zCallingMap.__setitem__cCstd|dS)NzKey %r was deleted)r;r#r=rrrZ __unavailableszCallingMap.__unavailablecCsX|jr,|j|_|j|_|j|_d|_z |j|=WntyJYn0|j|=dSrC)r!r rDrr(r;rFrrr __delitem__s    zCallingMap.__delitem__cCs t|jSr')iterrr5rrr__iter__szCallingMap.__iter__cCs t|jSr')lenrr5rrr__len__szCallingMap.__len__cCs|t|j|jSr')r+r rr r5rrrrDszCallingMap.copy)T)F)FN)r, __module__ __qualname____doc__r1 __slots__r&r*r/__repr__r-r?r9rEZ_CallingMap__unavailablerGrIrKrDrrrrrJs       rc@sXeZdZdZeddZddZddZdd Zd d Z d d Z e ddZ ddZ dS) 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. cCs(d}|D]}tt||dsdSqdS)N)startstopbanrebanunbanFT)r0getattr)clsCrequiredmethodrrr__subclasshook__s zActionBase.__subclasshook__cCs"||_||_td|jj|_dS)Nz fail2ban.%s)_jail_namer r+r,_logSysr#Zjailnamerrrr&szActionBase.__init__cCsdS)z,Executed when the jail/action is started. Nrr5rrrrRszActionBase.startcCsdS)z,Executed when the jail/action is stopped. Nrr5rrrrSszActionBase.stopcCsdS)Executed when a ban occurs. Parameters ---------- aInfo : dict Dictionary which includes information in relation to the ban. Nrr#aInforrrrTs zActionBase.bancCs ||S)rb)rTrcrrrrUs zActionBase.rebancCsdSrCrr5rrr _prolongable szActionBase._prolongablecCsdS)zExecuted when a ban expires. Parameters ---------- aInfo : dict Dictionary which includes information in relation to the ban. NrrcrrrrVs zActionBase.unbanN)r,rLrMrN classmethodr\r&rRrSrTrUpropertyrerVrrrrrQs    rQ) metaclass str2secondsignore)timeoutZbantimecseZdZdZedZddZfddZeddZ d d Z e Z d d Z e d dZe ddZddZddZgdfddZe ddZe ddZe ddZddZdNd!d"ZdOd$d%Ze d&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1ZdPd2d3Zd4d5Z dQd6d7Z!e"#d8Z$ed9d:Z%edRdZ$e"#d?Z'edSd@dAZ(e dBdCZ)dDdEZ*dTdGdHZ+dUdIdJZ,e-dVdLdMZ.Z/S)W 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 )matchesZ ipmatchesZ ipjailmatchescCsZd|_zFd|_d|_d|_d|_d|_d|_d|_d|_d|_ d|_ Wd|_nd|_0dS)z8 Clear all lists/dicts parameters (used by reloading) r<rN) _CommandAction__initrkZ actionstartZ actionban actionrebanZ actionunban actioncheckZ actionrepairZ actionflushZ actionstopZ actionreloadr5rrrclearAllParams>szCommandAction.clearAllParamscsHtt|||d|_d|_i|_i|_||j d|j dS)Nrz Created %s) superrlr&rp_CommandAction__properties_CommandAction__started_CommandAction__substCachersr_debugr+r`r+rrr&XszCommandAction.__init__cCstSr')NotImplemented)rXrYrrrr\aszCommandAction.__subclasshook__cCsn|ds`|js`t|s`t|}|dkr.dS|dkr@t|}d|_|j |j d||||j |<dS)N_rjriz Set %s = %r) startswithrpr0WRAP_CMD_PARAMSgetrrirurwclearr_rx__dict__)r#rar>Zwrprrr __setattr__es   zCommandAction.__setattr__cCs4|ds(d|_|j|jd||j|=dS)Nr{z Unset %s)r|rurwrr_rxr)r#rarrr __delattr__ws   zCommandAction.__delattr__cs2jdurjStfddtD_jS)z`A dictionary of the actions properties. This is used to substitute "tags" in the commands. Nc3s4|],}|dstt|s|t|fVqdS)r{N)r|r0rW)r2r=r5rrr6sz,CommandAction._properties..)rur"dirr5rr5r _propertiess    zCommandAction._propertiescCs|jSr')rwr5rrr _substCacheszCommandAction._substCachecCsF|j||j|rd|nd|jd}|r.d|vr2|S||d|i}|S)Nfamily=ro conditionalcache<family) replaceTagrrwreplaceDynamicTags)r#tagrcmdrrr _getOperations zCommandAction._getOperationcsd|f}t|sLts,|j|iSfdd|j|iDS|d}|rz|j|}Wn tyi}|j|<Yn0||<nPz<|j|}|}t|D]\}||kr|=qWntyYn0dS)z? Get, set or delete command of operation considering family. Z__eOpCmdcsg|]\}}|r|qSrrr2fr4rrr rz4CommandAction._operationExecuted..rN)rJr0rwr~r7r;popr8)r#rrr$r=rZfamdr4rrr_operationExecuteds(       z CommandAction._operationExecutedNc sBd}d}|s dd|jD}|D]z||}d}|r|||fddvr|} |jrt|jjdd} | s|jjd} t|jjd| t | d <| d <| || } | | |j }||M}|r|||||r|ndWq$ty} zd }| }WYd} ~ q$d} ~ 00q$|s>td ||j|j|f|S) 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 errorcSsg|]\}}|r|qSrr)r2famoperr4rrrrrz3CommandAction._executeOperation..cs|kSr'r)rrrrrrz1CommandAction._executeOperation..Z actionInfoNtimerFzError %s action %s/%s: %r)rvr7rrr]rWactionsZ_getActionInfosetattrrrr executeCmdrk ValueError RuntimeErrorr^) r#rZ operationr afterExecreserrrretrealCmdrderrr_executeOperations8   zCommandAction._executeOperationcCsH|jd}|dur|Sd}|jD]}t|r"d}q:q"||jd<|S)NZ__hasCondSectionFT)rr~CONDITIONAL_FAM_REmatch)r#r4r3rrr_hasCondSections    zCommandAction._hasCondSectioncCsl|jd}|r|S|jd}|rr)rrvrrr5rr_startedsz&CommandAction._start.._started Zstartingrr)rrvr~rr)r#r forceStartrrrr5rrs zCommandAction._start cCs`|dd}|jr,|j|s,|j|dd|||sDtd||j|ddB|j|<dS) 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. rroTrzError banning %(ip)srN)r~rrvr _processCmdr)r#rdrrrrrrT%s    zCommandAction.bancCs t|do|jot|j S)N actionprolong)rArrisspacer5rrrre;szCommandAction._prolongablecCs|d|std|dS)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)rrrcrrrprolong@s zCommandAction.prolongcCs:|dd}|j|dd@r6|d|s6td|dS)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. rrorr zError unbanning %(ip)sN)r~rvrr)r#rdrrrrrVOs  zCommandAction.unbancCs|||jrdndS)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 r)rTrqrcrrrrU`s zCommandAction.rebancs:ddjD}|sdSfdd}jdd||dS) 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. cSs g|]\}}|d@dkr|qS)rrrrrrryrz'CommandAction.flush..Tcs&|r"j|r"j|dM<dS)N)rvr~rr5rr _afterFlush}sz(CommandAction.flush.._afterFlushz Zflushingr)rvr7r)r#rrrr5rflushos  zCommandAction.flushcCs|S)Executes the "actionstop" command. Replaces the tags in the action command with actions properties and executes the resulting command. )_stopr5rrrrSszCommandAction.stopcs||dur,ddjD}|s$dSi_n2zj|dM<|g}Wnty\YdS0fdd}jdd ||d S) rNcSsg|]\}}|r|qSrrrrrrrrz'CommandAction._stop..Trcs|rd|ddS)Nr)rrr5rr_stoppedsz%CommandAction._stop.._stoppedrZstoppingr)rvr7r;r)r#rrrr5rrs   zCommandAction._stopcKs |ddS)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. zZ reloading)r)r#r%rrrreloads zCommandAction.reloadcCsVd}|jrRt|jD]8\}}|r|||sd|j|<|d|d|dM}q|S)zFExecutes the invariant check with repair if expected (conditional). TrrNF)rrr8rvr7_invariantCheckr)r# beforeRepairrrstartedrrrconsistencyChecks  zCommandAction.consistencyCheckz[\\#&;`|*?~<>^()\[\]{}$'"\n\r]cs(dddfdd}|j||}|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:: \#&;`|*?~<>^()[]{}$'" r3r)r cs|}d||S)N\)groupr~)mcZ_map2crr substCharsz*CommandAction.escapeTag..substChar) ESCAPE_CREsub)rXr>rrrr escapeTags  zCommandAction.escapeTagroc s<d|vr |S|dur:|f}z ||WSty8Yn0t|t}||sd}|durdt|f}z ||WntyYn0durt|j|d|dur||<ttfdd} td} t | |} |rq&| |ks&d| vrq&| }| d8} | dkrt d |fq|dur8| ||<| S) 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)rjaddreplcsn|d}d}r$|d}|durN|}|durN||St|}|jvrj|}|S)Nr?)rr~r _escapedTagsrrrr>ADD_REPL_TAGS_CMrXrZsubInforrsubstVals    z*CommandAction.replaceTag..substValrrzaunexpected too long replacement interpolation, possible self referencing definitions in query: %s) r;rridr r ADD_REPL_TAGSrrrr) rXqueryrdrrrZckeyZ noRecReplZcsubkeyrcountr>rrrrsP         zCommandAction.replaceTagz![\\#&;`|*?~<>\^\(\)\[\]{}$'"\n\r]z\Wcstsfddttfdd}t||}d|vrpdsVifdd}t||}rt|}|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). cs2j|r.djd|}||<d|}|S)Nzf2bV_%sr{$)rsearch ESCAPE_VN_CREr)rr>)rXvarsDictrr escapeValSs  z3CommandAction.replaceDynamicTags..escapeValcsL|d}z |}Wn"ty8||YS0t|}||S)Nr)rr;r~rr)rrdrrrras   z2CommandAction.replaceDynamicTags..substValrzF-*csBt|d}zt|}Wnty2YdS0d||S)NrroZF_)rrrr;r)rtickDatarrsubstTagss  z2CommandAction.replaceDynamicTags..substTag) r"rrrrr~ FCUSTAG_CRErZ buildShellCmd)rXrrdrrrr)rrdrXrrrrr8s     z CommandAction.replaceDynamicTagscCs t|ddS)N _banEpochr)rWr5rrrbanEpochszCommandAction.banEpochcCs6|jdur&|jjjd|_|jj_n |jd|_dS)zIncrements ban epoch of jail and this action, so already banned tickets would cause a re-ban for all tickets with previous epoch.Nr)r]rrrr5rrrinvalidateBanEpochs z CommandAction.invalidateBanEpochTcCs |s|dur||jvrdS|d|}|r8|||jrzrzUnable to restore environmentr) rvrrrkr_errorrZcriticalrrrrr~)r#rrrZcheckCmdZ repairCmdrrrrs6        zCommandAction._invariantCheckc sdkrjddSz |d}Wnttfy>d}Yn0d}|r|jr|fdd}j||dkd }|d kr|d Sjj|rd |ndjd }|dur ||}n} |j }|d 7}|s|d krD|SqDdS)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. ro Nothing to doTrrcs(dkr$jds$jddSdS)NrZactionrepair_on_unbanz,Invariant check failed. Unban is impossible.FT)rr~r_rrrr#rr _beforeRepairs z0CommandAction._processCmd.._beforeRepairrrrFrrN) r_rxr; TypeErrorrrrrrrwrrrk)r#rrdrZrepcntrrrrrrrs.      zCommandAction._processCmdrncKsnttjkrtd||s,tddSt*tj||fddd|WdS1s`0YdS)aIExecutes a command. Parameters ---------- realCmd : str The command to execute. timeout : int The time out in seconds for the command. Returns ------- bool True if the command succeeded. Raises ------ OSError If command fails to be executed. RuntimeError If command execution times out. rTF)shelloutputN) logSysZgetEffectiveLevelloggingDEBUGlogrx _cmd_lockrr)rrkr%rrrrs  zCommandAction.executeCmd)NF)r)N)N)roNN)N)NNT)N)rn)0r,rLrMrNrrrsr&rfr\rrErrgrrrrrrrrrRrrTrerrVrUrrSrrrrecompilerrrrrrrrr staticmethodr __classcell__rrryrrl sf      '           Y   I  ( ?rl)3 __author__Z __copyright__Z __license__rosrsignal subprocessZtempfile threadingrabcrcollections.abcr ImportError collectionsZ failregexrZipdnsrZmytimerZutilsrZhelpersr r r r rrrr,rLockrZ IPv6IsAllowedrrrZ COND_FAMILIESrZ DYN_REPL_TAGSrupdateobjectrrQr}rlrrrrsN      $   oc