
    ogf1-                         d Z dZdZddlZddlZddlZddlZddlmZ ddl	m
Z
mZmZmZ dd	lmZ  e
e      Z G d
 de      Zy)z.Cyril Jaquier, Lee Clemens, Yaroslav HalchenkozPCopyright (c) 2004 Cyril Jaquier, 2011-2012 Lee Clemens, 2012 Yaroslav HalchenkoGPL    N   )Actions   )	getLogger_as_boolextractOptionsMyTime)r
   c                   0   e Zd ZdZg dZddZd Zd Zd Zd Z	d	 Z
d
 Zed        Zed        Zej                  d        Zed        Zed        Zed        Zej                  d        ZddZed        Zd Zd Zd ZddZd Zd dZd Zd!dZd Zy)"Jailag  Fail2Ban jail, which manages a filter and associated actions.

	The class handles the initialisation of a filter, and actions. It's
	role is then to act as an interface between the filter and actions,
	passing bans detected by the filter, for the actions to then act upon.

	Parameters
	----------
	name : str
		Name assigned to the jail.
	backend : str
		Backend to be used for filter. "auto" will attempt to pick
		the most preferred backend method. Default: "auto"
	db : Fail2BanDb
		Fail2Ban persistent database instance. Default: `None`

	Attributes
	----------
	name
	database
	filter
	actions
	idle
	status
	)	pyinotifygaminpollingsystemdNc                 2   || _         t        |      dk\  rt        j                  d|z         || _        t        j                         | _        d | _        i | _	        t        j                  d| j                  z         || j                  |       || _        y )N   z]Jail name %r might be too long and some commands might not function correctly. Please shortenzCreating new jail '%s')	_Jail__dblenlogSyswarning_Jail__namequeueQueue_Jail__queue_Jail__filter	_banExtrainfoname_setBackendbackend)selfr   r    dbs       6/usr/lib/python3/dist-packages/fail2ban/server/jail.py__init__zJail.__init__G   s    $)Y"_	>> 6	  $+$,$-$.++&23G$,    c                 N    | j                   j                  d| j                  dS )N())	__class____name__r   r!   s    r#   __repr__zJail.__repr__X   s    ^^,,dii	88r%   c           	         t        |      \  }}|j                         }| j                  }|dk7  rP|| j                  vr.t        j	                  d|d|d       t        d|d|d      ||j                  |      d  }|D ]x  }t        | d|j                         z        }	  |di | |dk7  r"||k7  rt        j                  d|d|d       nt        j                  d	|z         t        |       | _         y  t        j	                  d| j$                  z         t'        d| j$                  z        # t        $ rJ}t        j                  |dk(  rt        j                   nt        j"                  d
|d|       Y d }~d }~ww xY w)NautozUnknown backend z. Must be among z
 or 'auto'z_init%szCould only initiated z backend whenever z was requestedzInitiated %r backendzBackend z failed to initialize due to z,Failed to initialize any backend for Jail %r )r	   lower	_BACKENDSr   error
ValueErrorindexgetattr
capitalizer   r   r   _Jail__actionsImportErrorlogloggingDEBUGERRORr   RuntimeError)r!   r    beArgsbackendsb
initmethodes          r#   r   zJail._setBackend[   sl   "7+/'6MMO'^^(dnn$
LL 
   x~~g./08 ;ai!,,.89:;&Q'\^^!"G- . [['!+,T]DN
;$ 	,,1DII=?1DII=	? ?  ;
JJ'W]]W]]45q9; ;;s   #AD77	F
 ?FF
c                 v    ddl m} t        j                  d| j                  d|        || fi || _        y )Nr   )
FilterPollJail 'z' uses poller )
filterpollrD   r   r   r   r   )r!   kwargsrD   s      r#   _initPollingzJail._initPolling   s+    $++DIIv>?T,V,$-r%   c                 v    ddl m} t        j                  d| j                  d|        || fi || _        y )Nr   )FilterGaminrE   z' uses Gamin )filtergaminrJ   r   r   r   r   )r!   rG   rJ   s      r#   
_initGaminzJail._initGamin   s+    &++499f=>d-f-$-r%   c                 v    ddl m} t        j                  d| j                  d|        || fi || _        y )Nr   )FilterPyinotifyrE   z' uses pyinotify )filterpyinotifyrN   r   r   r   r   )r!   rG   rN   s      r#   _initPyinotifyzJail._initPyinotify   s+    .++tyy&AB!$1&1$-r%   c                 v    ddl m} t        j                  d| j                  d|        || fi || _        y )Nr   )FilterSystemdrE   z' uses systemd )filtersystemdrR   r   r   r   r   )r!   rG   rR   s      r#   _initSystemdzJail._initSystemd   s+    *++TYY?@//$-r%   c                     | j                   S )zName of jail.
		)r   r+   s    r#   r   z	Jail.name   s     
