HEX
Server: Apache/2.4.65 (Debian)
System: Linux kubikelcreative 5.10.0-35-amd64 #1 SMP Debian 5.10.237-1 (2025-05-19) x86_64
User: www-data (33)
PHP: 8.4.13
Disabled: NONE
Upload Files
File: //usr/lib/python3/dist-packages/fail2ban/server/__pycache__/actions.cpython-39.pyc
a

���``�@s�dZdZdZddlZddlZddlZddlZddlmZzddlm	Z	Wne
y^eZ	Yn0ddlm
Z
mZdd	lmZdd
lmZddlmZmZmZddlmZdd
lmZddlmZddlmZee�Z Gdd�dee�Z!dS)z
Cyril Jaquierz Copyright (c) 2004 Cyril JaquierZGPL�N)�Mapping)�OrderedDict�)�
BanManager�	BanTicket)�IPAddr)�
JailThread)�
ActionBase�
CommandAction�
CallingMap)�MyTime)�	Observers)�Utils�)�	getLoggerc@seZdZdZdd�Zedd��Zd?dd	�Zd@dd�Zd
d�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�ZdAdd �Zd!d"�ZdBd#d$�ZdCd%d&�Zd'd(�ZGd)d*�d*e�Zd+d,�ZdDd.d/�ZdEd0d1�ZdFd2d3�Zd4d5�ZdGd6d7�ZdHd8d9�ZdId:d;�Z dJd=d>�Z!dS)K�Actionsa�Handles 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.
	cCsLtj|d|jd�||_t�|_t�|_d|_d|_	d|_
|j
d|_dS)Nzf2b/a.)�namer�
r)r�__init__r�_jailr�_actionsr�_Actions__banManager�banEpoch� _Actions__lastConsistencyCheckTM�
banPrecedence�
unbanMaxCount)�self�jail�r�9/usr/lib/python3/dist-packages/fail2ban/server/actions.pyrNszActions.__init__cCsFt�|�}t|d�s"td|��n t|jt�sBtd||jjf��|S)N�Actionz&%s module does not have 'Action' classz0%s module %s does not implement required methods)rZload_python_module�hasattr�RuntimeError�
issubclassr r	�__name__)�pythonModule�modrrr�_load_python_module\s

���zActions._load_python_moduleNFcCs�||jvrN|std|��|j|}t|d�rNt|d�rJ|��||j|<dS|durdt|j|�}n |�|�}|j|j|fi|��}||j|<dS)a�Adds 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 exists�reload�clearAllParamsN)	r�
ValueErrorr!r)�_reload_actionsr
rr'r )rrr%�initOptsr(�actionZcustomActionModulerrr�addis





zActions.addTcs�|rt��_n�t�d�r��j��D]0\}}|�jvr"�j|jfi|rJ|ni��q"t�fdd��j��D��}t|�r��jd|dd��j	|d�t
�d�dS)	z@ Begin or end of reloading resp. refreshing of all parameters
		r+c3s$|]\}}|�jvr||fVqdS�N)r+��.0rr-�rrr�	<genexpr>�s

�z!Actions.reload.<locals>.<genexpr>FT)�db�actions�stop�r5N)�dictr+r!�itemsrr(r�len�_Actions__flushBan�stopActions�delattr)rZbeginrr,Zdelactsrr2rr(�s


 zActions.reloadcCs0z|j|WSty*td|��Yn0dS�NzInvalid Action name: %s�r�KeyError�rrrrr�__getitem__�szActions.__getitem__cCs0z|j|=Wnty*td|��Yn0dSr>r?rArrr�__delitem__�szActions.__delitem__cCs
t|j�Sr/)�iterrr2rrr�__iter__�szActions.__iter__cCs
t|j�Sr/)r:rr2rrr�__len__�szActions.__len__cCsdS�NFr)r�otherrrr�__eq__�szActions.__eq__cCst|�Sr/)�idr2rrr�__hash__�szActions.__hash__cCs(t�|�}|j�|�t�d|�dS)Nz
  banTime: %s)rZstr2secondsr�
setBanTime�logSys�info)r�valuerrrrL�s
zActions.setBanTimecCs
|j��Sr/)r�
getBanTimer2rrrrP�szActions.getBanTimecsD|j���|s�St|�dkr2|d�vr.dSdS�fdd�|D�S)Nrrcsg|]}|�vrdnd�qS)rrr�r1�ip��lstrr�
<listcomp>��z%Actions.getBanned.<locals>.<listcomp>)r�
getBanListr:)rZidsrrSr�	getBanned�s
zActions.getBannedcCs|jjd|d�S)zkReturns the list of banned IP addresses.

		Returns
		-------
		list
			The list of banned IP addresses.
		T)Zordered�withTime)rrW)rrYrrrrW�szActions.getBanListcs<t���t|t�r&�fdd�|D�}nt|��f}|�|�S)zBan an IP or list of IPs.c3s|]}t|��VqdSr/)rrQ�ZunixTimerrr3�rVz&Actions.addBannedIP.<locals>.<genexpr>)r�time�
