Skip to content

Instantly share code, notes, and snippets.

@kwirk
Last active December 17, 2015 00:00
Show Gist options
  • Save kwirk/5518039 to your computer and use it in GitHub Desktop.
Save kwirk/5518039 to your computer and use it in GitHub Desktop.
fail2ban/fail2ban overlap date patterns
diff --git a/fail2ban/server/datetemplate.py b/fail2ban/server/datetemplate.py
index d37fa45..1be34d8 100644
--- a/fail2ban/server/datetemplate.py
+++ b/fail2ban/server/datetemplate.py
@@ -63,6 +63,9 @@ class DateTemplate:
def getHits(self):
return self.__hits
+ def resetHits(self):
+ self.__hits = 0
+
def matchDate(self, line):
dateMatch = self.__cRegex.search(line)
if not dateMatch == None:
diff --git a/fail2ban/tests/utils.py b/fail2ban/tests/utils.py
index 95646d6..02a50ba 100644
--- a/fail2ban/tests/utils.py
+++ b/fail2ban/tests/utils.py
@@ -22,10 +22,11 @@ __author__ = "Yaroslav Halchenko"
__copyright__ = "Copyright (c) 2013 Yaroslav Halchenko"
__license__ = "GPL"
-import logging, os, re, traceback, time, unittest
+import logging, os, re, traceback, time, unittest, calendar, datetime
from os.path import basename, dirname
from fail2ban.server.mytime import MyTime
+from fail2ban.server.datedetector import DateDetector
logSys = logging.getLogger(__name__)
@@ -205,3 +206,43 @@ def gatherTests(regexps=None, no_network=False):
tests.addTest(unittest.makeSuite(servertestcase.TransmitterLogging))
return tests
+
+def testTemplateOverlap():
+ datedetector = DateDetector()
+ datedetector.addDefaultTemplate()
+ patterns = [template.getPattern()
+ for template in datedetector.getTemplates()
+ if hasattr(template, "getPattern")]
+
+ year = 2008 # Leap year, 08 for %y can be confused with both %d and %m
+ def iterDates(year):
+ for month in xrange(1, 13):
+ for day in xrange(2, calendar.monthrange(year, month)[1]+1, 9):
+ for hour in xrange(0, 24, 6):
+ for minute in xrange(0, 60, 15):
+ for second in xrange(0, 60, 15): # Far enough?
+ yield datetime.datetime(
+ year, month, day, hour, minute, second)
+
+ overlapedTemplates = set()
+ for date in iterDates(year):
+ for pattern in patterns:
+ datestr = date.strftime(pattern)
+ datestrs = set([
+ datestr,
+ re.sub(r"(\s)0", r"\1 ", datestr),
+ re.sub(r"(\s)0", r"\1", datestr)])
+ for template in datedetector.getTemplates():
+ template.resetHits()
+ for datestr in datestrs:
+ template.matchDate(datestr) # or getDate?
+
+ matchedTemplates = [template
+ for template in datedetector.getTemplates()
+ if template.getHits() > 0]
+ assert matchedTemplates != [] # Should match at least one
+ if len(matchedTemplates) > 1:
+ overlapedTemplates.add((pattern, tuple(sorted(template.getName()
+ for template in matchedTemplates))))
+
+ return overlapedTemplates
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment