o ;s*bv@stdZdZdZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z zddl mZWneyCddlmZYnwddlmZdd 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 HalchenkoGPLN)ABCMeta)MutableMapping) mapTag2Opt)DNSUtils)MyTime)Utils) getLogger_merge_copy_dicts splitwordssubstituteRecursiveTags uni_stringTAG_CREMAX_TAG_REPLACE_COUNTz)inet4inet6z^(\w+)\?(family)=(.*)$cCttjddS)NTfqdnstrr getHostnamerr8/usr/lib/python3/dist-packages/fail2ban/server/action.py?rcCr)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 immutable __org_datacOs"t|_d|_t|i||_dS)NT)dictr$r%r#)selfargskwargsrrr__init___szCallingMap.__init__TcCs2t|_z|j|_Wn tyYnw||_dSN)r'r$_CallingMap__org_datar#AttributeErrorr%)r(r%rrrresetds   zCallingMap.resetFcCsd|jj||tfS)Nz%s(%r)) __class____name___asdictr)r( calculatedrrr_asreprlszCallingMap._asreprNcstjfij}|stfdd|DSt|D]\}}t|r>z|}|r3|||||<WqYqq|S)Nc3s.|]\}}t|r|jvr||fVqdSr,)callable CM_REPR_ITEMS).0nvr(rr us  z%CallingMap._asdict..)r'r#r$itemslistr5 __getitem__)r(r3checkerdr8r9rr:rr2rs    zCallingMap._asdictcCs0z|j|}W|Sty|j|}Y|Swr,)r$KeyErrorr#r(keyvaluerrr getRawItems  zCallingMap.getRawItemcCsbz|j|}Wnty|j|}Ynwt|r/t|dr'|jjr'||n|}||j|<|S)N__code__)r$rAr#r5hasattrrF co_argcountrBrrrr>s   zCallingMap.__getitem__cCs:|jr|j|_|j|_|j|_d|_||j|<dSNF)r%r$copyr#r-rBrrr __setitem__s   zCallingMap.__setitem__cCs td|)NzKey %r was deleted)rAr(rCrrr __unavailables zCallingMap.__unavailablecCsX|jr|j|_|j|_|j|_d|_z|j|=Wn ty%Ynw|j|=dSrI)r%r$rJr#r-rArLrrr __delitem__s     zCallingMap.__delitem__cC t|jSr,)iterr#r:rrr__iter__ zCallingMap.__iter__cCrOr,)lenr#r:rrr__len__rRzCallingMap.__len__cCs|t|j|jSr,)r0r r#r$r:rrrrJszCallingMap.copy)T)F)FN)r1 __module__ __qualname____doc__r6 __slots__r+r/r4__repr__r2rEr>rK_CallingMap__unavailablerNrQrTrJrrrrr"Js"       r"c@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)r5getattr)clsCrequiredmethodrrr__subclasshook__s zActionBase.__subclasshook__cCs"||_||_td|jj|_dS)Nz fail2ban.%s)_jail_namer r0r1_logSysr(jailnamerrrr+szActionBase.__init__cCdS)z,Executed when the jail/action is started. Nrr:rrrr\zActionBase.startcCrm)z,Executed when the jail/action is stopped. Nrr:rrrr]rnzActionBase.stopcCrm)Executed when a ban occurs. Parameters ---------- aInfo : dict Dictionary which includes information in relation to the ban. Nrr(aInforrrr^ zActionBase.bancCs ||S)ro)r^rprrrr_s zActionBase.rebancCrmrIrr:rrr _prolongable zActionBase._prolongablecCrm)zExecuted when a ban expires. Parameters ---------- aInfo : dict Dictionary which includes information in relation to the ban. Nrrprrrr`rrzActionBase.unbanN)r1rUrVrW classmethodrfr+r\r]r^r_propertyrsr`rrrrr[s     r[) metaclass str2secondsignore)timeoutbantimecseZdZdZedZddZfddZeddZ 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 dPd6d7Z!e"#d8Z$ed9d:Z%edQdZ$e"#d?Z'edPd@dAZ(e dBdCZ)dDdEZ*dRdGdHZ+dPdIdJZ,e-dSdLdMZ.Z/S)T 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 ipjailmatchescCsXd|_z$d|_d|_d|_d|_d|_d|_d|_d|_d|_ d|_ Wd|_dSd|_w)z8 Clear all lists/dicts parameters (used by reloading) r<rN) _CommandAction__initrz actionstart actionban actionreban actionunban actioncheck actionrepair actionflush actionstop actionreloadr:rrrclearAllParams>szCommandAction.clearAllParamscsHtt|||d|_d|_i|_i|_||j d|j dS)Nrz Created %s) superr|r+r_CommandAction__properties_CommandAction__started_CommandAction__substCacherridebugr0rjr0rrr+XszCommandAction.__init__cCstSr,)NotImplemented)rbrcrrrrfartzCommandAction.__subclasshook__cCsn|ds0|js0t|s0t|}|dkrdS|dkr t|}d|_|j |j d||||j |<dS)N_ryrxz Set %s = %r) startswithrr5WRAP_CMD_PARAMSgetrrxrrclearrir__dict__)r(rlrDwrprrr __setattr__es   zCommandAction.__setattr__cCs4|dsd|_|j|jd||j|=dS)Nrz Unset %s)rrrrrirr)r(rlrrr __delattr__ws   zCommandAction.__delattr__cs2jdurjStfddtD_jS)z`A dictionary of the actions properties. This is used to substitute "tags" in the commands. Nc3s6|]}|dstt|s|t|fVqdS)rN)rr5ra)r7rCr:rrr;s   z,CommandAction._properties..)rr'dirr:rr:r _propertiess   zCommandAction._propertiescCs|jSr,)rr:rrr _substCacheszCommandAction._substCachecCsF|j||j|r d|nd|jd}d|vs|s|S||d|i}|S)Nfamily=r conditionalcache<family) replaceTagrrreplaceDynamicTags)r(tagrcmdrrr _getOperations zCommandAction._getOperationcsd|f}t|s&ts|j|iSfdd|j|iDS|d}|rJz|j|}WntyCi}|j|<Ynw||<dSz|j|}|}t|D] \}||krf|=q[WdStysYdSw)z? Get, set or delete command of operation considering family. __eOpCmdcsg|] \}}|r|qSrrr7fr9rrr sz4CommandAction._operationExecuted..rN)rSr5rrr<rApopr=)r(rrr)rCrfamdr9rrr_operationExecuteds0      z CommandAction._operationExecutedNc s<d}d}|sdd|jD}|D]{zc||}d}|rd|||fddvrd|} |jrYt|jjdd} | sI|jjd} t|jjd| t | d <| d <| || } | | |j }||M}|rk|||||rs|ndWqty} z d }| }WYd} ~ qd} ~ ww|std ||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 errorcSg|]\}}|r|qSrr)r7famoperr9rrrrz3CommandAction._executeOperation..cs|kSr,r)rrrrrsz1CommandAction._executeOperation.. actionInfoNtimerFzError %s action %s/%s: %r)rr<rrrgraactions_getActionInfosetattrrrr executeCmdrz ValueError RuntimeErrorrh) r(r operationr afterExecreserrrretrealCmdrqerrr_executeOperations<   zCommandAction._executeOperationcCsH|jd}|dur |Sd}|jD] }t|rd}nq||jd<|S)N__hasCondSectionFT)rrCONDITIONAL_FAM_REmatch)r(r9r8rrr_hasCondSections    zCommandAction._hasCondSectioncCsl|jd}|r |S|jd}|rt|ttfst|}n|jr,tr(ddgndg}ndg}||jd<|S)N __familiesfamiliesrrr)rr isinstancer=setr r allowed_ipv6r(r9rrr _familiess    zCommandAction._familiescCs,|jd}|dur |S|j}||jd<|S)z1Checks the action depends on family (conditional)actionstart_on_demandN)rrrrrrr_startOnDemands  zCommandAction._startOnDemandcC|S)Executes the "actionstart" command. Replace the tags in the action command with actions properties and executes the resulting command. )_startr:rrrr\ zCommandAction.startFcsZjr|sdSn |sj|rdS|dur|gnj}fdd}jdd||d}|S)rTNcs$|rd|ddj|<dSdS)N r)rrrrr:rr_startedsz&CommandAction._start.._started startingrr)rrrrr)r(r forceStartrrrr:rrs zCommandAction._start cCs`|dd}|jr|j|s|j|dd|||s"td||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. rrTrzError banning %(ip)srN)rrrr _processCmdr)r(rqrrrrrr^%s    zCommandAction.bancCs t|do|jot|j S)N actionprolong)rGrrisspacer:rrrrs;szCommandAction._prolongablecCs|d|s td|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)rrrprrrprolong@s zCommandAction.prolongcCs>|dd}|j|dd@r|d|std|dSdS)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(rqrrrrr`Os   zCommandAction.unbancCs|||jr dSdS)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)r^rrprrrr_`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)rrrrrrrys z'CommandAction.flush..Tcs.|rj|rj|dM<dSdSdS)N)rrrr:rr _afterFlush}sz(CommandAction.flush.._afterFlushz flushingr)rr<r)r(rrrr:rflushos  zCommandAction.flushcCr)Executes the "actionstop" command. Replaces the tags in the action command with actions properties and executes the resulting command. )_stopr:rrrr]rzCommandAction.stopcs||durddjD}|sdSi_nzj|dM<|g}Wn ty.YdSwfdd}jdd ||d S) rNcSrrrrrrrrrz'CommandAction._stop..Trcs|r d|ddSdS)Nr)rrr:rr_stoppedsz%CommandAction._stop.._stoppedrstoppingr)rr<rAr)r(rrrr:rrs   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. z reloading)r)r(r*rrrreloads zCommandAction.reloadcCsVd}|jr)t|jD]\}}|r(|||s(d|j|<|d|d|dM}q |S)zFExecutes the invariant check with repair if expected (conditional). TrrNF)rr=rr<_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:: \#&;`|*?~<>^()[]{}$'" r8r)r cs|}d||S)N\)groupr)mc_map2crr substCharsz*CommandAction.escapeTag..substChar) ESCAPE_CREsub)rbrDrrrr escapeTags  zCommandAction.escapeTagrc s4d|vr|S|dur|f}z||WStyYnwt|t}||sZd}|durEdt|f}z||Wn tyDYnwdurRt|j|d|durZ||<ttfdd} td} t | |} |run| |ks}d| vr~n| }| d8} | d krt d |fql|dur| ||<| 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)ryaddreplcsn|d}d}r|d}|dur'|}|dur'||St|}|jvr5|}|S)Nr?)rrr _escapedTagsrrrrDADD_REPL_TAGS_CMrbrsubInforrsubstVals    z*CommandAction.replaceTag..substValrTrzaunexpected too long replacement interpolation, possible self referencing definitions in query: %s) rArr"idrr ADD_REPL_TAGSrrrr) rbqueryrqrrrckey noRecReplcsubkeyrcountrDrrrrsX        zCommandAction.replaceTagz![\\#&;`|*?~<>\^\(\)\[\]{}$'"\n\r]z\Wcsts fddttfdd}t||}d|vr8ds+ifdd}t||}r@t|}|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|rdjd|}||<d|}|S)Nzf2bV_%sr$)rsearch ESCAPE_VN_CREr)rrD)rbvarsDictrr escapeValSs z3CommandAction.replaceDynamicTags..escapeValcsL|d}z|}Wnty||YSwt|}||S)Nr)rrArrr)rrqrrrras    z2CommandAction.replaceDynamicTags..substValrzF-*csBt|d}zt|}Wn tyYdSwd||S)NrrF_)rrrrAr)rtickDatarrsubstTagss z2CommandAction.replaceDynamicTags..substTag) r'r"r rrr FCUSTAG_CREr buildShellCmd)rbrrqrrrr)rrqrbrrrrr8s     z CommandAction.replaceDynamicTagscCs t|ddS)N _banEpochr)rar:rrrbanEpochs zCommandAction.banEpochcCs8|jdur|jjjd|_|jj_dS|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)rgrrrr:rrrinvalidateBanEpochs z CommandAction.invalidateBanEpochTcCs|s |dur ||jvr dS|d|}|r|||jrdS|r%|s%dS|jd||d|}|rQ|||jsKd|j|<|jddSd|j|<nz||Wn t yaYnw|j ||pj|j d |j |r|||js|jddSdS) z0Executes a substituted `actioncheck` command. Nrz zrzUnable to restore environmentr) rrrrzrierrorrcriticalrrrrr)r(rrrcheckCmd repairCmdrrrrs8        zCommandAction._invariantCheckc sdkr jddSz|d}Wn ttfyd}Ynwjr:fdd}j||dkd}|d kr:d Sjj|rEd |ndjd }|d urV ||}n} |j S)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 doTrcs(dkrjdsjddSdS)Nractionrepair_on_unbanz,Invariant check failed. Unban is impossible.FT)rrrirrrr(rr _beforeRepairs z0CommandAction._processCmd.._beforeRepairrrrFrrN) rirrA TypeErrorrrrrrrrrz)r(rrqrr%rrrr$rrs(   zCommandAction._processCmdrcKsnttjkr td||stddSttj||fddd|WdS1s0wYdS)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. r"TF)shelloutputN) logSysgetEffectiveLevelloggingDEBUGlogr _cmd_lockr r)rrzr*rrrrs  $zCommandAction.executeCmdrI)rr,)rNN)NNT)r)0r1rUrVrWrrrr+rurfrrKrrvrrrrrrrrr\rr^rsrr`r_rr]rrrrecompilerrrrrrrrr staticmethodr __classcell__rrrrr| sh     '           Y  I   (8r|)3 __author__ __copyright__ __license__r,osr0signal subprocesstempfile threadingrabcrcollections.abcr ImportError collections failregexripdnsrmytimerutilsr helpersr r r rrrrr1r*Lockr/ IPv6IsAllowedrr1r COND_FAMILIESr DYN_REPL_TAGSr updateobjectr"r[rr|rrrrsR      $   oc