isinstance�listr�_Actions__checkBan)rrR�ticketsrrZr�addBannedIP�s

zActions.addBannedIPc	Cs2|dur|�|�St|ttf�r~g}d}|D]<}z||�|||�7}Wq,tyf|sb|�|�Yq,0q,|rztd|��|S|r�|jjdur�|jj�	|j|�|j
�|�}|dur�|�|�nnt|t
��st
|�}|j�stt|j|j
����}	|	�r|�|	||�Sd|}
t�tj|
�|�r&dSt|
��dS)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
		Nrznot banned: %rz%s is not bannedr)r;r\r]�tuple�removeBannedIPr*�appendr�database�delBanrZ
getTicketByID�_Actions__unBanrZisSingle�filter�containsrWrM�log�loggingZMSG)rrRr4ZifexistsZmissed�cnt�i�ticketZipaZips�msgrrrrb�s>
zActions.removeBannedIPcCs�|dur|j}t|���}|��|D]v\}}z|��WnFty�}z.tjd|jj	||t�
�tjkd�WYd}~n
d}~00|j|=t�
d|jj	|�q&dS)z>Stops the actions in reverse sequence (optionally filtered)
		Nz(Failed to stop jail '%s' action '%s': %s��exc_infoz%s: action %s terminated)rr]r9�reverser6�	ExceptionrM�errorrr�getEffectiveLevelrj�DEBUG�debug)rr5Z
revactionsrr-�errrr</s
�zActions.stopActionscs�d}�j��D]\\}}z|��Wqtyh}z.tjd�jj||t��t	j
kd�WYd}~qd}~00q�j�rƐz�jr�t�
d�t��fdd�dd��j�t�
d	�Wqld}t�j�jjt���}t�d
d|�j�t��fdd�|��r���}||7}|�r|�jk�rz�j�rv|d
9}t�d
d|�rF|�jk�rF|n�j|�j���|�rn|�jk�rn|n�j�d}Wqlt�y�}z,tjd�jj|t��t	j
kd�WYd}~qld}~00ql�jdd����dS)z�Main 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': %sroNzActions: enter idle modecs�jp�jSr/)�active�idlerr2rr�<lambda>XrVzActions.run.<locals>.<lambda>cSsdSrGrrrrrrzYrVzActions: leave idle mode�z1Actions: wait for pending tickets %s (default %s)cs�jp�jjSr/)rxrZhasFailTicketsrr2rrrz`rVrz+Actions: check-unban %s, bancnt %s, max: %sz*[%s] unhandled error in actions thread: %sT)r6)rr9�startrrrMrsrrrtrjrurxryrvrZwait_forZ	sleeptime�minrZ_nextUnbanTimerr[rir^rr�_Actions__checkUnBanr;r<)rrkrr-rwZbancntZwtrr2r�runAsL
�

�
,"�zActions.runc@s�eZdZdZdd�dd�dd�dd�dd�dd�d	d�d
d�dd�dd�d
d�d!dd�dd�dd�dd�dd�dd�d�ZejdZddefdd�Zdd�Zdd�Z	d"dd �Z
dS)#zActions.ActionInfo)�fid�
raw-ticketcCs
|j��Sr/)�_ActionInfo__ticket�getIPr2rrrrzyrVzActions.ActionInfo.<lambda>cCs
|djS�NrR)Z	familyStrr2rrrrzzrVcCs|d�d�S)NrR�)ZgetPTRr2rrrrz{rVcCs|d��Sr�)ZgetHostr2rrrrz|rVcCs
|j��Sr/)r�ZgetIDr2rrrrz}rVcCs
|j��Sr/)r��
getAttemptr2rrrrz~rVcCs
|j��Sr/)r��getTimer2rrrrzrVcCs|��Sr/)�_getBanTimer2rrrrz�rVcCs
|j��Sr/)r�ZgetBanCountr2rrrrz�rVcCsd�|j���S�N�
)�joinr��
getMatchesr2rrrrz�rVcCs|jjrdSdS)Nrr)r��restoredr2rrrrz�rVNcCs|j�|�Sr/)r�ZgetData)r�tagrrrrz�rVcCsd�|�d����S)Nr�T�r��_mi4ipr�r2rrrrz�rVcCsd�|�����Sr�r�r2rrrrz�rVcCs|�d���S)NT�r�r�r2rrrrz�rVcCs|����Sr/r�r2rrrrz�rVcCs
t|j�Sr/)�reprr�r2rrrrz�rV)rRZfamilyzip-revzip-hostr�Zfailuresr[ZbantimeZbancountZmatchesr�zF-*Z	ipmatchesZ
ipjailmatchesZ
ipfailuresZipjailfailuresr�)Z__ticketZ__jail�__mi4ipTcCs$||_||_t�|_||_||_dSr/)r��_ActionInfo__jailr8Zstorage�	immutable�data)rrmrr�r�rrrr�s
zActions.ActionInfo.__init__cCs|�|j|j|j|j���Sr/)�	__class__r�r�r�r��copyr2rrrr��szActions.ActionInfo.copycCs&|j��}|dur|jj��}t|�Sr/)r�rPr�r5�int)r�btimerrrr��s
zActions.ActionInfo._getBanTimeFc
Cs�t|d�si|_|j}|rdnd}||vrD||dur>||S|jSzT|j}|d}d||<|jsj|jWS|r�|jj|d�||<n|jj||d�||<WnDty�}z,tjd||j	|t�
�tjkd	�WYd}~n
d}~00||dur�||S|jS)
a�Gets 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
			r��allrNrR)rR)rRrz+Failed to get %s bans merged, jail '%s': %sro)