r%   c                     | j                   S )z;The database used to store persistent data for the jail.
		r   r+   s    r#   databasezJail.database   s     
r%   c                     || _         y NrW   r!   values     r#   rX   zJail.database   s	    $)r%   c                     | j                   S )z;The filter which the jail is using to monitor log files.
		)r   r+   s    r#   filterzJail.filter   s     
r%   c                     | j                   S )z2Actions object used to manage actions for jail.
		)r7   r+   s    r#   actionszJail.actions   s     
r%   c                 ^    | j                   j                  xs | j                  j                  S )z-A boolean indicating whether jail is idle.
		r^   idler`   r+   s    r#   rc   z	Jail.idle   s#     
			.T\\...r%   c                 H    || j                   _        || j                  _        y rZ   rb   r[   s     r#   rc   z	Jail.idle   s    $++$,,r%   c                 z    d| j                   j                  |      fd| j                  j                  |      fgS )zThe status of the jail.
		Filter)flavorr   )r^   statusr`   )r!   rg   s     r#   rh   zJail.status   sB     dkk   /0t||""&"12
 r%   c                 8    | j                   j                          S )z-Retrieve whether queue has tickets to ban.
		)r   emptyr+   s    r#   hasFailTicketszJail.hasFailTickets   s     \\!	!!r%   c                 :    | j                   j                  |       y)zQAdd a fail ticket to the jail.

		Used by filter to add a failure for banning.
		N)r   putr!   tickets     r#   putFailTicketzJail.putFailTicket   s    
 ,,6r%   c                 p    	 | j                   j                  d      }|S # t        j                  $ r Y yw xY w)zTGet a fail ticket from the jail.

		Used by actions to get a failure for banning.
		F)r   getr   Emptyrn   s     r#   getFailTicketzJail.getFailTicket   s6    
LLU#6
=	 
s    55c                 8  	
 | j                   }|dk(  rd }||||<   n||v r||= t        j                  d||       |dk(  r@t        |      ||<   |j	                  |      r!| j
                  t        j                  d       |dv r|t        j                  |      ||<   |dv s|j	                  dd       |dk(  r4||dk7  r|j                  d	      ng D cg c]  }t        |       c}|d
<   |j	                  d
g       	t        |j	                  dd            }t        	      r|f	fd	}n%|j	                  dd      }t        |dd      }||fd}|j	                  dd       |d   |ffd	}|j	                  dd       |d   
|f
fd	}||d<   y y c c}w )N zSet banTime.%s = %s	incrementzDban time increment is not available as long jail database is not set)maxtimerndtime)formulafactorrx   ry   multipliers	evformular|    evmultipliersr{   1c                 ~    | j                   |z  | j                  t              k  r| j                     z  S d   z  S )N)TimeCountr   )ban	banFactorr|   s     r#   <lambda>z&Jail.setBanTimeExtra.<locals>.<lambda>   s@    XX	KSYY[AQ5Q		ZZ WYZZ r%   rz   z?ban.Time * (1<<(ban.Count if ban.Count<20 else 20)) * banFactorz~inline-conf-expr~evalc                 @    t        | j                  t        |            S rZ   )maxr   r   )r   r   rz   s      r#   r   z&Jail.setBanTimeExtra.<locals>.<lambda>  s    #chhPTU\P]B^ r%   rx   c                 (    t         ||             S rZ   )min)r   r}   rx   s     r#   r   z&Jail.setBanTimeExtra.<locals>.<lambda>  s    Ys^W1M r%   ry   c                 D     ||       t        j                          z  z   S rZ   )random)r   r}   ry   s     r#   r   z&Jail.setBanTimeExtra.<locals>.<lambda>	  s    )C.6==?U\C\2\ r%   )r   r   r   r   rr   rX   r   r
   str2secondssplitintr   r   compile)r!   optr\   beir   r}   rz   rx   r|   ry   s           @@@r#   setBanTimeExtrazJail.setBanTimeExtra   s   ~~"
