Skip to content

Commit

Permalink
fix cut out of match for pattern with {EPOCH} (similar to other dat…
Browse files Browse the repository at this point in the history
…epatterns group capturing whole regex only added if no groups specified at all);

allows to specify more precise anchored patterns, for example `datepattern = ^type=\S+ msg=audit\(({EPOCH})` for selinux-filters
  • Loading branch information
sebres committed Nov 14, 2022
1 parent eba33d6 commit a58fcb8
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
6 changes: 4 additions & 2 deletions fail2ban/server/datetemplate.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,8 +227,10 @@ def __init__(self, lineBeginOnly=False, pattern=None, longFrm=False):
self.name = "LongEpoch" if not pattern else pattern
epochRE = r"\d{10,11}(?:\d{3}(?:\.\d{1,6}|\d{3})?)?"
if pattern:
# pattern should capture/cut out the whole match:
regex = "(" + RE_EPOCH_PATTERN.sub(lambda v: "(%s)" % epochRE, pattern) + ")"
# pattern should find the whole pattern, but cut out grouped match (or whole match if no groups specified):
regex = RE_EPOCH_PATTERN.sub(lambda v: "(%s)" % epochRE, pattern)
if not RE_GROUPED.search(pattern):
regex = "(" + regex + ")"
self._grpIdx = 2
self.setRegex(regex)
elif not lineBeginOnly:
Expand Down
9 changes: 9 additions & 0 deletions fail2ban/tests/datedetectortestcase.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,15 @@ def testGetEpochPattern(self):
log = log % dateLong
datelog = self.datedetector.getTime(log)
self.assertFalse(datelog)

def testGetEpochPatternCut(self):
self.__datedetector = DateDetector()
self.__datedetector.appendTemplate(r'^type=\S+ msg=audit\(({EPOCH})')
# correct epoch time and cut out epoch string only (captured group only, not the whole match):
line = "type=USER_AUTH msg=audit(1106513999.000:987)"
datelog = self.datedetector.getTime(line)
timeMatch = datelog[1]
self.assertEqual([int(datelog[0]), line[timeMatch.start(1):timeMatch.end(1)]], [1106513999, '1106513999.000'])

def testGetTime(self):
log = "Jan 23 21:59:59 [sshd] error: PAM: Authentication failure"
Expand Down

0 comments on commit a58fcb8

Please sign in to comment.