
    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#dS )"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                 R    |                                                      dd          S )Nz** )groupreplace)ms    >/usr/lib/python3/dist-packages/fail2ban/server/datetemplate.py<lambda>r   /   s    qwwyy00r::     z(^(?:\(\?\w+\))?(?:\^|\((?:\?:)?\^(?!\|))z(?<![\\\|])(?:\$\)?)$z(?<!\%)\%[aAbBpc]z(?<!\\)\{L?EPOCH\}c                       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dS )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                 h    d| _         d| _        d| _        d| _        d| _        d| _        d | _        d S )Nr   g      ?r   )nameweightflagshitstime_regex_cRegexselfs    r   __init__zDateTemplate.__init__J   s7    $)$+$*$)$)$+$,,,r   c                     | j         S N)r   r   s    r   getRegexzDateTemplate.getRegexS   s
    	r   Tc                    |                                 }t                              |          }|rt                              d|d          }|ot                              |           }|ot
                              |           }t                              |          s,t          d                             t          d         |          }d| _        |rf| xj        |dk    rt          j
        nt          j        z  c_        |dk    rd|z   }n.d|z   }| j                            d          sd| j        z   | _        |r| xj        t          j        z  c_        |d	z  }| j        t          j        z  s4t                              |          r| xj        t          j        z  c_        | j        t          j        z  s4t"                              |          r| xj        t          j        z  c_        t$          d                             t$          d         |          }|r|                    d          |z   }|| _        t*                              d
d|           d| _        dS )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##" 2b%q115B!4!;!;E!B!BB*>077>>>(			5	!	! /A;??8A;..5$* )::I,@,@((lF]]::7U"EEu$E9,, )ty(TY ::&&::N5
*|.
. )4E4L4LU4S4S )::((::
*|,
, '2C2J2J52Q2Q '::&&::
A

"
"#4Q#7
?
?% 88A;;5$+**Q(%000$,,,r   z!Regex used to search for date.
		)docc                     | j         s[	 t          j        | j                  | _         dS # t          $ r-}t
                              d| j        | j                   |d}~ww xY wdS )z Compile regex by first usage.
		z Compile %r failed, expression %rN)r   recompiler:   	Exceptionr8   errorr   )r    es     r   _compileRegexzDateTemplate._compileRegex   ss     
 :dj))DLLL
   
LL3TY
KKK
G	 s   ) 
A (AA c                     | j         s|                                  t                              dd| j                    | j         j        |g|R  }|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   sq     
 **Q
+++!dl!$....) 99>99	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44r   c                     t                               dt                              dt                              dt                              d|                                         S )Nr   )RE_EXEANC_BOUND_BEGr+   RE_EXSANC_BOUND_BEGRE_EXLINE_BOUND_BEGRE_EXLINE_NO_BOUNDS)patterns    r   unboundPatternzDateTemplate.unboundPattern   sU    		 	 2B 3 7 7G D DE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   s        	 	     > > > >@ 
(H
 
 
	 	 	
 
 
 5 5 5 .5*   ,  r   r   c                   "    e Zd ZdZddZddZdS )	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
	FNc                    t                               |            |sdn|| _        || _        d| _        d|r|sdn|| _        d|rBdt
                              fd|          z   dz   }d	| _        |                     |           d S |sd
z  }|                     |d           d S dz  }|                     |dd           d S )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    $1gg'$)$-$,(' 8")6{{w4977 
9!%%&@&@&@&@'JJJSP54<== 9tw~~5==%=(((((87B5=='4=88888r   c                 :   |s|                      |          }|r|                    | j                  }| j        rOt	          |          dk    r<t	          |          dk    rd|vrt          |          dz  }nt          |          dz  }t          |          |fS dS )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
m A"
1vv||1	qG	QQ	qDQ88Y
   r   )FNFr[   r\   r]   r^   r_   r!   rR   rb   r   r   rd   rd      sF        	 	9 9 9 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
	Nc                     t          t          |                                            d | _        | | j        |fi | d S d S r#   )superr{   r!   _patternr@   )r    rX   kwargs	__class__s      r   r!   zDatePatternRegex.__init__  sU    $((***$-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                 0    |                      |           d S r#   )r@   )r    rX   s     r   rX   zDatePatternRegex.pattern1  s    --r   Tc                 D   || _         t                              |          rt                              d|          }dx}}|r7t                              |          rt                              d|          }d}	 | j                            d|          }|| j        z  | _        |t          z  }t                              |          rd|z   }t          t          |                               |||           d S # 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  s8   $-((  $$R1179w &--g66  $$R1179
}			Y	0	03T&&49<5g&& uE	4  ))%GDDDDD	 } } }	pwpwpwyzyz{	|	||}s   <A=C; ;
DDDc                     |s|                      |          }|r%t          |                                |          |fS dS )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  sX    $ 
 $~~d##9 y2244LL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{     s          -,..\bj$$$ $ $ $ $ $ 	 	 (	 
.  .} } } } } }.       r   r{   c                   "    e Zd ZdZddZddZdS )
DateTai64nz`A date template which matches TAI64N formate timestamps.

	Attributes
	----------
	name
	regex
	Fc                 v    t                               |            d| _        |                     d|           d S )NTAI64Nz@[0-9a-f]{24}rm   )r   r!   r   r@   )r    r;   s     r   r!   zDateTai64n.__init__n  s9    $)--9-55555r   Nc                     |s|                      |          }|r1|                    d          }|dd         }t          |d          |fS dS )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  sd     
 $~~d##9 4??15qt"B''
334 4r   )Fr[   ry   rb   r   r   r   r   e  sF         6 6 6 64 4 4 4 4 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      s[  . 
2        C C C C C C C C C C      	8		 RZ788
RZHII;X:;; bj--  bj!122  bj!=>>  bj!899  bj!QRR  bj!EFF  bj!MNN::=  BJJKK BJ788 2:233 2:3R]CC T T T T T6 T T Tn:  :  :  :  :  :  :  : zU U U U U| U U Up%4 %4 %4 %4 %4 %4 %4 %4 %4 %4r   