2007-01-29 20:31:04 +00:00
|
|
|
#!/usr/bin/python
|
2012-12-24 16:05:44 +00:00
|
|
|
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*-
|
|
|
|
# vi: set ft=python sts=4 ts=4 sw=4 noet :
|
|
|
|
#
|
2006-09-06 18:25:11 +00:00
|
|
|
# This file is part of Fail2Ban.
|
|
|
|
#
|
|
|
|
# Fail2Ban is free software; you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation; either version 2 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# Fail2Ban is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with Fail2Ban; if not, write to the Free Software
|
2011-11-21 12:20:20 +00:00
|
|
|
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
2013-06-14 02:19:10 +00:00
|
|
|
"""
|
|
|
|
Fail2Ban reads log file that contains password failure report
|
|
|
|
and bans the corresponding IP addresses using firewall rules.
|
|
|
|
|
|
|
|
This tools can test regular expressions for "fail2ban".
|
|
|
|
|
|
|
|
"""
|
2006-09-06 18:25:11 +00:00
|
|
|
|
2014-05-16 01:17:43 +00:00
|
|
|
__author__ = "Fail2Ban Developers"
|
|
|
|
__copyright__ = "Copyright (c) 2004-2008 Cyril Jaquier, 2012-2014 Yaroslav Halchenko"
|
2006-09-06 18:25:11 +00:00
|
|
|
__license__ = "GPL"
|
|
|
|
|
2014-05-16 01:17:43 +00:00
|
|
|
import getopt, sys, time, logging, os, locale, shlex, time, urllib
|
2013-06-14 03:01:35 +00:00
|
|
|
from optparse import OptionParser, Option
|
|
|
|
|
2007-01-21 22:21:13 +00:00
|
|
|
from ConfigParser import NoOptionError, NoSectionError, MissingSectionHeaderError
|
2013-03-31 17:18:21 +00:00
|
|
|
|
2013-05-09 23:15:07 +00:00
|
|
|
try:
|
|
|
|
from systemd import journal
|
2013-06-29 12:00:40 +00:00
|
|
|
from fail2ban.server.filtersystemd import FilterSystemd
|
|
|
|
except ImportError:
|
2013-05-09 23:15:07 +00:00
|
|
|
journal = None
|
|
|
|
|
2013-03-31 17:18:21 +00:00
|
|
|
from fail2ban.version import version
|
2014-01-01 23:03:14 +00:00
|
|
|
from fail2ban.client.filterreader import FilterReader
|
2013-03-31 17:18:21 +00:00
|
|
|
from fail2ban.server.filter import Filter
|
|
|
|
from fail2ban.server.failregex import RegexException
|
2006-09-06 18:25:11 +00:00
|
|
|
|
2014-06-10 19:36:19 +00:00
|
|
|
from fail2ban.helpers import FormatterWithTraceBack, getLogger
|
2006-10-31 22:25:26 +00:00
|
|
|
# Gets the instance of the logger.
|
2014-06-10 19:36:19 +00:00
|
|
|
logSys = getLogger("fail2ban")
|
2006-10-31 22:25:26 +00:00
|
|
|
|
2013-09-22 03:20:17 +00:00
|
|
|
def debuggexURL(sample, regex):
|
2013-09-22 05:49:30 +00:00
|
|
|
q = urllib.urlencode({ 're': regex.replace('<HOST>', '(?&.ipv4)'),
|
2013-09-22 03:20:17 +00:00
|
|
|
'str': sample,
|
|
|
|
'flavor': 'python' })
|
|
|
|
return 'http://www.debuggex.com/?' + q
|
|
|
|
|
2013-06-14 02:19:10 +00:00
|
|
|
def shortstr(s, l=53):
|
|
|
|
"""Return shortened string
|
|
|
|
"""
|
|
|
|
if len(s) > l:
|
|
|
|
return s[:l-3] + '...'
|
|
|
|
return s
|
|
|
|
|
|
|
|
def pprint_list(l, header=None):
|
|
|
|
if not len(l):
|
|
|
|
return
|
|
|
|
if header:
|
|
|
|
s = "|- %s\n" % header
|
|
|
|
else:
|
|
|
|
s = ''
|
|
|
|
print s + "| " + "\n| ".join(l) + '\n`-'
|
|
|
|
|
2013-07-27 11:35:42 +00:00
|
|
|
def file_lines_gen(hdlr):
|
|
|
|
for line in hdlr:
|
|
|
|
try:
|
|
|
|
line = line.decode(fail2banRegex.encoding, 'strict')
|
|
|
|
except UnicodeDecodeError:
|
|
|
|
if sys.version_info >= (3,): # Python 3 must be decoded
|
|
|
|
line = line.decode(fail2banRegex.encoding, 'ignore')
|
|
|
|
yield line
|
|
|
|
|
|
|
|
def journal_lines_gen(myjournal):
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
entry = myjournal.get_next()
|
|
|
|
except OSError:
|
|
|
|
continue
|
|
|
|
if not entry:
|
|
|
|
break
|
|
|
|
yield FilterSystemd.formatJournalEntry(entry)
|
|
|
|
|
2013-06-14 02:19:10 +00:00
|
|
|
def get_opt_parser():
|
|
|
|
# use module docstring for help output
|
|
|
|
p = OptionParser(
|
|
|
|
usage="%s [OPTIONS] <LOG> <REGEX> [IGNOREREGEX]\n" % sys.argv[0] + __doc__
|
|
|
|
+ """
|
|
|
|
LOG:
|
|
|
|
string a string representing a log line
|
|
|
|
filename path to a log file (/var/log/auth.log)
|
2013-12-14 17:21:56 +00:00
|
|
|
"systemd-journal" search systemd journal (systemd-python required)
|
2013-06-14 02:19:10 +00:00
|
|
|
|
|
|
|
REGEX:
|
|
|
|
string a string representing a 'failregex'
|
|
|
|
filename path to a filter file (filter.d/sshd.conf)
|
|
|
|
|
|
|
|
IGNOREREGEX:
|
|
|
|
string a string representing an 'ignoreregex'
|
|
|
|
filename path to a filter file (filter.d/sshd.conf)
|
2013-10-30 23:26:49 +00:00
|
|
|
|
|
|
|
Copyright (c) 2004-2008 Cyril Jaquier, 2008- Fail2Ban Contributors
|
|
|
|
Copyright of modifications held by their respective authors.
|
|
|
|
Licensed under the GNU General Public License v2 (GPL).
|
|
|
|
|
|
|
|
Written by Cyril Jaquier <cyril.jaquier@fail2ban.org>.
|
|
|
|
Many contributions by Yaroslav O. Halchenko and Steven Hiscocks.
|
|
|
|
|
|
|
|
Report bugs to https://github.com/fail2ban/fail2ban/issues
|
2013-06-14 02:19:10 +00:00
|
|
|
""",
|
|
|
|
version="%prog " + version)
|
|
|
|
|
|
|
|
p.add_options([
|
2013-07-17 20:07:09 +00:00
|
|
|
Option("-d", "--datepattern",
|
|
|
|
help="set custom pattern used to match date/times"),
|
2013-06-18 23:46:25 +00:00
|
|
|
Option("-e", "--encoding",
|
|
|
|
help="File encoding. Default: system locale"),
|
|
|
|
Option("-L", "--maxlines", type=int, default=0,
|
|
|
|
help="maxlines for multi-line regex"),
|
2013-06-29 12:00:40 +00:00
|
|
|
Option("-m", "--journalmatch",
|
|
|
|
help="journalctl style matches overriding filter file. "
|
|
|
|
"\"systemd-journal\" only"),
|
2013-06-14 02:19:10 +00:00
|
|
|
Option('-l', "--log-level", type="choice",
|
|
|
|
dest="log_level",
|
2014-02-20 23:01:40 +00:00
|
|
|
choices=('heavydebug', 'debug', 'info', 'notice', 'warning', 'error', 'critical'),
|
2013-06-14 02:19:10 +00:00
|
|
|
default=None,
|
|
|
|
help="Log level for the Fail2Ban logger to use"),
|
|
|
|
Option("-v", "--verbose", action='store_true',
|
|
|
|
help="Be verbose in output"),
|
2013-09-23 22:35:12 +00:00
|
|
|
Option("-D", "--debuggex", action='store_true',
|
2013-09-22 03:20:17 +00:00
|
|
|
help="Produce debuggex.com urls for debugging there"),
|
2014-03-14 05:57:55 +00:00
|
|
|
Option("--print-no-missed", action='store_true',
|
|
|
|
help="Do not print any missed lines"),
|
|
|
|
Option("--print-no-ignored", action='store_true',
|
|
|
|
help="Do not print any ignored lines"),
|
2014-03-17 04:50:04 +00:00
|
|
|
Option("--print-all-matched", action='store_true',
|
|
|
|
help="Print all matched lines"),
|
2013-06-14 02:19:10 +00:00
|
|
|
Option("--print-all-missed", action='store_true',
|
2014-03-14 05:57:55 +00:00
|
|
|
help="Print all missed lines, no matter how many"),
|
2013-06-14 02:19:10 +00:00
|
|
|
Option("--print-all-ignored", action='store_true',
|
2014-03-14 05:57:55 +00:00
|
|
|
help="Print all ignored lines, no matter how many"),
|
2013-06-14 03:01:35 +00:00
|
|
|
Option("-t", "--log-traceback", action='store_true',
|
|
|
|
help="Enrich log-messages with compressed tracebacks"),
|
|
|
|
Option("--full-traceback", action='store_true',
|
|
|
|
help="Either to make the tracebacks full, not compressed (as by default)"),
|
2013-06-14 02:19:10 +00:00
|
|
|
])
|
|
|
|
|
|
|
|
return p
|
|
|
|
|
|
|
|
|
|
|
|
class RegexStat(object):
|
2007-01-21 22:21:13 +00:00
|
|
|
|
|
|
|
def __init__(self, failregex):
|
2013-06-14 02:19:10 +00:00
|
|
|
self._stats = 0
|
|
|
|
self._failregex = failregex
|
|
|
|
self._ipList = list()
|
2012-12-24 16:05:44 +00:00
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return "%s(%r) %d failed: %s" \
|
2013-06-14 02:19:10 +00:00
|
|
|
% (self.__class__, self._failregex, self._stats, self._ipList)
|
2013-03-29 16:31:50 +00:00
|
|
|
|
2007-01-21 22:21:13 +00:00
|
|
|
def inc(self):
|
2013-06-14 02:19:10 +00:00
|
|
|
self._stats += 1
|
2013-03-29 16:31:50 +00:00
|
|
|
|
2007-01-21 22:21:13 +00:00
|
|
|
def getStats(self):
|
2013-06-14 02:19:10 +00:00
|
|
|
return self._stats
|
2007-01-21 22:21:13 +00:00
|
|
|
|
|
|
|
def getFailRegex(self):
|
2013-06-14 02:19:10 +00:00
|
|
|
return self._failregex
|
2013-03-29 16:31:50 +00:00
|
|
|
|
2007-01-21 22:21:13 +00:00
|
|
|
def appendIP(self, value):
|
2013-07-15 21:16:40 +00:00
|
|
|
self._ipList.append(value)
|
2013-03-29 16:31:50 +00:00
|
|
|
|
2007-01-21 22:21:13 +00:00
|
|
|
def getIPList(self):
|
2013-06-14 02:19:10 +00:00
|
|
|
return self._ipList
|
2007-01-21 22:21:13 +00:00
|
|
|
|
2013-03-29 16:31:50 +00:00
|
|
|
|
2013-06-14 02:19:10 +00:00
|
|
|
class LineStats(object):
|
|
|
|
"""Just a convenience container for stats
|
|
|
|
"""
|
|
|
|
def __init__(self):
|
|
|
|
self.tested = self.matched = 0
|
2014-03-17 04:50:04 +00:00
|
|
|
self.matched_lines = []
|
2014-03-14 03:18:08 +00:00
|
|
|
self.missed = 0
|
2013-06-14 02:19:10 +00:00
|
|
|
self.missed_lines = []
|
2013-09-22 03:20:17 +00:00
|
|
|
self.missed_lines_timeextracted = []
|
2014-03-14 03:18:08 +00:00
|
|
|
self.ignored = 0
|
2013-06-14 02:19:10 +00:00
|
|
|
self.ignored_lines = []
|
2013-09-22 03:20:17 +00:00
|
|
|
self.ignored_lines_timeextracted = []
|
2007-09-12 21:38:51 +00:00
|
|
|
|
2013-06-14 02:19:10 +00:00
|
|
|
def __str__(self):
|
|
|
|
return "%(tested)d lines, %(ignored)d ignored, %(matched)d matched, %(missed)d missed" % self
|
2007-09-12 21:38:51 +00:00
|
|
|
|
2013-06-14 02:19:10 +00:00
|
|
|
# just for convenient str
|
|
|
|
def __getitem__(self, key):
|
|
|
|
return getattr(self, key)
|
2007-01-21 22:21:13 +00:00
|
|
|
|
|
|
|
|
2013-06-14 02:19:10 +00:00
|
|
|
class Fail2banRegex(object):
|
|
|
|
|
|
|
|
def __init__(self, opts):
|
|
|
|
self._verbose = opts.verbose
|
2013-09-22 03:20:17 +00:00
|
|
|
self._debuggex = opts.debuggex
|
2014-03-14 06:10:00 +00:00
|
|
|
self._maxlines = 20
|
2014-03-14 05:57:55 +00:00
|
|
|
self._print_no_missed = opts.print_no_missed
|
|
|
|
self._print_no_ignored = opts.print_no_ignored
|
2014-03-17 04:50:04 +00:00
|
|
|
self._print_all_matched = opts.print_all_matched
|
2013-06-14 02:19:10 +00:00
|
|
|
self._print_all_missed = opts.print_all_missed
|
|
|
|
self._print_all_ignored = opts.print_all_ignored
|
2013-06-18 23:46:25 +00:00
|
|
|
self._maxlines_set = False # so we allow to override maxlines in cmdline
|
2013-09-22 17:14:04 +00:00
|
|
|
self._datepattern_set = False
|
2013-06-29 12:00:40 +00:00
|
|
|
self._journalmatch = None
|
|
|
|
|
2013-06-14 02:19:10 +00:00
|
|
|
self._filter = Filter(None)
|
|
|
|
self._ignoreregex = list()
|
|
|
|
self._failregex = list()
|
2014-05-16 01:17:43 +00:00
|
|
|
self._time_elapsed = None
|
2013-06-14 02:19:10 +00:00
|
|
|
self._line_stats = LineStats()
|
|
|
|
|
2013-06-18 23:46:25 +00:00
|
|
|
if opts.maxlines:
|
|
|
|
self.setMaxLines(opts.maxlines)
|
2013-06-29 12:00:40 +00:00
|
|
|
if opts.journalmatch is not None:
|
|
|
|
self.setJournalMatch(opts.journalmatch.split())
|
2013-09-22 17:14:04 +00:00
|
|
|
if opts.datepattern:
|
|
|
|
self.setDatePattern(opts.datepattern)
|
|
|
|
if opts.encoding:
|
|
|
|
self.encoding = opts.encoding
|
|
|
|
else:
|
|
|
|
self.encoding = locale.getpreferredencoding()
|
|
|
|
|
|
|
|
|
2007-07-10 19:54:01 +00:00
|
|
|
|
2013-05-04 16:12:33 +00:00
|
|
|
def setDatePattern(self, pattern):
|
2013-09-22 17:14:04 +00:00
|
|
|
if not self._datepattern_set:
|
|
|
|
self._filter.setDatePattern(pattern)
|
|
|
|
self._datepattern_set = True
|
2013-12-28 18:02:16 +00:00
|
|
|
if pattern is not None:
|
|
|
|
print "Use datepattern : %s" % (
|
|
|
|
self._filter.getDatePattern()[1], )
|
2013-06-18 23:46:25 +00:00
|
|
|
|
|
|
|
def setMaxLines(self, v):
|
|
|
|
if not self._maxlines_set:
|
|
|
|
self._filter.setMaxLines(int(v))
|
|
|
|
self._maxlines_set = True
|
2013-07-05 17:47:08 +00:00
|
|
|
print "Use maxlines : %d" % self._filter.getMaxLines()
|
2013-06-18 23:46:25 +00:00
|
|
|
|
2013-06-29 12:00:40 +00:00
|
|
|
def setJournalMatch(self, v):
|
|
|
|
if self._journalmatch is None:
|
|
|
|
self._journalmatch = v
|
2013-03-29 16:31:50 +00:00
|
|
|
|
2013-06-14 02:19:10 +00:00
|
|
|
def readRegex(self, value, regextype):
|
|
|
|
assert(regextype in ('fail', 'ignore'))
|
|
|
|
regex = regextype + 'regex'
|
2007-01-21 22:21:13 +00:00
|
|
|
if os.path.isfile(value):
|
2014-01-01 23:03:14 +00:00
|
|
|
print "Use %11s file : %s" % (regex, value)
|
|
|
|
reader = FilterReader(value, 'fail2ban-regex-jail', {})
|
|
|
|
reader.setBaseDir(None)
|
2013-04-22 04:01:30 +00:00
|
|
|
|
2014-01-01 23:03:14 +00:00
|
|
|
if reader.readexplicit():
|
|
|
|
reader.getOptions(None)
|
|
|
|
readercommands = reader.convert()
|
|
|
|
regex_values = [
|
|
|
|
RegexStat(m[3])
|
|
|
|
for m in filter(
|
|
|
|
lambda x: x[0] == 'set' and x[2] == "add%sregex" % regextype,
|
|
|
|
readercommands)]
|
|
|
|
# Read out and set possible value of maxlines
|
|
|
|
for command in readercommands:
|
|
|
|
if command[2] == "maxlines":
|
|
|
|
maxlines = int(command[3])
|
|
|
|
try:
|
|
|
|
self.setMaxLines(maxlines)
|
|
|
|
except ValueError:
|
|
|
|
print "ERROR: Invalid value for maxlines (%(maxlines)r) " \
|
|
|
|
"read from %(value)s" % locals()
|
|
|
|
return False
|
|
|
|
elif command[2] == 'addjournalmatch':
|
|
|
|
journalmatch = command[3]
|
|
|
|
self.setJournalMatch(shlex.split(journalmatch))
|
2014-01-05 22:55:53 +00:00
|
|
|
elif command[2] == 'datepattern':
|
|
|
|
datepattern = command[3]
|
|
|
|
self.setDatePattern(datepattern)
|
2007-01-29 20:31:04 +00:00
|
|
|
else:
|
2014-01-01 23:03:14 +00:00
|
|
|
print "ERROR: failed to read %s" % value
|
|
|
|
return False
|
2007-01-21 22:21:13 +00:00
|
|
|
else:
|
2013-06-14 02:19:10 +00:00
|
|
|
print "Use %11s line : %s" % (regex, shortstr(value))
|
|
|
|
regex_values = [RegexStat(value)]
|
2013-04-22 04:01:30 +00:00
|
|
|
|
2013-06-14 02:19:10 +00:00
|
|
|
setattr(self, "_" + regex, regex_values)
|
2013-07-15 21:16:40 +00:00
|
|
|
for regex in regex_values:
|
|
|
|
getattr(
|
|
|
|
self._filter,
|
|
|
|
'add%sRegex' % regextype.title())(regex.getFailRegex())
|
2007-01-21 22:21:13 +00:00
|
|
|
return True
|
2013-03-29 16:31:50 +00:00
|
|
|
|
2007-07-10 19:54:01 +00:00
|
|
|
def testIgnoreRegex(self, line):
|
|
|
|
found = False
|
2013-07-15 21:16:40 +00:00
|
|
|
try:
|
2013-12-13 16:38:26 +00:00
|
|
|
ret = self._filter.ignoreLine([(line, "", "")])
|
2013-07-15 21:16:40 +00:00
|
|
|
if ret is not None:
|
|
|
|
found = True
|
|
|
|
regex = self._ignoreregex[ret].inc()
|
|
|
|
except RegexException, e:
|
|
|
|
print e
|
|
|
|
return False
|
2013-06-14 02:19:10 +00:00
|
|
|
return found
|
2013-03-29 16:31:50 +00:00
|
|
|
|
2013-12-28 18:02:16 +00:00
|
|
|
def testRegex(self, line, date=None):
|
2013-07-16 23:08:43 +00:00
|
|
|
orgLineBuffer = self._filter._Filter__lineBuffer
|
|
|
|
fullBuffer = len(orgLineBuffer) >= self._filter.getMaxLines()
|
2013-07-15 21:16:40 +00:00
|
|
|
try:
|
2013-12-28 18:02:16 +00:00
|
|
|
line, ret = self._filter.processLine(line, date, checkAllRegex=True)
|
2013-07-15 21:16:40 +00:00
|
|
|
for match in ret:
|
2013-07-16 19:58:44 +00:00
|
|
|
# Append True/False flag depending if line was matched by
|
|
|
|
# more than one regex
|
2013-07-15 21:16:40 +00:00
|
|
|
match.append(len(ret)>1)
|
|
|
|
regex = self._failregex[match[0]]
|
|
|
|
regex.inc()
|
|
|
|
regex.appendIP(match)
|
|
|
|
except RegexException, e:
|
|
|
|
print e
|
|
|
|
return False
|
|
|
|
except IndexError:
|
2013-09-22 03:20:17 +00:00
|
|
|
print "Sorry, but no <HOST> found in regex"
|
2013-07-15 21:16:40 +00:00
|
|
|
return False
|
2013-07-16 23:08:43 +00:00
|
|
|
for bufLine in orgLineBuffer[int(fullBuffer):]:
|
|
|
|
if bufLine not in self._filter._Filter__lineBuffer:
|
2013-12-04 22:05:17 +00:00
|
|
|
try:
|
|
|
|
self._line_stats.missed_lines.pop(
|
|
|
|
self._line_stats.missed_lines.index("".join(bufLine)))
|
|
|
|
self._line_stats.missed_lines_timeextracted.pop(
|
|
|
|
self._line_stats.missed_lines_timeextracted.index(
|
|
|
|
"".join(bufLine[::2])))
|
|
|
|
except ValueError:
|
|
|
|
pass
|
|
|
|
else:
|
2013-07-16 23:08:43 +00:00
|
|
|
self._line_stats.matched += 1
|
2014-04-27 12:27:11 +00:00
|
|
|
self._line_stats.missed -= 1
|
2013-09-22 03:20:17 +00:00
|
|
|
return line, ret
|
2013-06-14 02:19:10 +00:00
|
|
|
|
|
|
|
def process(self, test_lines):
|
2014-05-16 01:17:43 +00:00
|
|
|
t0 = time.time()
|
2013-07-27 10:34:10 +00:00
|
|
|
for line_no, line in enumerate(test_lines):
|
2013-12-28 18:02:16 +00:00
|
|
|
if isinstance(line, tuple):
|
|
|
|
line_datetimestripped, ret = fail2banRegex.testRegex(
|
|
|
|
line[0], line[1])
|
|
|
|
line = "".join(line[0])
|
|
|
|
else:
|
|
|
|
line = line.rstrip('\r\n')
|
|
|
|
if line.startswith('#') or not line:
|
|
|
|
# skip comment and empty lines
|
|
|
|
continue
|
|
|
|
line_datetimestripped, ret = fail2banRegex.testRegex(line)
|
2013-12-04 22:05:17 +00:00
|
|
|
is_ignored = fail2banRegex.testIgnoreRegex(line_datetimestripped)
|
2013-09-22 03:20:17 +00:00
|
|
|
|
2013-06-14 02:19:10 +00:00
|
|
|
if is_ignored:
|
2014-03-14 03:18:08 +00:00
|
|
|
self._line_stats.ignored += 1
|
2014-03-14 05:57:55 +00:00
|
|
|
if not self._print_no_ignored and (self._print_all_ignored or self._line_stats.ignored <= self._maxlines + 1):
|
2014-03-14 03:18:08 +00:00
|
|
|
self._line_stats.ignored_lines.append(line)
|
|
|
|
self._line_stats.ignored_lines_timeextracted.append(line_datetimestripped)
|
2013-06-14 02:19:10 +00:00
|
|
|
|
2013-09-22 03:20:17 +00:00
|
|
|
if len(ret) > 0:
|
2013-06-14 02:19:10 +00:00
|
|
|
assert(not is_ignored)
|
|
|
|
self._line_stats.matched += 1
|
2014-03-17 04:50:04 +00:00
|
|
|
if self._print_all_matched:
|
|
|
|
self._line_stats.matched_lines.append(line)
|
2013-06-14 02:19:10 +00:00
|
|
|
else:
|
|
|
|
if not is_ignored:
|
2014-03-14 03:18:08 +00:00
|
|
|
self._line_stats.missed += 1
|
2014-03-14 05:57:55 +00:00
|
|
|
if not self._print_no_missed and (self._print_all_missed or self._line_stats.missed <= self._maxlines + 1):
|
2014-03-14 03:18:08 +00:00
|
|
|
self._line_stats.missed_lines.append(line)
|
|
|
|
self._line_stats.missed_lines_timeextracted.append(line_datetimestripped)
|
2013-06-14 02:19:10 +00:00
|
|
|
self._line_stats.tested += 1
|
|
|
|
|
2013-12-28 18:02:16 +00:00
|
|
|
if line_no % 10 == 0 and self._filter.dateDetector is not None:
|
2013-07-27 10:34:10 +00:00
|
|
|
self._filter.dateDetector.sortTemplate()
|
2014-05-16 01:17:43 +00:00
|
|
|
self._time_elapsed = time.time() - t0
|
2013-07-27 10:34:10 +00:00
|
|
|
|
2013-09-22 03:20:17 +00:00
|
|
|
|
|
|
|
|
2013-06-14 02:19:10 +00:00
|
|
|
def printLines(self, ltype):
|
|
|
|
lstats = self._line_stats
|
2014-03-14 05:57:55 +00:00
|
|
|
assert(self._line_stats.missed == lstats.tested - (lstats.matched + lstats.ignored))
|
|
|
|
lines = lstats[ltype]
|
2013-06-14 02:19:10 +00:00
|
|
|
l = lstats[ltype + '_lines']
|
2014-03-14 05:57:55 +00:00
|
|
|
if lines:
|
2013-06-14 02:19:10 +00:00
|
|
|
header = "%s line(s):" % (ltype.capitalize(),)
|
2013-09-22 03:20:17 +00:00
|
|
|
if self._debuggex:
|
2014-03-17 04:50:04 +00:00
|
|
|
if ltype == 'missed' or ltype == 'matched':
|
2013-09-22 03:20:17 +00:00
|
|
|
regexlist = self._failregex
|
|
|
|
else:
|
|
|
|
regexlist = self._ignoreregex
|
|
|
|
l = lstats[ltype + '_lines_timeextracted']
|
2014-03-14 05:57:55 +00:00
|
|
|
if lines < self._maxlines or getattr(self, '_print_all_' + ltype):
|
2013-09-22 03:20:17 +00:00
|
|
|
ans = [[]]
|
|
|
|
for arg in [l, regexlist]:
|
2014-03-16 18:25:16 +00:00
|
|
|
ans = [ x + [y] for x in ans for y in arg ]
|
2013-09-22 03:20:17 +00:00
|
|
|
b = map(lambda a: a[0] + ' | ' + a[1].getFailRegex() + ' | ' + debuggexURL(a[0], a[1].getFailRegex()), ans)
|
|
|
|
pprint_list([x.rstrip() for x in b], header)
|
|
|
|
else:
|
2014-03-14 05:57:55 +00:00
|
|
|
print "%s too many to print. Use --print-all-%s " \
|
2013-09-22 03:20:17 +00:00
|
|
|
"to print all %d lines" % (header, ltype, lines)
|
2014-03-14 05:57:55 +00:00
|
|
|
elif lines < self._maxlines or getattr(self, '_print_all_' + ltype):
|
2013-06-14 02:19:10 +00:00
|
|
|
pprint_list([x.rstrip() for x in l], header)
|
|
|
|
else:
|
2014-03-14 05:57:55 +00:00
|
|
|
print "%s too many to print. Use --print-all-%s " \
|
|
|
|
"to print all %d lines" % (header, ltype, lines)
|
2013-03-29 16:31:50 +00:00
|
|
|
|
2007-01-21 22:21:13 +00:00
|
|
|
def printStats(self):
|
|
|
|
print
|
|
|
|
print "Results"
|
|
|
|
print "======="
|
2012-02-11 03:19:44 +00:00
|
|
|
|
|
|
|
def print_failregexes(title, failregexes):
|
|
|
|
# Print title
|
2012-02-11 03:51:31 +00:00
|
|
|
total, out = 0, []
|
2012-02-11 03:19:44 +00:00
|
|
|
for cnt, failregex in enumerate(failregexes):
|
|
|
|
match = failregex.getStats()
|
|
|
|
total += match
|
2013-06-14 02:19:10 +00:00
|
|
|
if (match or self._verbose):
|
|
|
|
out.append("%2d) [%d] %s" % (cnt+1, match, failregex.getFailRegex()))
|
|
|
|
|
|
|
|
if self._verbose and len(failregex.getIPList()):
|
|
|
|
for ip in failregex.getIPList():
|
2013-07-15 21:16:40 +00:00
|
|
|
timeTuple = time.localtime(ip[2])
|
2013-06-14 02:19:10 +00:00
|
|
|
timeString = time.strftime("%a %b %d %H:%M:%S %Y", timeTuple)
|
2013-07-15 21:16:40 +00:00
|
|
|
out.append(
|
|
|
|
" %s %s%s" % (
|
|
|
|
ip[1],
|
|
|
|
timeString,
|
2013-12-04 23:36:45 +00:00
|
|
|
ip[-1] and " (multiple regex matched)" or ""))
|
2013-06-14 02:19:10 +00:00
|
|
|
|
|
|
|
print "\n%s: %d total" % (title, total)
|
|
|
|
pprint_list(out, " #) [# of hits] regular expression")
|
2012-02-11 03:19:44 +00:00
|
|
|
return total
|
|
|
|
|
2007-07-10 19:54:01 +00:00
|
|
|
# Print title
|
2013-06-14 02:19:10 +00:00
|
|
|
total = print_failregexes("Failregex", self._failregex)
|
|
|
|
_ = print_failregexes("Ignoreregex", self._ignoreregex)
|
2012-02-11 03:51:31 +00:00
|
|
|
|
|
|
|
|
2013-12-28 18:02:16 +00:00
|
|
|
if self._filter.dateDetector is not None:
|
|
|
|
print "\nDate template hits:"
|
|
|
|
out = []
|
2014-01-27 19:59:01 +00:00
|
|
|
for template in self._filter.dateDetector.templates:
|
|
|
|
if self._verbose or template.hits:
|
2013-12-28 18:02:16 +00:00
|
|
|
out.append("[%d] %s" % (
|
2014-01-27 19:59:01 +00:00
|
|
|
template.hits, template.name))
|
2013-12-28 18:02:16 +00:00
|
|
|
pprint_list(out, "[# of hits] date format")
|
2013-03-29 16:31:50 +00:00
|
|
|
|
2014-05-16 01:17:43 +00:00
|
|
|
print "\nLines: %s" % self._line_stats,
|
|
|
|
if self._time_elapsed is not None:
|
|
|
|
print "[processed in %.2f sec]" % self._time_elapsed,
|
|
|
|
print
|
2013-03-29 16:31:50 +00:00
|
|
|
|
2014-03-17 04:50:04 +00:00
|
|
|
if self._print_all_matched:
|
|
|
|
self.printLines('matched')
|
2014-03-14 05:57:55 +00:00
|
|
|
if not self._print_no_ignored:
|
2014-03-14 02:47:28 +00:00
|
|
|
self.printLines('ignored')
|
2014-03-14 05:57:55 +00:00
|
|
|
if not self._print_no_missed:
|
2014-03-14 02:47:28 +00:00
|
|
|
self.printLines('missed')
|
2013-03-29 16:31:50 +00:00
|
|
|
|
2013-06-14 02:19:10 +00:00
|
|
|
return True
|
2007-01-21 22:21:13 +00:00
|
|
|
|
2013-03-29 16:31:50 +00:00
|
|
|
|
2006-09-06 18:25:11 +00:00
|
|
|
if __name__ == "__main__":
|
2013-06-14 02:19:10 +00:00
|
|
|
|
|
|
|
parser = get_opt_parser()
|
|
|
|
(opts, args) = parser.parse_args()
|
2014-03-14 06:10:00 +00:00
|
|
|
if opts.print_no_missed and opts.print_all_missed:
|
|
|
|
sys.stderr.write("ERROR: --print-no-missed and --print-all-missed are mutually exclusive.\n\n")
|
|
|
|
parser.print_help()
|
2014-03-16 18:25:16 +00:00
|
|
|
sys.exit(-1)
|
2014-03-14 06:10:00 +00:00
|
|
|
if opts.print_no_ignored and opts.print_all_ignored:
|
|
|
|
sys.stderr.write("ERROR: --print-no-ignored and --print-all-ignored are mutually exclusive.\n\n")
|
|
|
|
parser.print_help()
|
2014-03-16 18:25:16 +00:00
|
|
|
sys.exit(-1)
|
2013-06-14 02:19:10 +00:00
|
|
|
|
2013-09-22 17:14:04 +00:00
|
|
|
print
|
|
|
|
print "Running tests"
|
|
|
|
print "============="
|
|
|
|
print
|
|
|
|
|
2013-06-14 02:19:10 +00:00
|
|
|
fail2banRegex = Fail2banRegex(opts)
|
2012-02-11 03:51:31 +00:00
|
|
|
|
|
|
|
# We need 2 or 3 parameters
|
|
|
|
if not len(args) in (2, 3):
|
2013-06-14 02:19:10 +00:00
|
|
|
sys.stderr.write("ERROR: provide both <LOG> and <REGEX>.\n\n")
|
|
|
|
parser.print_help()
|
2006-09-06 18:25:11 +00:00
|
|
|
sys.exit(-1)
|
2007-01-21 22:21:13 +00:00
|
|
|
|
2013-06-14 03:01:35 +00:00
|
|
|
# TODO: taken from -testcases -- move common functionality somewhere
|
|
|
|
if opts.log_level is not None: # pragma: no cover
|
|
|
|
# so we had explicit settings
|
|
|
|
logSys.setLevel(getattr(logging, opts.log_level.upper()))
|
|
|
|
else: # pragma: no cover
|
|
|
|
# suppress the logging but it would leave unittests' progress dots
|
2014-02-20 23:01:40 +00:00
|
|
|
# ticking, unless like with '-l critical' which would be silent
|
2013-06-14 03:01:35 +00:00
|
|
|
# unless error occurs
|
2014-02-20 23:01:40 +00:00
|
|
|
logSys.setLevel(getattr(logging, 'CRITICAL'))
|
2007-07-10 19:54:01 +00:00
|
|
|
|
2013-06-14 03:01:35 +00:00
|
|
|
# Add the default logging handler
|
|
|
|
stdout = logging.StreamHandler(sys.stdout)
|
2007-01-29 20:31:04 +00:00
|
|
|
|
2013-06-14 03:01:35 +00:00
|
|
|
fmt = 'D: %(message)s'
|
2012-02-11 03:51:31 +00:00
|
|
|
|
2013-06-14 03:01:35 +00:00
|
|
|
if opts.log_traceback:
|
|
|
|
Formatter = FormatterWithTraceBack
|
|
|
|
fmt = (opts.full_traceback and ' %(tb)s' or ' %(tbc)s') + fmt
|
|
|
|
else:
|
|
|
|
Formatter = logging.Formatter
|
|
|
|
|
|
|
|
# Custom log format for the verbose tests runs
|
2013-06-29 12:56:53 +00:00
|
|
|
if opts.verbose: # pragma: no cover
|
2013-06-14 03:01:35 +00:00
|
|
|
stdout.setFormatter(Formatter(' %(asctime)-15s %(thread)s' + fmt))
|
|
|
|
else: # pragma: no cover
|
|
|
|
# just prefix with the space
|
|
|
|
stdout.setFormatter(Formatter(fmt))
|
|
|
|
logSys.addHandler(stdout)
|
|
|
|
|
2013-06-14 02:19:10 +00:00
|
|
|
cmd_log, cmd_regex = args[:2]
|
2007-01-29 20:31:04 +00:00
|
|
|
|
2013-07-05 17:47:08 +00:00
|
|
|
fail2banRegex.readRegex(cmd_regex, 'fail') or sys.exit(-1)
|
|
|
|
|
2013-06-14 02:19:10 +00:00
|
|
|
if len(args) == 3:
|
|
|
|
fail2banRegex.readRegex(args[2], 'ignore') or sys.exit(-1)
|
2012-02-11 03:51:31 +00:00
|
|
|
|
2013-06-14 02:19:10 +00:00
|
|
|
if os.path.isfile(cmd_log):
|
|
|
|
try:
|
2013-06-18 23:46:25 +00:00
|
|
|
hdlr = open(cmd_log, 'rb')
|
2013-06-14 02:19:10 +00:00
|
|
|
print "Use log file : %s" % cmd_log
|
2013-06-18 23:46:25 +00:00
|
|
|
print "Use encoding : %s" % fail2banRegex.encoding
|
2013-07-27 11:35:42 +00:00
|
|
|
test_lines = file_lines_gen(hdlr)
|
2013-06-14 02:19:10 +00:00
|
|
|
except IOError, e:
|
|
|
|
print e
|
|
|
|
sys.exit(-1)
|
2013-06-29 12:00:40 +00:00
|
|
|
elif cmd_log == "systemd-journal":
|
|
|
|
if not journal:
|
|
|
|
print "Error: systemd library not found. Exiting..."
|
|
|
|
sys.exit(-1)
|
|
|
|
myjournal = journal.Reader(converters={'__CURSOR': lambda x: x})
|
|
|
|
journalmatch = fail2banRegex._journalmatch
|
2013-12-28 18:02:16 +00:00
|
|
|
fail2banRegex.setDatePattern(None)
|
2013-06-29 12:00:40 +00:00
|
|
|
if journalmatch:
|
2013-05-09 23:15:07 +00:00
|
|
|
try:
|
2013-06-29 12:00:40 +00:00
|
|
|
for element in journalmatch:
|
|
|
|
if element == "+":
|
|
|
|
myjournal.add_disjunction()
|
|
|
|
else:
|
|
|
|
myjournal.add_match(element)
|
2013-05-09 23:15:07 +00:00
|
|
|
except ValueError:
|
2013-06-29 12:00:40 +00:00
|
|
|
print "Error: Invalid journalmatch: %s" % shortstr(" ".join(journalmatch))
|
2013-05-09 23:15:07 +00:00
|
|
|
sys.exit(-1)
|
2013-06-29 12:00:40 +00:00
|
|
|
print "Use journal match : %s" % " ".join(journalmatch)
|
2013-07-27 11:35:42 +00:00
|
|
|
test_lines = journal_lines_gen(myjournal)
|
2013-06-14 02:19:10 +00:00
|
|
|
else:
|
|
|
|
print "Use single line : %s" % shortstr(cmd_log)
|
|
|
|
test_lines = [ cmd_log ]
|
|
|
|
print
|
|
|
|
|
|
|
|
fail2banRegex.process(test_lines)
|
2012-02-11 03:51:31 +00:00
|
|
|
|
2013-06-14 02:19:10 +00:00
|
|
|
fail2banRegex.printStats() or sys.exit(-1)
|