
    Gkc1                        d Z dZdZddlZddlZddlmZ ddlmZm	Z	m
Z
 dd	lmZ  ee      Z ej                  d
      Z ej                  d      dfZ ej                  d      Z ej                  d      Z ej                  d      Z ej                  d      Z ej                  d      Z ej                  d      Z ej                  d      Z ej                  d      d fZ ej                  d      Z ej                  d      Z ej                  d      Z ej                  dej:                        Z G d de      Z  G d de       Z! G d de       Z" G d  d!e       Z#y)"zCyril Jaquierz Copyright (c) 2004 Cyril JaquierGPL    N)abstractmethod   )reGroupDictStrptimetimeREgetTimePatternRE   )	getLoggerz(?<!(?:\(\?))(?<!\\)\((?!\?)z-^((?:\(\?\w+\))?\^?(?:\(\?\w+\))?)(.*?)(\$?)$z\1(\2)\3z((?:^|(?!<\\))\(\?[a-z]+\))z^\{UNB\}z^\{\^LN-BEG\}z^\((?:\?:)?\^\|\\b\|\\W\)z\(\?=\\b\|\\W\|\$\)$z-^\(*(?:\(\?\w+\))?(?:\^|\(*\*\*|\((?:\?:)?\^)z!(?<!\\)(?:\$\)?|\\b|\\s|\*\*\)*)$z)^\(*(?:\(\?\w+\))?\(*\*\*|(?<!\\)\*\*\)*$c                 B    | j                         j                  dd      S )Nz** )groupreplace)ms    >/usr/lib/python3/dist-packages/fail2ban/server/datetemplate.py<lambda>r   /   s    qwwy00r:     z(^(?:\(\?\w+\))?(?:\^|\((?:\?:)?\^(?!\|))z(?<![\\\|])(?:\$\)?)$z(?<!\%)\%[aAbBpc]z(?<!\\)\{L?EPOCH\}c                   x    e Zd ZdZdZdZdZdZd Zd Z	ddZ
 ee	e
d	
      Zd Zd Zedd       Zed        Zy)DateTemplatezA template which searches for and returns a date from a log line.

	This is an not functional abstract class which other templates should
	inherit from.

	Attributes
	----------
	name
	regex
	      r	   r   c                 f    d| _         d| _        d| _        d| _        d| _        d| _        d | _        y )Nr   g      ?r   )nameweightflagshitstime_regex_cRegexselfs    r   __init__zDateTemplate.__init__J   s3    $)$+$*$)$)$+$,r   c                     | j                   S N)r   r   s    r   getRegexzDateTemplate.getRegexS   s    	r   c                    |j                         }t        j                  |      }|rt        j                  d|d      }|xr t        j                  |       }|xr t
        j                  |       }t        j                  |      s t        d   j                  t        d   |      }d| _        |rw| xj                  |dk7  rt        j                  nt        j                  z  c_        |dk7  rd|z   }n4d|z   }| j                  j                  d      sd| j                  z   | _        |r(| xj                  t        j                  z  c_        |d	z  }| j                  t        j                  z  s8t        j                  |      r#| xj                  t        j                  z  c_        | j                  t        j                   z  s8t"        j                  |      r#| xj                  t        j                   z  c_        t$        d   j                  t$        d   |      }|r|j'                  d      |z   }|| _        t*        j-                  d
d|       d| _        y)a  Sets regex to use for searching for date in log line.

		Parameters
		----------
		regex : str
			The regex the template will use for searching for a date.
		wordBegin : bool
			Defines whether the regex should be modified to search at beginning of a
			word, by adding special boundary r'(?=^|\b|\W)' to start of regex.
			Can be disabled with specifying of ** at front of regex.
			Default True.
		wordEnd : bool
			Defines whether the regex should be modified to search at end of a word,
			by adding special boundary r'(?=\b|\W|$)' to end of regex.
			Can be disabled with specifying of ** at end of regex.
			Default True.

		Raises
		------
		re.error
			If regular expression fails to compile
		r   r   )countr   startz(?=^|\b|\W)z^(?:\W{0,2})?z	{^LN-BEG}z(?=\b|\W|$)r   z  constructed regex %sN)stripRE_GLOBALFLAGSsearchsubRE_NO_WRD_BOUND_BEGRE_NO_WRD_BOUND_END