r!Z_ActionInfo__mi4ipr�r�rdZ
getBansMergedrrrMrsrrtrjru)rZoveralljails�mi�idxrrRrwrrrr��s,
�zActions.ActionInfo._mi4ip)N)F)r$�
__module__�__qualname__Z
CM_REPR_ITEMSZAI_DICTr�	__slots__rr�r�r�rrrr�
ActionInfots0�
r�cCs$|stdt���}t�||j�}|S)Nr�)rrr[rr�r)rrm�aInforrr�_getActionInfo�szActions._getActionInfo�dccs0d}||kr,|j��}|sq,|V|d7}qdS)zAGenerator to get maximal count failure tickets from fail-manager.rrN)rZ
getFailTicket)r�countrkrmrrrZ__getFailTickets�s
zActions.__getFailTicketsc
s�d}|s|�|j�}d}|D�]b}t�|��|�|j���}���}|���}i}|jj�|d��rX|d7}t	j
dur��js�t	j
�d�|j
|�t�d|j
j�js�dnd|�|j��D]�\}	}
z2�jr�t|
d	d
�r�Wq�|js�|��|
�|�Wq�t�y<}z0tjd|j
j|	||t��tjkd�WYd}~q�d}~00q�d
�_|j�r�|j�_q|�dd��rzt�d|j
j|�q|�d����j�rr|� ��� �}|dk�r�tjn|dk�r�tj!ntj"}
t�#|
d|j
j|��j|jk�r.|dk�r.|�s.t$�%�|j&dk�r.|j�'�D]}
|
�(��qt$�%�|_&�j|jk�r�|�s^t)�fdd�|j��D��}||j*�|d�7}q||�*��7}q|�r�t�+d||j�,�|j�-�|j
j�|S)aCheck for IP address to ban.

		If tickets are not specified look in the jail queue for FailTicket. If a ticket is available,
		it executes the "ban" command and adds a ticket to the BanManager.

		Returns
		-------
		bool
			True if an IP address get banned.
		rN)�reasonrZbanFoundz
[%s] %sBan %sr�zRestore �
norestoredF�9Failed to execute ban jail '%s' action '%s' info '%r': %sroTZexpiredz[%s] Ignore %s, expired bantimerm��<z[%s] %s already bannedc3s&|]\}}|j�jkr||fVqdSr/)rr0�ZbTicketrrr3#s�z%Actions.__checkBan.<locals>.<genexpr>r7z"Banned %s / %s, %s ticket(s) in %r).�_Actions__getFailTicketsrrZwraprPrr�r�ZaddBanTicketr
ZMainr�r.rrM�noticerrr9�getattrr��resetZbanrrrsrtrjru�bannedr�getrNr�ZNOTICEZWARNINGrirr[r�values�consistencyCheckr8�_Actions__reBanrv�getBanTotal�size)rr_rkZ	rebanactsrmr�rRr�r�rr-rwZdiftmZllrr�rZ
__checkBan�sr


�
�
��zActions.__checkBanc	Cs|p|j}|��}|�|�}|rXt�d|jj|dt|�dkrRdt|�	��dnd�|�
�D]�\}}z0t�d|jj||�|js�|�
�|�|�Wq`ty�}z4tjd|jj|||t��tjkd	�WYd
}~dSd
}~00q`d|_|j�r�|j|_dS)z�Repeat 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%srRrz, action %rrr�z[%s] action %r: reban %sz;Failed to execute reban jail '%s' action '%s' info '%r': %sroNT)rr�r�rMr�rrr:r]�keysr9rvr�r�Zrebanrrrsrtrjrur�r)	rrmr5rirRr�rr-rwrrrZ__reBan0s*