b[5
2c7
by	#w++#S%0Ke_2c7ffSkdmm+
NNYZ""
-  'BsGFF"&&Q\^bJcJk	]@E@QV[_aVaEKK,<gika3q6kB,;BFF8S)*9	+&/ I ffY abGg3V<G&/^I
&&D
!
)mG&/MI
&&D
!
)mG&/]I2k?1 Kl ls   Fc                 V    || j                   j                  |d       S | j                   S rZ   )r   rr   )r!   r   s     r#   getBanTimeExtrazJail.getBanTimeExtra  s(    _
..

S$
''	r%   c                     | j                   j                  d      r| j                   j                  dd      S | j                  j                         S )z)Returns max possible ban-time of jail.
		rw   rx   r   )r   rr   r`   
getBanTimer+   s    r#   getMaxBanTimezJail.getMaxBanTime  sH     nn% 
		Ir	* E+/<<+B+B+DEr%   c                    	 | j                   "| j                  j                  d      rd}|r+| j                         }n| j                  j                         }| j                   j                  | ||| j                  j                  j                        D ]  }	 | j                  j                  |j                         d      r0d|_        |j                  |      }t        j                         |j                         z
  }|dk7  r
|dkD  r||z  }|dk7  r|dk  r| j!                  |        yy# t"        $ rE}t$        j'                  d|t$        j)                         t*        j,                  k  	       Y d}~d}~ww xY w# t"        $ rE}t$        j'                  d
|t$        j)                         t*        j,                  k  	       Y d}~yd}~ww xY w)z5Restore any previous valid bans from the database.
		Nrw   )jail
forbantimecorrectBanTime
maxmatchesT)
log_ignorer   r   zRestore ticket failed: %sexc_infozRestore bans failed: %s)rX   r   rr   r   r`   r   getCurrentBansr^   failManager
maxMatchesinIgnoreIPListgetIDrestoredr
   timegetTimerp   	Exceptionr   r2   getEffectiveLevelr:   r;   )r!   r   r   ro   btmdiftmrB   s          r#   restoreCurrentBanszJail.restoreCurrentBans  s   8
mm~~+&Z))+n ,,))+Z--..DZ"t{{/F/F/Q/Q /  ;;		#	#FLLNt	#	Dhfoj)ckkmfnn..e	uqy
e|s	sax
 !;  2  ;ll.((*GMM9  ; ;; 
 8	<<)1%%'6  8 88s[   BF +D2F AD2F D2.F 2	F ;;E;6F ;F  F 	G;GGc                    t         j                  d| j                         | j                  j	                          | j
                  j	                          | j                          t         j                  d| j                         y)zStart the jail, by starting filter and actions threads.

		Once stated, also queries the persistent database to reinstate
		any valid bans.
		zStarting jail %rzJail %r startedN)r   debugr   r^   startr`   r   r   r+   s    r#   r   z
Jail.start=  sV     	,,!499-++,,+++r%   c           
         |r t         j                  d| j                         | j                  | j                  fD ]'  }	 |r|j                          |r|j                          ) |r!t         j                  d| j                         yy# t        $ rQ}t         j                  d|| j                  |t         j                         t        j                  k         Y d}~d}~ww xY w)z9Stop the jail, by stopping filter and actions threads.
		zStopping jail %rzStop %r of jail %r failed: %sr   NzJail %r stopped)r   r   r   r^   r`   stopjoinr   r2   r   r:   r;   r   )r!   r   r   objrB   s        r#   r   z	Jail.stopI  s     
	<<"DII.kk4<<( 
9c	9XXZXXZ
9 
	;; $)), 
  9
LL0#tyy!&&('--7  9 99s   $B			C#ACC#c                 n    | j                   j                         xs | j                  j                         S )z?Check jail "isAlive" by checking filter and actions threads.
		)r^   isAliver`   r+   s    r#   r   zJail.isAlive\  s)     
				8$,,"6"6"88r%   )r.   N)basicrZ   )T)TT)r*   
__module____qualname____doc__r1   r$   r,   r   rH   rL   rP   rT   propertyr   rX   setterr^   r`   rc   rh   rk   rp   rt   r   r   r   r   r   r   r   r/   r%   r#   r   r   '   s   : :"9$?L-
.20  
  
 //   
  
 / /
 ++  " "
	*Z
E"8H
,-&9r%   r   )
__author____copyright____license__r:   mathr   r   r`   r   helpersr   r   r	   r
   mytimer*   r   objectr   r/   r%   r#   <module>r      sH   , >
b      A A  
8	x96 x9r%   