RE_GROUPEDRE_GROUPr   r   
WORD_BEGIN
LINE_BEGINr   
startswithWORD_ENDRE_LINE_BOUND_BEGLINE_ENDRE_LINE_BOUND_ENDRE_DEL_WRD_BOUNDSr   r   logSyslogr   )r    regex	wordBeginwordEndgf
boundBeginboundEnds          r   setRegexzDateTemplate.setRegexV   s   6 ++-%U#"b%q15B!4!;!;E!BB*>077>>(			5	!A;??8A;.5$*::I,@((lF]F]]:7U"Eu$E99,tyy(TY::&&&:N5
**|..
.4E4L4LU4S::(((:
**|,,
,2C2J2J52Q::&&&:
A

"
"#4Q#7
?%88A;5$+**Q(%0$,r   z!Regex used to search for date.
		)docc                     | j                   s&	 t        j                  | j                        | _         yy# t        $ r2}t
        j                  d| j                  | j                         |d}~ww xY w)z Compile regex by first usage.
		z Compile %r failed, expression %rN)r   recompiler:   	Exceptionr8   errorr   )r    es     r   _compileRegexzDateTemplate._compileRegex   sY     
::djj)DL 
  
LL3TYY

K
Gs   $4 	A/-A**A/c                     | j                   s| j                          t        j                  dd| j                          | j                   j
                  |g| }|r| xj                  dz  c_        |S )z1Check if regex for date matches on a log line.
		r   z   search %sr   )r   rH   r8   r9   r:   r*   r   )r    lineargs	dateMatchs       r   	matchDatezDateTemplate.matchDate   s\     
**Q

+!dll!!$..)99>9	r   Nc                     t        d      )aQ  Abstract method, which should return the date for a log line

		This should return the date for a log line, typically taking the
		date from the part of the line which matched the templates regex.
		This requires abstraction, therefore just raises exception.

		Parameters
		----------
		line : str
			Log line, of which the date should be extracted from.
		default_tz: if no explicit time zone is present in the line
                            passing this will interpret it as in that time zone.

		Raises
		------
		NotImplementedError
			Abstract method, therefore always returns this.
		zgetDate() is abstract)NotImplementedErrorr    rJ   rL   
default_tzs       r   getDatezDateTemplate.getDate   s    ( 	344r   c                     t         j                  dt        j                  dt        j                  dt        j                  d|                         S )Nr   )RE_EXEANC_BOUND_BEGr+   RE_EXSANC_BOUND_BEGRE_EXLINE_BOUND_BEGRE_EXLINE_NO_BOUNDS)patterns    r   unboundPatternzDateTemplate.unboundPattern   sE    		 	 2B 3 7 7G DE
 r   TTNN)__name__
__module____qualname____doc__r1   r5   r0   r3   r!   r$   r@   propertyr:   rH   rM   r   rR   staticmethodrY    r   r   r   r   9   st    	 >@ 
(H
	
 5 5*  r   r   c                        e Zd ZdZddZddZy)	DateEpochzA date template which searches for Unix timestamps.

	This includes Unix timestamps which appear at start of a line, optionally
	within square braces (nsd), or on SELinux audit log lines.

	Attributes
	----------
	name
	regex
	Nc                 `   t         j                  |        |sdn|| _        || _        d| _        d|r|sdn|| _        d|r8dt
        j                  fd|      z   dz   }d	| _        | j                  |       y |sd
z  }| j                  |d       y dz  }| j                  |dd       y )NEpochr   z\d{10,11}\b(?:\.\d{3,6})?	LongEpochz'\d{10,11}(?:\d{3}(?:\.\d{1,6}|\d{3})?)?(c                     dz  S )Nz(%s)rb   )vepochREs    r   r   z$DateEpoch.__init__.<locals>.<lambda>   s    0@ r   )r	   zf((?:^|(?P<square>(?<=^\[))|(?P<selinux>(?<=\baudit\()))%s)(?:(?(selinux)(?=:\d+\)))|(?(square)(?=\])))Fr;   z*((?P<square>(?<=^\[))?%s)(?(square)(?=\]))r'   T)r;   r<   )r   r!   r   _longFrm_grpIdxRE_EPOCH_PATTERNr+   r@   )r    lineBeginOnlyrX   longFrmr:   rk   s        @r   r!   zDateEpoch.__init__   s    $g'$)$-$,('"){w4977!%%&@'JJSP54<==tw~~5==%=(87B5=='4=8r   c                    |s| j                  |      }|rq|j                  | j                        }| j                  r=t	        |      dk\  r/t	        |      dk\  rd|vrt        |      dz  }nt        |      dz  }t        |      |fS y)ax  Method to return the date for a log line.

		Parameters
		----------
		line : str
			Log line, of which the date should be extracted from.
		default_tz: ignored, Unix timestamps are time zone independent

		Returns
		-------
		(float, str)
			Tuple containing a Unix timestamp, and the string of the date
			which was matched and in turned used to calculated the timestamp.
		      .i@B i  N)rM   r   ro   rn   lenfloat)r    rJ   rL   rQ   rj   s        r   rR   zDateEpoch.getDate   s{     
~~d#9t||$1
mmA"
1v|1	qG	Q	qDQ8Y
 r   )FNFr[   r\   r]   r^   r_   r!   rR   rb   r   r   rd   rd      s    	9* r   rd   c                        e Zd ZdZ e       \  ZZ ej                  e      Zd fd	Z	e
d        Zej                  d        Zd fd	Zd	dZ xZS )
DatePatternRegexzDate template, with regex/pattern

	Parameters
	----------
	pattern : str
		Sets the date templates pattern.

	Attributes
	----------
	name
	regex
	pattern
	c                 d    t         t        |           d | _        | | j                  |fi | y y r#   )superr{   r!   _patternr@   )r    rX   kwargs	__class__s      r   r!   zDatePatternRegex.__init__  s6    $(*$-4==#F# r   c                     | j                   S )aV  The pattern used for regex with strptime "%" time fields.

		This should be a valid regular expression, of which matching string
		will be extracted from the log line. strptime style "%" fields will
		be replaced by appropriate regular expressions, or custom regex
		groups with names as per the strptime fields can also be used
		instead.
		)r~   r   s    r   rX   zDatePatternRegex.pattern%  s     
r   c                 &    | j                  |       y r#   )r@   )r    rX   s     r   rX   zDatePatternRegex.pattern1  s    --r   c                    || _         t        j                  |      rt        j                  d|      }dx}}|r-t        j                  |      rt        j                  d|      }d}	 | j
                  j                  d|      }|| j                  z  | _        |t        z  }t        j                  |      rd|z   }t        t        | 3  |||       y # t        $ r}t        d|d|      d }~ww xY w)Nr   Fr'   z%(\1)sz(?iu)zFailed to set datepattern 'z8' (may be an invalid format or unescaped percent char): )r~   rW   r*   r+   rV   
_patternRE_patternNamer   r   RE_ALPHA_PATTERNr}   r{   r@   rE   	TypeError)r    rX   r;   r<   fmtr:   rG   r   s          r   r@   zDatePatternRegex.setRegex5  s    $-( $$R179w&--g6 $$R179
}			Y	03T&&&49<5g&uE	4)%GD	 }	pwyz{	||}s   (A(C 	C0C++C0c                 h    |s| j                  |      }|rt        |j                         |      |fS y)a  Method to return the date for a log line.

		This uses a custom version of strptime, using the named groups
		from the instances `pattern` property.

		Parameters
		----------
		line : str
			Log line, of which the date should be extracted from.
		default_tz: optionally used to correct timezone

		Returns
		-------
		(float, str)
			Tuple containing a Unix timestamp, and the string of the date
			which was matched and in turned used to calculated the timestamp.
		)rQ   N)rM   r   	groupdictrP   s       r   rR   zDatePatternRegex.getDateL  s=    $ 
~~d#9y224L  r   r#   rZ   r[   )r\   r]   r^   r_   r   r   r   rC   rD   r!   r`   rX   setterr@   rR   __classcell__)r   s   @r   r{   r{     sc     -.\bjj$$ 	 	 
.. }.r   r{   c                        e Zd ZdZddZddZy)
DateTai64nz`A date template which matches TAI64N formate timestamps.

	Attributes
	----------
	name
	regex
	c                 b    t         j                  |        d| _        | j                  d|       y )NTAI64Nz@[0-9a-f]{24}rm   )r   r!   r   r@   )r    r;   s     r   r!   zDateTai64n.__init__n  s'    $)--9-5r   Nc                 v    |s| j                  |      }|r$|j                  d      }|dd }t        |d      |fS y)aq  Method to return the date for a log line.

		Parameters
		----------
		line : str
			Log line, of which the date should be extracted from.
		default_tz: ignored, since TAI is time zone independent

		Returns
		-------
		(float, str)
			Tuple containing a Unix timestamp, and the string of the date
			which was matched and in turned used to calculated the timestamp.
		r   r	      ru   N)rM   r   int)r    rJ   rL   rQ   valueseconds_since_epochs         r   rR   zDateTai64n.getDatet  sJ     
~~d#9??15q"B'
33 r   )Fr[   ry   rb   r   r   r   r   e  s    64r   r   )$
__author____copyright____license__rC   r   abcr   strptimer   r   r   helpersr
   r\   r8   rD   r.   r/   r)   rW   rV   rU   rT   r,   r-   r7   r4   r6   r   
IGNORECASErp   objectr   rd   r{   r   rb   r   r   <module>r      su  . 
2   C C 	8	 RZZ78
RZZHI;X:; bjj-  bjj!12  bjj!=>  bjj!89  bjj!QR  bjj!EF  bjj!MN:=  BJJJK BJJ78 2::23 2::3R]]C T6 Tn:  : zU| Up%4 %4r   