8�zActions.__reBancCs�|j�|�sdSd}|j��D]�\}}zN|jr>t|dd�r>Wq|jsHWq|durZ|�|�}|jsh|�	�|�
|�Wqty�}z0tj
d|jj|||t��tjkd�WYd}~qd}~00qdS)Nr�Fr�ro)rZ
_inBanListrr9r�r�Z_prolongabler�r�r�ZprolongrrrMrsrrrtrjru)rrmr�rr-rwrrr�_prolongBanRs$
�zActions._prolongBancCsP|j�t��|�}|D]}|�|�qt|�}|rLt�d||j��|j	j
�|S)zKCheck for IP address to unban.

		Unban IP addresses which are outdated.
		zUnbanned %s, %s ticket(s) in %r)rZ	unBanListrr[rfr:rMrvr�rr)rZmaxCountrTrmrkrrrZ__checkUnBanis�zActions.__checkUnBancs�d}|dur"t�d��j��}nd}t�j�}d}i}|durD|n�j��D]�\}�z<t�d�r�t�t	�rr�j
r�t�d�jj
|����r�WqNWn�t�y}	zjtjd�jj
||	t��tjkd	�t�d
�t�d��r���fdd
�}
��|
�WYd}	~	qNWYd}	~	n
d}	~	00t�d��||<qN|}|�r^�jjdu�r^t�d��jj��j�|D]}�j|||d�|d7}�qbt�d|�j���jj
�|S)z�Flush the ban list.

		Unban all IP address which are still in the banning list.

		If actions specified, don't flush list - just execute unban for 
		given actions (reload, obsolete resp. removed actions).
		TNz  Flush ban listFr�flushz[%s] Flush ticket(s) with %sz1Failed to flush bans in jail '%s' action '%s': %sroz'No flush occurred, do consistency checkr�cs$�r t�dd�s �j�d�dSdS)NZactionrepair_on_unbanz,Invariant check failed. Flush is impossible.FT)r�Z_logSysrsr�r-rr6rr�
_beforeRepair�sz)Actions.__flushBan.<locals>._beforeRepairz   Unban tickets each individualyz  Flush jail in database)r5rirz!  Unbanned %s, %s ticket(s) in %r)rMrvrZflushBanListrDrr9r!r\r
Zactionflushr�rrr�rrrsrtrjrurNr�rdrerfr�)rr4r5r6rirTrk�
unbactionsrrwr�rmrr�rZ
__flushBanwsJ


�

"


�zActions.__flushBanc
Cs�|dur|j}n|}|��}|�|�}|r@t�d|jj|d�|��D]�\}}z0t�d|jj||�|j	st|�
�|�|�WqHty�}	z0tj
d|jj|||	t��tjkd�WYd}	~	qHd}	~	00qHdS)z�Unbans 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 %srRz[%s] action %r: unban %sz;Failed to execute unban jail '%s' action '%s' info '%r': %sro)rr�r�rMr�rrr9rvr�r�Zunbanrrrsrtrjru)
rrmr5rir�rRr�rr-rwrrrZ__unBan�s$
�zActions.__unBan�basiccCs�gd�}|dus||vr*t�d||f�|dkrF|j��}t|�}n
|j��}d|fd|j��fg}|dkr||d|fg7}|dkr�|j��}|d	|j�|�fd
|j�	|�fd|j�
|�fg7}|S)zEStatus of current and total ban counts and current banned IP list.
		)�shortr��cymruNz9Unsupported extended jail status flavor %r. Supported: %sr�zCurrently bannedzTotal bannedzBanned IP listr�zBanned ASN listzBanned Country listzBanned RIR list)rMZwarningrrWr:r�r�ZgetBanListExtendedCymruInfoZgeBanListExtendedASNZgeBanListExtendedCountryZgeBanListExtendedRIR)rZflavorZsupported_flavorsr�rkZretZ
cymru_inforrr�status�s*


�
��zActions.status)NNF)T)F)NTF)N)r�)N)NT)N)FNF)NT)r�)"r$r�r��__doc__r�staticmethodr'r.r(rBrCrErFrIrKrLrPrXrWr`rbr<rrr�r�r�r^r�r�r~r;rfr�rrrrr2s<

.




:
3X


T
"

6
r)"�
__author__Z
__copyright__Z__license__rj�os�sysr[�collectionsrr�ImportErrorr8Z
banmanagerrrZipdnsrZ
jailthreadrr-r	r
rZmytimerZobserverr
ZutilsrZhelpersrr$rMrrrrr�<module>s*