mirror of https://github.com/fail2ban/fail2ban
Fix PEP8 E302 expected 2 blank lines, found X
parent
fbeee8bb28
commit
fdc3172aec
|
@ -35,6 +35,7 @@ else:
|
||||||
from fail2ban.server.actions import ActionBase
|
from fail2ban.server.actions import ActionBase
|
||||||
from fail2ban.version import version as f2bVersion
|
from fail2ban.version import version as f2bVersion
|
||||||
|
|
||||||
|
|
||||||
class BadIPsAction(ActionBase):
|
class BadIPsAction(ActionBase):
|
||||||
"""Fail2Ban action which reports bans to badips.com, and also
|
"""Fail2Ban action which reports bans to badips.com, and also
|
||||||
blacklist bad IPs listed on badips.com by using another action's
|
blacklist bad IPs listed on badips.com by using another action's
|
||||||
|
|
|
@ -68,6 +68,7 @@ Matches for %(ip)s for jail %(jailname)s:
|
||||||
%(ipjailmatches)s
|
%(ipjailmatches)s
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
class SMTPAction(ActionBase):
|
class SMTPAction(ActionBase):
|
||||||
"""Fail2Ban action which sends emails to inform on jail starting,
|
"""Fail2Ban action which sends emails to inform on jail starting,
|
||||||
stopping and bans.
|
stopping and bans.
|
||||||
|
|
|
@ -37,6 +37,7 @@ Below derived from:
|
||||||
logging.NOTICE = logging.INFO + 5
|
logging.NOTICE = logging.INFO + 5
|
||||||
logging.addLevelName(logging.NOTICE, 'NOTICE')
|
logging.addLevelName(logging.NOTICE, 'NOTICE')
|
||||||
|
|
||||||
|
|
||||||
# define a new logger function for notice
|
# define a new logger function for notice
|
||||||
# this is exactly like existing info, critical, debug...etc
|
# this is exactly like existing info, critical, debug...etc
|
||||||
def _Logger_notice(self, msg, *args, **kwargs):
|
def _Logger_notice(self, msg, *args, **kwargs):
|
||||||
|
@ -53,6 +54,7 @@ def _Logger_notice(self, msg, *args, **kwargs):
|
||||||
|
|
||||||
logging.Logger.notice = _Logger_notice
|
logging.Logger.notice = _Logger_notice
|
||||||
|
|
||||||
|
|
||||||
# define a new root level notice function
|
# define a new root level notice function
|
||||||
# this is exactly like existing info, critical, debug...etc
|
# this is exactly like existing info, critical, debug...etc
|
||||||
def _root_notice(msg, *args, **kwargs):
|
def _root_notice(msg, *args, **kwargs):
|
||||||
|
|
|
@ -32,6 +32,7 @@ from ..helpers import getLogger
|
||||||
# Gets the instance of the logger.
|
# Gets the instance of the logger.
|
||||||
logSys = getLogger(__name__)
|
logSys = getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class ActionReader(DefinitionInitConfigReader):
|
class ActionReader(DefinitionInitConfigReader):
|
||||||
|
|
||||||
_configOpts = [
|
_configOpts = [
|
||||||
|
|
|
@ -27,6 +27,7 @@ from ..helpers import getLogger
|
||||||
# Gets the instance of the logger.
|
# Gets the instance of the logger.
|
||||||
logSys = getLogger(__name__)
|
logSys = getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
##
|
##
|
||||||
# Beautify the output of the client.
|
# Beautify the output of the client.
|
||||||
#
|
#
|
||||||
|
|
|
@ -67,6 +67,7 @@ logLevel = 7
|
||||||
|
|
||||||
__all__ = ['SafeConfigParserWithIncludes']
|
__all__ = ['SafeConfigParserWithIncludes']
|
||||||
|
|
||||||
|
|
||||||
class SafeConfigParserWithIncludes(SafeConfigParser):
|
class SafeConfigParserWithIncludes(SafeConfigParser):
|
||||||
"""
|
"""
|
||||||
Class adds functionality to SafeConfigParser to handle included
|
Class adds functionality to SafeConfigParser to handle included
|
||||||
|
|
|
@ -34,6 +34,7 @@ from ..helpers import getLogger
|
||||||
# Gets the instance of the logger.
|
# Gets the instance of the logger.
|
||||||
logSys = getLogger(__name__)
|
logSys = getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class ConfigReader():
|
class ConfigReader():
|
||||||
"""Generic config reader class.
|
"""Generic config reader class.
|
||||||
|
|
||||||
|
@ -136,6 +137,7 @@ class ConfigReader():
|
||||||
return self._cfg.getOptions(*args, **kwargs)
|
return self._cfg.getOptions(*args, **kwargs)
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
|
|
||||||
class ConfigReaderUnshared(SafeConfigParserWithIncludes):
|
class ConfigReaderUnshared(SafeConfigParserWithIncludes):
|
||||||
"""Unshared config reader (previously ConfigReader).
|
"""Unshared config reader (previously ConfigReader).
|
||||||
|
|
||||||
|
@ -237,6 +239,7 @@ class ConfigReaderUnshared(SafeConfigParserWithIncludes):
|
||||||
values[option[1]] = option[2]
|
values[option[1]] = option[2]
|
||||||
return values
|
return values
|
||||||
|
|
||||||
|
|
||||||
class DefinitionInitConfigReader(ConfigReader):
|
class DefinitionInitConfigReader(ConfigReader):
|
||||||
"""Config reader for files with options grouped in [Definition] and
|
"""Config reader for files with options grouped in [Definition] and
|
||||||
[Init] sections.
|
[Init] sections.
|
||||||
|
|
|
@ -31,6 +31,7 @@ from ..helpers import getLogger
|
||||||
# Gets the instance of the logger.
|
# Gets the instance of the logger.
|
||||||
logSys = getLogger(__name__)
|
logSys = getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class Configurator:
|
class Configurator:
|
||||||
|
|
||||||
def __init__(self, force_enable=False, share_config=None):
|
def __init__(self, force_enable=False, share_config=None):
|
||||||
|
|
|
@ -36,6 +36,7 @@ else:
|
||||||
# python 2.x, string type is equivalent to bytes.
|
# python 2.x, string type is equivalent to bytes.
|
||||||
EMPTY_BYTES = ""
|
EMPTY_BYTES = ""
|
||||||
|
|
||||||
|
|
||||||
class CSocket:
|
class CSocket:
|
||||||
|
|
||||||
if sys.version_info >= (3,):
|
if sys.version_info >= (3,):
|
||||||
|
|
|
@ -30,6 +30,7 @@ from ..helpers import getLogger
|
||||||
# Gets the instance of the logger.
|
# Gets the instance of the logger.
|
||||||
logSys = getLogger(__name__)
|
logSys = getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class Fail2banReader(ConfigReader):
|
class Fail2banReader(ConfigReader):
|
||||||
|
|
||||||
def __init__(self, **kwargs):
|
def __init__(self, **kwargs):
|
||||||
|
|
|
@ -34,6 +34,7 @@ from ..helpers import getLogger
|
||||||
# Gets the instance of the logger.
|
# Gets the instance of the logger.
|
||||||
logSys = getLogger(__name__)
|
logSys = getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class FilterReader(DefinitionInitConfigReader):
|
class FilterReader(DefinitionInitConfigReader):
|
||||||
|
|
||||||
_configOpts = [
|
_configOpts = [
|
||||||
|
|
|
@ -37,6 +37,7 @@ from ..helpers import getLogger
|
||||||
# Gets the instance of the logger.
|
# Gets the instance of the logger.
|
||||||
logSys = getLogger(__name__)
|
logSys = getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class JailReader(ConfigReader):
|
class JailReader(ConfigReader):
|
||||||
|
|
||||||
optionCRE = re.compile("^((?:\w|-|_|\.)+)(?:\[(.*)\])?$")
|
optionCRE = re.compile("^((?:\w|-|_|\.)+)(?:\[(.*)\])?$")
|
||||||
|
|
|
@ -31,6 +31,7 @@ from ..helpers import getLogger
|
||||||
# Gets the instance of the logger.
|
# Gets the instance of the logger.
|
||||||
logSys = getLogger(__name__)
|
logSys = getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class JailsReader(ConfigReader):
|
class JailsReader(ConfigReader):
|
||||||
|
|
||||||
def __init__(self, force_enable=False, **kwargs):
|
def __init__(self, force_enable=False, **kwargs):
|
||||||
|
|
|
@ -23,12 +23,14 @@ __author__ = "Cyril Jaquier, Yaroslav Halchenko"
|
||||||
__copyright__ = "Copyright (c) 2004 Cyril Jaquier, 2011-2012 Yaroslav Halchenko"
|
__copyright__ = "Copyright (c) 2004 Cyril Jaquier, 2011-2012 Yaroslav Halchenko"
|
||||||
__license__ = "GPL"
|
__license__ = "GPL"
|
||||||
|
|
||||||
|
|
||||||
#
|
#
|
||||||
# Jails
|
# Jails
|
||||||
#
|
#
|
||||||
class DuplicateJailException(Exception):
|
class DuplicateJailException(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class UnknownJailException(KeyError):
|
class UnknownJailException(KeyError):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
|
@ -26,11 +26,13 @@ import traceback
|
||||||
import re
|
import re
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
|
|
||||||
def formatExceptionInfo():
|
def formatExceptionInfo():
|
||||||
""" Consistently format exception information """
|
""" Consistently format exception information """
|
||||||
cla, exc = sys.exc_info()[:2]
|
cla, exc = sys.exc_info()[:2]
|
||||||
return (cla.__name__, str(exc))
|
return (cla.__name__, str(exc))
|
||||||
|
|
||||||
|
|
||||||
#
|
#
|
||||||
# Following "traceback" functions are adopted from PyMVPA distributed
|
# Following "traceback" functions are adopted from PyMVPA distributed
|
||||||
# under MIT/Expat and copyright by PyMVPA developers (i.e. me and
|
# under MIT/Expat and copyright by PyMVPA developers (i.e. me and
|
||||||
|
@ -49,6 +51,7 @@ def mbasename(s):
|
||||||
base = os.path.basename(os.path.dirname(s)) + '.' + base
|
base = os.path.basename(os.path.dirname(s)) + '.' + base
|
||||||
return base
|
return base
|
||||||
|
|
||||||
|
|
||||||
class TraceBack(object):
|
class TraceBack(object):
|
||||||
"""Customized traceback to be included in debug messages
|
"""Customized traceback to be included in debug messages
|
||||||
"""
|
"""
|
||||||
|
@ -94,6 +97,7 @@ class TraceBack(object):
|
||||||
|
|
||||||
return sftb
|
return sftb
|
||||||
|
|
||||||
|
|
||||||
class FormatterWithTraceBack(logging.Formatter):
|
class FormatterWithTraceBack(logging.Formatter):
|
||||||
"""Custom formatter which expands %(tb) and %(tbc) with tracebacks
|
"""Custom formatter which expands %(tb) and %(tbc) with tracebacks
|
||||||
|
|
||||||
|
@ -108,6 +112,7 @@ class FormatterWithTraceBack(logging.Formatter):
|
||||||
record.tbc = record.tb = self._tb()
|
record.tbc = record.tb = self._tb()
|
||||||
return logging.Formatter.format(self, record)
|
return logging.Formatter.format(self, record)
|
||||||
|
|
||||||
|
|
||||||
def getLogger(name):
|
def getLogger(name):
|
||||||
"""Get logging.Logger instance with Fail2Ban logger name convention
|
"""Get logging.Logger instance with Fail2Ban logger name convention
|
||||||
"""
|
"""
|
||||||
|
@ -115,6 +120,7 @@ def getLogger(name):
|
||||||
name = "fail2ban.%s" % name.rpartition(".")[-1]
|
name = "fail2ban.%s" % name.rpartition(".")[-1]
|
||||||
return logging.getLogger(name)
|
return logging.getLogger(name)
|
||||||
|
|
||||||
|
|
||||||
def excepthook(exctype, value, traceback):
|
def excepthook(exctype, value, traceback):
|
||||||
"""Except hook used to log unhandled exceptions to Fail2Ban log
|
"""Except hook used to log unhandled exceptions to Fail2Ban log
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -119,6 +119,7 @@ protocol = [
|
||||||
["get <JAIL> action <ACT> <PROPERTY>", "gets the value of <PROPERTY> for the action <ACT> for <JAIL>"],
|
["get <JAIL> action <ACT> <PROPERTY>", "gets the value of <PROPERTY> for the action <ACT> for <JAIL>"],
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
##
|
##
|
||||||
# Prints the protocol in a "man" format. This is used for the
|
# Prints the protocol in a "man" format. This is used for the
|
||||||
# "-h" output of fail2ban-client.
|
# "-h" output of fail2ban-client.
|
||||||
|
@ -143,6 +144,7 @@ def printFormatted():
|
||||||
line = ' ' * (INDENT + MARGIN) + n.strip()
|
line = ' ' * (INDENT + MARGIN) + n.strip()
|
||||||
print line
|
print line
|
||||||
|
|
||||||
|
|
||||||
##
|
##
|
||||||
# Prints the protocol in a "mediawiki" format.
|
# Prints the protocol in a "mediawiki" format.
|
||||||
|
|
||||||
|
@ -159,6 +161,7 @@ def printWiki():
|
||||||
print "| <span style=\"white-space:nowrap;\"><tt>" + m[0] + "</tt></span> || || " + m[1]
|
print "| <span style=\"white-space:nowrap;\"><tt>" + m[0] + "</tt></span> || || " + m[1]
|
||||||
print "|}"
|
print "|}"
|
||||||
|
|
||||||
|
|
||||||
def __printWikiHeader(section, desc):
|
def __printWikiHeader(section, desc):
|
||||||
print
|
print
|
||||||
print "=== " + section + " ==="
|
print "=== " + section + " ==="
|
||||||
|
|
|
@ -55,6 +55,7 @@ _RETCODE_HINTS = {
|
||||||
signame = dict((num, name)
|
signame = dict((num, name)
|
||||||
for name, num in signal.__dict__.iteritems() if name.startswith("SIG"))
|
for name, num in signal.__dict__.iteritems() if name.startswith("SIG"))
|
||||||
|
|
||||||
|
|
||||||
class CallingMap(MutableMapping):
|
class CallingMap(MutableMapping):
|
||||||
"""A Mapping type which returns the result of callable values.
|
"""A Mapping type which returns the result of callable values.
|
||||||
|
|
||||||
|
@ -100,6 +101,7 @@ class CallingMap(MutableMapping):
|
||||||
def copy(self):
|
def copy(self):
|
||||||
return self.__class__(self.data.copy())
|
return self.__class__(self.data.copy())
|
||||||
|
|
||||||
|
|
||||||
class ActionBase(object):
|
class ActionBase(object):
|
||||||
"""An abstract base class for actions in Fail2Ban.
|
"""An abstract base class for actions in Fail2Ban.
|
||||||
|
|
||||||
|
@ -182,6 +184,7 @@ class ActionBase(object):
|
||||||
"""
|
"""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class CommandAction(ActionBase):
|
class CommandAction(ActionBase):
|
||||||
"""A action which executes OS shell commands.
|
"""A action which executes OS shell commands.
|
||||||
|
|
||||||
|
|
|
@ -47,6 +47,7 @@ from ..helpers import getLogger
|
||||||
# Gets the instance of the logger.
|
# Gets the instance of the logger.
|
||||||
logSys = getLogger(__name__)
|
logSys = getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class Actions(JailThread, Mapping):
|
class Actions(JailThread, Mapping):
|
||||||
"""Handles jail actions.
|
"""Handles jail actions.
|
||||||
|
|
||||||
|
|
|
@ -45,6 +45,7 @@ else:
|
||||||
# python 2.x, string type is equivalent to bytes.
|
# python 2.x, string type is equivalent to bytes.
|
||||||
EMPTY_BYTES = ""
|
EMPTY_BYTES = ""
|
||||||
|
|
||||||
|
|
||||||
##
|
##
|
||||||
# Request handler class.
|
# Request handler class.
|
||||||
#
|
#
|
||||||
|
@ -92,6 +93,7 @@ class RequestHandler(asynchat.async_chat):
|
||||||
logSys.error(traceback.format_exc().splitlines())
|
logSys.error(traceback.format_exc().splitlines())
|
||||||
self.close()
|
self.close()
|
||||||
|
|
||||||
|
|
||||||
##
|
##
|
||||||
# Asynchronous server class.
|
# Asynchronous server class.
|
||||||
#
|
#
|
||||||
|
@ -187,6 +189,7 @@ class AsyncServer(asyncore.dispatcher):
|
||||||
flags = fcntl.fcntl(fd, fcntl.F_GETFD)
|
flags = fcntl.fcntl(fd, fcntl.F_GETFD)
|
||||||
fcntl.fcntl(fd, fcntl.F_SETFD, flags|fcntl.FD_CLOEXEC)
|
fcntl.fcntl(fd, fcntl.F_SETFD, flags|fcntl.FD_CLOEXEC)
|
||||||
|
|
||||||
|
|
||||||
##
|
##
|
||||||
# AsyncServerException is used to wrap communication exceptions.
|
# AsyncServerException is used to wrap communication exceptions.
|
||||||
|
|
||||||
|
|
|
@ -33,6 +33,7 @@ from ..helpers import getLogger
|
||||||
# Gets the instance of the logger.
|
# Gets the instance of the logger.
|
||||||
logSys = getLogger(__name__)
|
logSys = getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
##
|
##
|
||||||
# Banning Manager.
|
# Banning Manager.
|
||||||
#
|
#
|
||||||
|
|
|
@ -87,6 +87,7 @@ else:
|
||||||
sqlite3.register_adapter(dict, _json_dumps_safe)
|
sqlite3.register_adapter(dict, _json_dumps_safe)
|
||||||
sqlite3.register_converter("JSON", _json_loads_safe)
|
sqlite3.register_converter("JSON", _json_loads_safe)
|
||||||
|
|
||||||
|
|
||||||
def commitandrollback(f):
|
def commitandrollback(f):
|
||||||
@wraps(f)
|
@wraps(f)
|
||||||
def wrapper(self, *args, **kwargs):
|
def wrapper(self, *args, **kwargs):
|
||||||
|
@ -95,6 +96,7 @@ def commitandrollback(f):
|
||||||
return f(self, self._db.cursor(), *args, **kwargs)
|
return f(self, self._db.cursor(), *args, **kwargs)
|
||||||
return wrapper
|
return wrapper
|
||||||
|
|
||||||
|
|
||||||
class Fail2BanDb(object):
|
class Fail2BanDb(object):
|
||||||
"""Fail2Ban database for storing persistent data.
|
"""Fail2Ban database for storing persistent data.
|
||||||
|
|
||||||
|
|
|
@ -29,6 +29,7 @@ from ..helpers import getLogger
|
||||||
# Gets the instance of the logger.
|
# Gets the instance of the logger.
|
||||||
logSys = getLogger(__name__)
|
logSys = getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class DateDetector(object):
|
class DateDetector(object):
|
||||||
"""Manages one or more date templates to find a date within a log line.
|
"""Manages one or more date templates to find a date within a log line.
|
||||||
|
|
||||||
|
|
|
@ -154,6 +154,7 @@ class DateEpoch(DateTemplate):
|
||||||
return (float(dateMatch.group()), dateMatch)
|
return (float(dateMatch.group()), dateMatch)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
class DatePatternRegex(DateTemplate):
|
class DatePatternRegex(DateTemplate):
|
||||||
"""Date template, with regex/pattern
|
"""Date template, with regex/pattern
|
||||||
|
|
||||||
|
@ -236,6 +237,7 @@ class DatePatternRegex(DateTemplate):
|
||||||
if value is not None)
|
if value is not None)
|
||||||
return reGroupDictStrptime(groupdict), dateMatch
|
return reGroupDictStrptime(groupdict), dateMatch
|
||||||
|
|
||||||
|
|
||||||
class DateTai64n(DateTemplate):
|
class DateTai64n(DateTemplate):
|
||||||
"""A date template which matches TAI64N formate timestamps.
|
"""A date template which matches TAI64N formate timestamps.
|
||||||
|
|
||||||
|
|
|
@ -29,6 +29,7 @@ from ..helpers import getLogger
|
||||||
# Gets the instance of the logger.
|
# Gets the instance of the logger.
|
||||||
logSys = getLogger(__name__)
|
logSys = getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class FailData:
|
class FailData:
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
|
|
@ -34,6 +34,7 @@ from ..helpers import getLogger
|
||||||
# Gets the instance of the logger.
|
# Gets the instance of the logger.
|
||||||
logSys = getLogger(__name__)
|
logSys = getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class FailManager:
|
class FailManager:
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
@ -154,5 +155,6 @@ class FailManager:
|
||||||
finally:
|
finally:
|
||||||
self.__lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
|
|
||||||
class FailManagerEmpty(Exception):
|
class FailManagerEmpty(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
|
@ -25,6 +25,7 @@ import re
|
||||||
import sre_constants
|
import sre_constants
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
|
|
||||||
##
|
##
|
||||||
# Regular expression class.
|
# Regular expression class.
|
||||||
#
|
#
|
||||||
|
@ -184,6 +185,7 @@ class Regex:
|
||||||
else:
|
else:
|
||||||
return ["".join(line) for line in self._matchedTupleLines]
|
return ["".join(line) for line in self._matchedTupleLines]
|
||||||
|
|
||||||
|
|
||||||
##
|
##
|
||||||
# Exception dedicated to the class Regex.
|
# Exception dedicated to the class Regex.
|
||||||
|
|
||||||
|
|
|
@ -48,6 +48,7 @@ logSys = getLogger(__name__)
|
||||||
# that matches a given regular expression. This class is instantiated by
|
# that matches a given regular expression. This class is instantiated by
|
||||||
# a Jail object.
|
# a Jail object.
|
||||||
|
|
||||||
|
|
||||||
class Filter(JailThread):
|
class Filter(JailThread):
|
||||||
|
|
||||||
##
|
##
|
||||||
|
@ -717,6 +718,7 @@ except ImportError: # pragma: no cover
|
||||||
import md5
|
import md5
|
||||||
md5sum = md5.new
|
md5sum = md5.new
|
||||||
|
|
||||||
|
|
||||||
class FileContainer:
|
class FileContainer:
|
||||||
|
|
||||||
def __init__(self, filename, encoding, tail = False):
|
def __init__(self, filename, encoding, tail = False):
|
||||||
|
@ -843,6 +845,7 @@ class JournalFilter(Filter): # pragma: systemd no cover
|
||||||
import socket
|
import socket
|
||||||
import struct
|
import struct
|
||||||
|
|
||||||
|
|
||||||
class DNSUtils:
|
class DNSUtils:
|
||||||
|
|
||||||
IP_CRE = re.compile("^(?:\d{1,3}\.){3}\d{1,3}$")
|
IP_CRE = re.compile("^(?:\d{1,3}\.){3}\d{1,3}$")
|
||||||
|
|
|
@ -36,6 +36,7 @@ from ..helpers import getLogger
|
||||||
# Gets the instance of the logger.
|
# Gets the instance of the logger.
|
||||||
logSys = getLogger(__name__)
|
logSys = getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
##
|
##
|
||||||
# Log reader class.
|
# Log reader class.
|
||||||
#
|
#
|
||||||
|
|
|
@ -35,6 +35,7 @@ from ..helpers import getLogger
|
||||||
# Gets the instance of the logger.
|
# Gets the instance of the logger.
|
||||||
logSys = getLogger(__name__)
|
logSys = getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
##
|
##
|
||||||
# Log reader class.
|
# Log reader class.
|
||||||
#
|
#
|
||||||
|
|
|
@ -51,6 +51,7 @@ except Exception, e:
|
||||||
# Gets the instance of the logger.
|
# Gets the instance of the logger.
|
||||||
logSys = getLogger(__name__)
|
logSys = getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
##
|
##
|
||||||
# Log reader class.
|
# Log reader class.
|
||||||
#
|
#
|
||||||
|
|
|
@ -38,6 +38,7 @@ from ..helpers import getLogger
|
||||||
# Gets the instance of the logger.
|
# Gets the instance of the logger.
|
||||||
logSys = getLogger(__name__)
|
logSys = getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
##
|
##
|
||||||
# Journal reader class.
|
# Journal reader class.
|
||||||
#
|
#
|
||||||
|
|
|
@ -32,6 +32,7 @@ from ..helpers import getLogger
|
||||||
# Gets the instance of the logger.
|
# Gets the instance of the logger.
|
||||||
logSys = getLogger(__name__)
|
logSys = getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class Jail:
|
class Jail:
|
||||||
"""Fail2Ban jail, which manages a filter and associated actions.
|
"""Fail2Ban jail, which manages a filter and associated actions.
|
||||||
|
|
||||||
|
|
|
@ -30,6 +30,7 @@ from abc import abstractmethod
|
||||||
|
|
||||||
from ..helpers import excepthook
|
from ..helpers import excepthook
|
||||||
|
|
||||||
|
|
||||||
class JailThread(Thread):
|
class JailThread(Thread):
|
||||||
"""Abstract class for threading elements in Fail2Ban.
|
"""Abstract class for threading elements in Fail2Ban.
|
||||||
|
|
||||||
|
|
|
@ -24,6 +24,7 @@ __license__ = "GPL"
|
||||||
import datetime
|
import datetime
|
||||||
import time
|
import time
|
||||||
|
|
||||||
|
|
||||||
##
|
##
|
||||||
# MyTime class.
|
# MyTime class.
|
||||||
#
|
#
|
||||||
|
|
|
@ -48,6 +48,7 @@ except ImportError:
|
||||||
# Dont print error here, as database may not even be used
|
# Dont print error here, as database may not even be used
|
||||||
Fail2BanDb = None
|
Fail2BanDb = None
|
||||||
|
|
||||||
|
|
||||||
class Server:
|
class Server:
|
||||||
|
|
||||||
def __init__(self, daemon = False):
|
def __init__(self, daemon = False):
|
||||||
|
|
|
@ -28,6 +28,7 @@ locale_time = LocaleTime()
|
||||||
timeRE = TimeRE()
|
timeRE = TimeRE()
|
||||||
timeRE['z'] = r"(?P<z>Z|[+-]\d{2}(?::?[0-5]\d)?)"
|
timeRE['z'] = r"(?P<z>Z|[+-]\d{2}(?::?[0-5]\d)?)"
|
||||||
|
|
||||||
|
|
||||||
def reGroupDictStrptime(found_dict):
|
def reGroupDictStrptime(found_dict):
|
||||||
"""Return time from dictionary of strptime fields
|
"""Return time from dictionary of strptime fields
|
||||||
|
|
||||||
|
|
|
@ -29,6 +29,7 @@ from ..helpers import getLogger
|
||||||
# Gets the instance of the logger.
|
# Gets the instance of the logger.
|
||||||
logSys = getLogger(__name__)
|
logSys = getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class Ticket:
|
class Ticket:
|
||||||
|
|
||||||
def __init__(self, ip, time, matches=None):
|
def __init__(self, ip, time, matches=None):
|
||||||
|
|
|
@ -33,6 +33,7 @@ from .. import version
|
||||||
# Gets the instance of the logger.
|
# Gets the instance of the logger.
|
||||||
logSys = getLogger(__name__)
|
logSys = getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class Transmitter:
|
class Transmitter:
|
||||||
|
|
||||||
##
|
##
|
||||||
|
|
|
@ -32,6 +32,7 @@ from ..dummyjail import DummyJail
|
||||||
|
|
||||||
from ..utils import CONFIG_DIR
|
from ..utils import CONFIG_DIR
|
||||||
|
|
||||||
|
|
||||||
class TestSMTPServer(smtpd.SMTPServer):
|
class TestSMTPServer(smtpd.SMTPServer):
|
||||||
|
|
||||||
def process_message(self, peer, mailfrom, rcpttos, data):
|
def process_message(self, peer, mailfrom, rcpttos, data):
|
||||||
|
@ -40,6 +41,7 @@ class TestSMTPServer(smtpd.SMTPServer):
|
||||||
self.rcpttos = rcpttos
|
self.rcpttos = rcpttos
|
||||||
self.data = data
|
self.data = data
|
||||||
|
|
||||||
|
|
||||||
class SMTPActionTest(unittest.TestCase):
|
class SMTPActionTest(unittest.TestCase):
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
|
|
|
@ -35,6 +35,7 @@ from .utils import LogCaptureTestCase
|
||||||
|
|
||||||
TEST_FILES_DIR = os.path.join(os.path.dirname(__file__), "files")
|
TEST_FILES_DIR = os.path.join(os.path.dirname(__file__), "files")
|
||||||
|
|
||||||
|
|
||||||
class ExecuteActions(LogCaptureTestCase):
|
class ExecuteActions(LogCaptureTestCase):
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
|
|
|
@ -30,6 +30,7 @@ from ..server.action import CommandAction, CallingMap
|
||||||
|
|
||||||
from .utils import LogCaptureTestCase
|
from .utils import LogCaptureTestCase
|
||||||
|
|
||||||
|
|
||||||
class CommandActionTest(LogCaptureTestCase):
|
class CommandActionTest(LogCaptureTestCase):
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
|
|
|
@ -29,6 +29,7 @@ import unittest
|
||||||
from ..server.banmanager import BanManager
|
from ..server.banmanager import BanManager
|
||||||
from ..server.ticket import BanTicket
|
from ..server.ticket import BanTicket
|
||||||
|
|
||||||
|
|
||||||
class AddFailure(unittest.TestCase):
|
class AddFailure(unittest.TestCase):
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
"""Call before every test case."""
|
"""Call before every test case."""
|
||||||
|
|
|
@ -45,6 +45,7 @@ STOCK = os.path.exists(os.path.join('config','fail2ban.conf'))
|
||||||
|
|
||||||
IMPERFECT_CONFIG = os.path.join(os.path.dirname(__file__), 'config')
|
IMPERFECT_CONFIG = os.path.join(os.path.dirname(__file__), 'config')
|
||||||
|
|
||||||
|
|
||||||
class ConfigReaderTest(unittest.TestCase):
|
class ConfigReaderTest(unittest.TestCase):
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
|
@ -156,6 +157,7 @@ c = d ;in line comment
|
||||||
self.assertEqual(self.c.get('DEFAULT', 'b'), 'a')
|
self.assertEqual(self.c.get('DEFAULT', 'b'), 'a')
|
||||||
self.assertEqual(self.c.get('DEFAULT', 'c'), 'd')
|
self.assertEqual(self.c.get('DEFAULT', 'c'), 'd')
|
||||||
|
|
||||||
|
|
||||||
class JailReaderTest(LogCaptureTestCase):
|
class JailReaderTest(LogCaptureTestCase):
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
|
@ -355,6 +357,7 @@ class FilterReaderTest(unittest.TestCase):
|
||||||
except Exception, e: # pragma: no cover - failed if reachable
|
except Exception, e: # pragma: no cover - failed if reachable
|
||||||
self.fail('unexpected options after readexplicit: %s' % (e))
|
self.fail('unexpected options after readexplicit: %s' % (e))
|
||||||
|
|
||||||
|
|
||||||
class JailsReaderTestCache(LogCaptureTestCase):
|
class JailsReaderTestCache(LogCaptureTestCase):
|
||||||
|
|
||||||
def _readWholeConf(self, basedir, force_enable=False, share_config=None):
|
def _readWholeConf(self, basedir, force_enable=False, share_config=None):
|
||||||
|
|
|
@ -42,6 +42,7 @@ from .utils import LogCaptureTestCase
|
||||||
|
|
||||||
TEST_FILES_DIR = os.path.join(os.path.dirname(__file__), "files")
|
TEST_FILES_DIR = os.path.join(os.path.dirname(__file__), "files")
|
||||||
|
|
||||||
|
|
||||||
class DatabaseTest(LogCaptureTestCase):
|
class DatabaseTest(LogCaptureTestCase):
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
|
|
|
@ -32,6 +32,7 @@ from ..server.datedetector import DateDetector
|
||||||
from ..server.datetemplate import DateTemplate
|
from ..server.datetemplate import DateTemplate
|
||||||
from .utils import setUpMyTime, tearDownMyTime
|
from .utils import setUpMyTime, tearDownMyTime
|
||||||
|
|
||||||
|
|
||||||
class DateDetectorTest(unittest.TestCase):
|
class DateDetectorTest(unittest.TestCase):
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
|
|
|
@ -26,6 +26,7 @@ from threading import Lock
|
||||||
|
|
||||||
from ..server.actions import Actions
|
from ..server.actions import Actions
|
||||||
|
|
||||||
|
|
||||||
class DummyJail(object):
|
class DummyJail(object):
|
||||||
"""A simple 'jail' to suck in all the tickets generated by Filter's
|
"""A simple 'jail' to suck in all the tickets generated by Filter's
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -29,6 +29,7 @@ import unittest
|
||||||
from ..server.failmanager import FailManager, FailManagerEmpty
|
from ..server.failmanager import FailManager, FailManagerEmpty
|
||||||
from ..server.ticket import FailTicket
|
from ..server.ticket import FailTicket
|
||||||
|
|
||||||
|
|
||||||
class AddFailure(unittest.TestCase):
|
class AddFailure(unittest.TestCase):
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
|
|
||||||
from fail2ban.server.action import ActionBase
|
from fail2ban.server.action import ActionBase
|
||||||
|
|
||||||
|
|
||||||
class TestAction(ActionBase):
|
class TestAction(ActionBase):
|
||||||
|
|
||||||
def __init__(self, jail, name, opt1, opt2=None):
|
def __init__(self, jail, name, opt1, opt2=None):
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
|
|
||||||
from fail2ban.server.action import ActionBase
|
from fail2ban.server.action import ActionBase
|
||||||
|
|
||||||
|
|
||||||
class TestAction(ActionBase):
|
class TestAction(ActionBase):
|
||||||
|
|
||||||
def ban(self, aInfo):
|
def ban(self, aInfo):
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
|
|
||||||
from fail2ban.server.action import ActionBase
|
from fail2ban.server.action import ActionBase
|
||||||
|
|
||||||
|
|
||||||
class TestAction(ActionBase):
|
class TestAction(ActionBase):
|
||||||
|
|
||||||
def __init__(self, jail, name):
|
def __init__(self, jail, name):
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
|
|
||||||
from fail2ban.server.action import ActionBase
|
from fail2ban.server.action import ActionBase
|
||||||
|
|
||||||
|
|
||||||
class TestAction(ActionBase):
|
class TestAction(ActionBase):
|
||||||
|
|
||||||
def ban(self, aInfo):
|
def ban(self, aInfo):
|
||||||
|
|
|
@ -1,5 +1,6 @@
|
||||||
|
|
||||||
from fail2ban.server.action import ActionBase
|
from fail2ban.server.action import ActionBase
|
||||||
|
|
||||||
|
|
||||||
class TestAction(ActionBase):
|
class TestAction(ActionBase):
|
||||||
pass
|
pass
|
||||||
|
|
|
@ -10,6 +10,7 @@ except ImportError: # pragma: no cover
|
||||||
import md5
|
import md5
|
||||||
md5sum = md5.new
|
md5sum = md5.new
|
||||||
|
|
||||||
|
|
||||||
def auth(v):
|
def auth(v):
|
||||||
|
|
||||||
ha1 = md5sum(username + ':' + realm + ':' + password).hexdigest()
|
ha1 = md5sum(username + ':' + realm + ':' + password).hexdigest()
|
||||||
|
@ -44,6 +45,7 @@ def auth(v):
|
||||||
s = requests.Session()
|
s = requests.Session()
|
||||||
return s.send(p)
|
return s.send(p)
|
||||||
|
|
||||||
|
|
||||||
def preauth():
|
def preauth():
|
||||||
r = requests.get(host + url)
|
r = requests.get(host + url)
|
||||||
print(r)
|
print(r)
|
||||||
|
|
|
@ -46,6 +46,7 @@ from .dummyjail import DummyJail
|
||||||
|
|
||||||
TEST_FILES_DIR = os.path.join(os.path.dirname(__file__), "files")
|
TEST_FILES_DIR = os.path.join(os.path.dirname(__file__), "files")
|
||||||
|
|
||||||
|
|
||||||
# yoh: per Steven Hiscocks's insight while troubleshooting
|
# yoh: per Steven Hiscocks's insight while troubleshooting
|
||||||
# https://github.com/fail2ban/fail2ban/issues/103#issuecomment-15542836
|
# https://github.com/fail2ban/fail2ban/issues/103#issuecomment-15542836
|
||||||
# adding a sufficiently large buffer might help to guarantee that
|
# adding a sufficiently large buffer might help to guarantee that
|
||||||
|
@ -63,6 +64,7 @@ def open(*args):
|
||||||
else:
|
else:
|
||||||
return fopen(*args)
|
return fopen(*args)
|
||||||
|
|
||||||
|
|
||||||
def _killfile(f, name):
|
def _killfile(f, name):
|
||||||
try:
|
try:
|
||||||
f.close()
|
f.close()
|
||||||
|
@ -98,6 +100,7 @@ def _assert_equal_entries(utest, found, output, count=None):
|
||||||
srepr = repr
|
srepr = repr
|
||||||
utest.assertEqual(srepr(found[3]), srepr(output[3]))
|
utest.assertEqual(srepr(found[3]), srepr(output[3]))
|
||||||
|
|
||||||
|
|
||||||
def _ticket_tuple(ticket):
|
def _ticket_tuple(ticket):
|
||||||
"""Create a tuple for easy comparison from fail ticket
|
"""Create a tuple for easy comparison from fail ticket
|
||||||
"""
|
"""
|
||||||
|
@ -107,6 +110,7 @@ def _ticket_tuple(ticket):
|
||||||
matches = ticket.getMatches()
|
matches = ticket.getMatches()
|
||||||
return (ip, attempts, date, matches)
|
return (ip, attempts, date, matches)
|
||||||
|
|
||||||
|
|
||||||
def _assert_correct_last_attempt(utest, filter_, output, count=None):
|
def _assert_correct_last_attempt(utest, filter_, output, count=None):
|
||||||
"""Additional helper to wrap most common test case
|
"""Additional helper to wrap most common test case
|
||||||
|
|
||||||
|
@ -120,6 +124,7 @@ def _assert_correct_last_attempt(utest, filter_, output, count=None):
|
||||||
|
|
||||||
_assert_equal_entries(utest, found, output, count)
|
_assert_equal_entries(utest, found, output, count)
|
||||||
|
|
||||||
|
|
||||||
def _copy_lines_between_files(in_, fout, n=None, skip=0, mode='a', terminal_line=""):
|
def _copy_lines_between_files(in_, fout, n=None, skip=0, mode='a', terminal_line=""):
|
||||||
"""Copy lines from one file to another (which might be already open)
|
"""Copy lines from one file to another (which might be already open)
|
||||||
|
|
||||||
|
@ -156,6 +161,7 @@ def _copy_lines_between_files(in_, fout, n=None, skip=0, mode='a', terminal_line
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
return fout
|
return fout
|
||||||
|
|
||||||
|
|
||||||
def _copy_lines_to_journal(in_, fields={},n=None, skip=0, terminal_line=""): # pragma: systemd no cover
|
def _copy_lines_to_journal(in_, fields={},n=None, skip=0, terminal_line=""): # pragma: systemd no cover
|
||||||
"""Copy lines from one file to systemd journal
|
"""Copy lines from one file to systemd journal
|
||||||
|
|
||||||
|
@ -184,6 +190,7 @@ def _copy_lines_to_journal(in_, fields={},n=None, skip=0, terminal_line=""): # p
|
||||||
# Opened earlier, therefore must close it
|
# Opened earlier, therefore must close it
|
||||||
fin.close()
|
fin.close()
|
||||||
|
|
||||||
|
|
||||||
#
|
#
|
||||||
# Actual tests
|
# Actual tests
|
||||||
#
|
#
|
||||||
|
@ -209,6 +216,7 @@ class BasicFilter(unittest.TestCase):
|
||||||
("^%Y-%m-%d-%H%M%S.%f %z",
|
("^%Y-%m-%d-%H%M%S.%f %z",
|
||||||
"^Year-Month-Day-24hourMinuteSecond.Microseconds Zone offset"))
|
"^Year-Month-Day-24hourMinuteSecond.Microseconds Zone offset"))
|
||||||
|
|
||||||
|
|
||||||
class IgnoreIP(LogCaptureTestCase):
|
class IgnoreIP(LogCaptureTestCase):
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
|
@ -276,6 +284,7 @@ class IgnoreIP(LogCaptureTestCase):
|
||||||
self.filter.logIgnoreIp("example.com", False, ignore_source="NOT_LOGGED")
|
self.filter.logIgnoreIp("example.com", False, ignore_source="NOT_LOGGED")
|
||||||
self.assertFalse(self._is_logged("[%s] Ignore %s by %s" % (self.jail.name, "example.com", "NOT_LOGGED")))
|
self.assertFalse(self._is_logged("[%s] Ignore %s by %s" % (self.jail.name, "example.com", "NOT_LOGGED")))
|
||||||
|
|
||||||
|
|
||||||
class IgnoreIPDNS(IgnoreIP):
|
class IgnoreIPDNS(IgnoreIP):
|
||||||
|
|
||||||
def testIgnoreIPDNSOK(self):
|
def testIgnoreIPDNSOK(self):
|
||||||
|
@ -289,6 +298,7 @@ class IgnoreIPDNS(IgnoreIP):
|
||||||
self.assertFalse(self.filter.inIgnoreIPList("128.178.50.11"))
|
self.assertFalse(self.filter.inIgnoreIPList("128.178.50.11"))
|
||||||
self.assertFalse(self.filter.inIgnoreIPList("128.178.50.13"))
|
self.assertFalse(self.filter.inIgnoreIPList("128.178.50.13"))
|
||||||
|
|
||||||
|
|
||||||
class LogFile(LogCaptureTestCase):
|
class LogFile(LogCaptureTestCase):
|
||||||
|
|
||||||
MISSING = 'testcases/missingLogFile'
|
MISSING = 'testcases/missingLogFile'
|
||||||
|
@ -303,6 +313,7 @@ class LogFile(LogCaptureTestCase):
|
||||||
self.filter = FilterPoll(None)
|
self.filter = FilterPoll(None)
|
||||||
self.assertRaises(IOError, self.filter.addLogPath, LogFile.MISSING)
|
self.assertRaises(IOError, self.filter.addLogPath, LogFile.MISSING)
|
||||||
|
|
||||||
|
|
||||||
class LogFileFilterPoll(unittest.TestCase):
|
class LogFileFilterPoll(unittest.TestCase):
|
||||||
|
|
||||||
FILENAME = os.path.join(TEST_FILES_DIR, "testcase01.log")
|
FILENAME = os.path.join(TEST_FILES_DIR, "testcase01.log")
|
||||||
|
@ -675,6 +686,7 @@ def get_monitor_failures_testcase(Filter_):
|
||||||
% (Filter_.__name__, testclass_name) # 'tempfile')
|
% (Filter_.__name__, testclass_name) # 'tempfile')
|
||||||
return MonitorFailures
|
return MonitorFailures
|
||||||
|
|
||||||
|
|
||||||
def get_monitor_failures_journal_testcase(Filter_): # pragma: systemd no cover
|
def get_monitor_failures_journal_testcase(Filter_): # pragma: systemd no cover
|
||||||
"""Generator of TestCase's for journal based filters/backends
|
"""Generator of TestCase's for journal based filters/backends
|
||||||
"""
|
"""
|
||||||
|
@ -798,6 +810,7 @@ def get_monitor_failures_journal_testcase(Filter_): # pragma: systemd no cover
|
||||||
|
|
||||||
return MonitorJournalFailures
|
return MonitorJournalFailures
|
||||||
|
|
||||||
|
|
||||||
class GetFailures(unittest.TestCase):
|
class GetFailures(unittest.TestCase):
|
||||||
|
|
||||||
FILENAME_01 = os.path.join(TEST_FILES_DIR, "testcase01.log")
|
FILENAME_01 = os.path.join(TEST_FILES_DIR, "testcase01.log")
|
||||||
|
@ -987,6 +1000,7 @@ class GetFailures(unittest.TestCase):
|
||||||
break
|
break
|
||||||
self.assertEqual(sorted(foundList), sorted(output))
|
self.assertEqual(sorted(foundList), sorted(output))
|
||||||
|
|
||||||
|
|
||||||
class DNSUtilsTests(unittest.TestCase):
|
class DNSUtilsTests(unittest.TestCase):
|
||||||
|
|
||||||
def testUseDns(self):
|
def testUseDns(self):
|
||||||
|
@ -1034,6 +1048,7 @@ class DNSUtilsTests(unittest.TestCase):
|
||||||
res = DNSUtils.bin2addr(167772160L)
|
res = DNSUtils.bin2addr(167772160L)
|
||||||
self.assertEqual(res, '10.0.0.0')
|
self.assertEqual(res, '10.0.0.0')
|
||||||
|
|
||||||
|
|
||||||
class JailTests(unittest.TestCase):
|
class JailTests(unittest.TestCase):
|
||||||
|
|
||||||
def testSetBackend_gh83(self):
|
def testSetBackend_gh83(self):
|
||||||
|
|
|
@ -55,6 +55,7 @@ class HelpersTest(unittest.TestCase):
|
||||||
# might be fragile due to ' vs "
|
# might be fragile due to ' vs "
|
||||||
self.assertEqual(args, "('Very bad', None)")
|
self.assertEqual(args, "('Very bad', None)")
|
||||||
|
|
||||||
|
|
||||||
class SetupTest(unittest.TestCase):
|
class SetupTest(unittest.TestCase):
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
|
@ -116,6 +117,7 @@ class SetupTest(unittest.TestCase):
|
||||||
os.system("%s %s clean --all >/dev/null 2>&1"
|
os.system("%s %s clean --all >/dev/null 2>&1"
|
||||||
% (sys.executable, self.setup))
|
% (sys.executable, self.setup))
|
||||||
|
|
||||||
|
|
||||||
class TestsUtilsTest(unittest.TestCase):
|
class TestsUtilsTest(unittest.TestCase):
|
||||||
|
|
||||||
def testmbasename(self):
|
def testmbasename(self):
|
||||||
|
@ -176,6 +178,7 @@ class TestsUtilsTest(unittest.TestCase):
|
||||||
|
|
||||||
iso8601 = DatePatternRegex("%Y-%m-%d[T ]%H:%M:%S(?:\.%f)?%z")
|
iso8601 = DatePatternRegex("%Y-%m-%d[T ]%H:%M:%S(?:\.%f)?%z")
|
||||||
|
|
||||||
|
|
||||||
class CustomDateFormatsTest(unittest.TestCase):
|
class CustomDateFormatsTest(unittest.TestCase):
|
||||||
|
|
||||||
def testIso8601(self):
|
def testIso8601(self):
|
||||||
|
|
|
@ -37,6 +37,7 @@ from .utils import setUpMyTime, tearDownMyTime, CONFIG_DIR
|
||||||
|
|
||||||
TEST_FILES_DIR = os.path.join(os.path.dirname(__file__), "files")
|
TEST_FILES_DIR = os.path.join(os.path.dirname(__file__), "files")
|
||||||
|
|
||||||
|
|
||||||
class FilterSamplesRegex(unittest.TestCase):
|
class FilterSamplesRegex(unittest.TestCase):
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
|
@ -58,6 +59,7 @@ class FilterSamplesRegex(unittest.TestCase):
|
||||||
>= 10,
|
>= 10,
|
||||||
"Expected more FilterSampleRegexs tests")
|
"Expected more FilterSampleRegexs tests")
|
||||||
|
|
||||||
|
|
||||||
def testSampleRegexsFactory(name):
|
def testSampleRegexsFactory(name):
|
||||||
def testFilter(self):
|
def testFilter(self):
|
||||||
|
|
||||||
|
|
|
@ -47,6 +47,7 @@ except ImportError: # pragma: no cover
|
||||||
|
|
||||||
TEST_FILES_DIR = os.path.join(os.path.dirname(__file__), "files")
|
TEST_FILES_DIR = os.path.join(os.path.dirname(__file__), "files")
|
||||||
|
|
||||||
|
|
||||||
class TestServer(Server):
|
class TestServer(Server):
|
||||||
def setLogLevel(self, *args, **kwargs):
|
def setLogLevel(self, *args, **kwargs):
|
||||||
pass
|
pass
|
||||||
|
@ -54,6 +55,7 @@ class TestServer(Server):
|
||||||
def setLogTarget(self, *args, **kwargs):
|
def setLogTarget(self, *args, **kwargs):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class TransmitterBase(unittest.TestCase):
|
class TransmitterBase(unittest.TestCase):
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
|
@ -146,6 +148,7 @@ class TransmitterBase(unittest.TestCase):
|
||||||
self.transm.proceed(["get", jail, cmd]),
|
self.transm.proceed(["get", jail, cmd]),
|
||||||
(0, outValues[n+1:]))
|
(0, outValues[n+1:]))
|
||||||
|
|
||||||
|
|
||||||
class Transmitter(TransmitterBase):
|
class Transmitter(TransmitterBase):
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
|
@ -760,6 +763,7 @@ class Transmitter(TransmitterBase):
|
||||||
["set", jailName, "deljournalmatch", value])
|
["set", jailName, "deljournalmatch", value])
|
||||||
self.assertTrue(isinstance(result[1], ValueError))
|
self.assertTrue(isinstance(result[1], ValueError))
|
||||||
|
|
||||||
|
|
||||||
class TransmitterLogging(TransmitterBase):
|
class TransmitterLogging(TransmitterBase):
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
|
@ -884,6 +888,7 @@ class JailTests(unittest.TestCase):
|
||||||
jail = Jail(longname)
|
jail = Jail(longname)
|
||||||
self.assertEqual(jail.name, longname)
|
self.assertEqual(jail.name, longname)
|
||||||
|
|
||||||
|
|
||||||
class RegexTests(unittest.TestCase):
|
class RegexTests(unittest.TestCase):
|
||||||
|
|
||||||
def testInit(self):
|
def testInit(self):
|
||||||
|
@ -908,10 +913,12 @@ class RegexTests(unittest.TestCase):
|
||||||
self.assertTrue(fr.hasMatched())
|
self.assertTrue(fr.hasMatched())
|
||||||
self.assertRaises(RegexException, fr.getHost)
|
self.assertRaises(RegexException, fr.getHost)
|
||||||
|
|
||||||
|
|
||||||
class _BadThread(JailThread):
|
class _BadThread(JailThread):
|
||||||
def run(self):
|
def run(self):
|
||||||
raise RuntimeError('run bad thread exception')
|
raise RuntimeError('run bad thread exception')
|
||||||
|
|
||||||
|
|
||||||
class LoggingTests(LogCaptureTestCase):
|
class LoggingTests(LogCaptureTestCase):
|
||||||
|
|
||||||
def testGetF2BLogger(self):
|
def testGetF2BLogger(self):
|
||||||
|
|
|
@ -33,6 +33,7 @@ import unittest
|
||||||
from ..server.asyncserver import AsyncServer, AsyncServerException
|
from ..server.asyncserver import AsyncServer, AsyncServerException
|
||||||
from ..client.csocket import CSocket
|
from ..client.csocket import CSocket
|
||||||
|
|
||||||
|
|
||||||
class Socket(unittest.TestCase):
|
class Socket(unittest.TestCase):
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
|
|
|
@ -44,12 +44,15 @@ if not CONFIG_DIR:
|
||||||
else:
|
else:
|
||||||
CONFIG_DIR = '/etc/fail2ban'
|
CONFIG_DIR = '/etc/fail2ban'
|
||||||
|
|
||||||
|
|
||||||
def mtimesleep():
|
def mtimesleep():
|
||||||
# no sleep now should be necessary since polling tracks now not only
|
# no sleep now should be necessary since polling tracks now not only
|
||||||
# mtime but also ino and size
|
# mtime but also ino and size
|
||||||
pass
|
pass
|
||||||
|
|
||||||
old_TZ = os.environ.get('TZ', None)
|
old_TZ = os.environ.get('TZ', None)
|
||||||
|
|
||||||
|
|
||||||
def setUpMyTime():
|
def setUpMyTime():
|
||||||
# Set the time to a fixed, known value
|
# Set the time to a fixed, known value
|
||||||
# Sun Aug 14 12:00:00 CEST 2005
|
# Sun Aug 14 12:00:00 CEST 2005
|
||||||
|
@ -58,6 +61,7 @@ def setUpMyTime():
|
||||||
time.tzset()
|
time.tzset()
|
||||||
MyTime.setTime(1124013600)
|
MyTime.setTime(1124013600)
|
||||||
|
|
||||||
|
|
||||||
def tearDownMyTime():
|
def tearDownMyTime():
|
||||||
os.environ.pop('TZ')
|
os.environ.pop('TZ')
|
||||||
if old_TZ:
|
if old_TZ:
|
||||||
|
@ -65,6 +69,7 @@ def tearDownMyTime():
|
||||||
time.tzset()
|
time.tzset()
|
||||||
MyTime.myTime = None
|
MyTime.myTime = None
|
||||||
|
|
||||||
|
|
||||||
def gatherTests(regexps=None, no_network=False):
|
def gatherTests(regexps=None, no_network=False):
|
||||||
# Import all the test cases here instead of a module level to
|
# Import all the test cases here instead of a module level to
|
||||||
# avoid circular imports
|
# avoid circular imports
|
||||||
|
@ -197,6 +202,7 @@ def gatherTests(regexps=None, no_network=False):
|
||||||
|
|
||||||
return tests
|
return tests
|
||||||
|
|
||||||
|
|
||||||
class LogCaptureTestCase(unittest.TestCase):
|
class LogCaptureTestCase(unittest.TestCase):
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
|
|
Loading…
Reference in New Issue