mirror of https://github.com/fail2ban/fail2ban
- Made private fields prefixed with "__"
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/trunk@368 a942ae1a-1317-0410-a47c-b1dcaea8d6050.x
parent
dac67d6ea6
commit
126807dea8
|
@ -34,24 +34,24 @@ class ActionReader(ConfigReader):
|
||||||
|
|
||||||
def __init__(self, action, name):
|
def __init__(self, action, name):
|
||||||
ConfigReader.__init__(self)
|
ConfigReader.__init__(self)
|
||||||
self.file = action[0]
|
self.__file = action[0]
|
||||||
self.cInfo = action[1]
|
self.__cInfo = action[1]
|
||||||
self.name = name
|
self.__name = name
|
||||||
|
|
||||||
def setFile(self, file):
|
def setFile(self, file):
|
||||||
self.file = file
|
self.__file = file
|
||||||
|
|
||||||
def getFile(self):
|
def getFile(self):
|
||||||
return self.file
|
return self.__file
|
||||||
|
|
||||||
def setName(self, name):
|
def setName(self, name):
|
||||||
self.name = name
|
self.__name = name
|
||||||
|
|
||||||
def getName(self):
|
def getName(self):
|
||||||
return self.name
|
return self.__name
|
||||||
|
|
||||||
def read(self):
|
def read(self):
|
||||||
return ConfigReader.read(self, "action.d/" + self.file)
|
return ConfigReader.read(self, "action.d/" + self.__file)
|
||||||
|
|
||||||
def getOptions(self, pOpts):
|
def getOptions(self, pOpts):
|
||||||
opts = [["string", "actionstart", ""],
|
opts = [["string", "actionstart", ""],
|
||||||
|
@ -59,32 +59,32 @@ class ActionReader(ConfigReader):
|
||||||
["string", "actioncheck", ""],
|
["string", "actioncheck", ""],
|
||||||
["string", "actionban", ""],
|
["string", "actionban", ""],
|
||||||
["string", "actionunban", ""]]
|
["string", "actionunban", ""]]
|
||||||
self.opts = ConfigReader.getOptions(self, "Definition", opts, pOpts)
|
self.__opts = ConfigReader.getOptions(self, "Definition", opts, pOpts)
|
||||||
|
|
||||||
if self.has_section("Init"):
|
if self.has_section("Init"):
|
||||||
for opt in self.options("Init"):
|
for opt in self.options("Init"):
|
||||||
if not self.cInfo.has_key(opt):
|
if not self.__cInfo.has_key(opt):
|
||||||
self.cInfo[opt] = self.get("Init", opt)
|
self.__cInfo[opt] = self.get("Init", opt)
|
||||||
|
|
||||||
def convert(self):
|
def convert(self):
|
||||||
head = ["set", self.name]
|
head = ["set", self.__name]
|
||||||
stream = list()
|
stream = list()
|
||||||
stream.append(head + ["addaction", self.file])
|
stream.append(head + ["addaction", self.__file])
|
||||||
for opt in self.opts:
|
for opt in self.__opts:
|
||||||
if opt == "actionstart":
|
if opt == "actionstart":
|
||||||
stream.append(head + ["actionstart", self.file, self.opts[opt]])
|
stream.append(head + ["actionstart", self.__file, self.__opts[opt]])
|
||||||
elif opt == "actionstop":
|
elif opt == "actionstop":
|
||||||
stream.append(head + ["actionstop", self.file, self.opts[opt]])
|
stream.append(head + ["actionstop", self.__file, self.__opts[opt]])
|
||||||
elif opt == "actioncheck":
|
elif opt == "actioncheck":
|
||||||
stream.append(head + ["actioncheck", self.file, self.opts[opt]])
|
stream.append(head + ["actioncheck", self.__file, self.__opts[opt]])
|
||||||
elif opt == "actionban":
|
elif opt == "actionban":
|
||||||
stream.append(head + ["actionban", self.file, self.opts[opt]])
|
stream.append(head + ["actionban", self.__file, self.__opts[opt]])
|
||||||
elif opt == "actionunban":
|
elif opt == "actionunban":
|
||||||
stream.append(head + ["actionunban", self.file, self.opts[opt]])
|
stream.append(head + ["actionunban", self.__file, self.__opts[opt]])
|
||||||
# cInfo
|
# cInfo
|
||||||
if self.cInfo:
|
if self.__cInfo:
|
||||||
for p in self.cInfo:
|
for p in self.__cInfo:
|
||||||
stream.append(head + ["setcinfo", self.file, p, self.cInfo[p]])
|
stream.append(head + ["setcinfo", self.__file, p, self.__cInfo[p]])
|
||||||
|
|
||||||
return stream
|
return stream
|
||||||
|
|
|
@ -40,17 +40,17 @@ logSys = logging.getLogger("fail2ban.client.config")
|
||||||
class Beautifier:
|
class Beautifier:
|
||||||
|
|
||||||
def __init__(self, cmd = None):
|
def __init__(self, cmd = None):
|
||||||
self.inputCmd = cmd
|
self.__inputCmd = cmd
|
||||||
|
|
||||||
def setInputCmd(self, cmd):
|
def setInputCmd(self, cmd):
|
||||||
self.inputCmd = cmd
|
self.__inputCmd = cmd
|
||||||
|
|
||||||
def getInputCmd(self):
|
def getInputCmd(self):
|
||||||
return self.inputCmd
|
return self.__inputCmd
|
||||||
|
|
||||||
def beautify(self, response):
|
def beautify(self, response):
|
||||||
logSys.debug("Beautify " + `response` + " with " + `self.inputCmd`)
|
logSys.debug("Beautify " + `response` + " with " + `self.__inputCmd`)
|
||||||
inC = self.inputCmd
|
inC = self.__inputCmd
|
||||||
msg = response
|
msg = response
|
||||||
try:
|
try:
|
||||||
if inC[0] == "start":
|
if inC[0] == "start":
|
||||||
|
@ -110,13 +110,13 @@ class Beautifier:
|
||||||
msg = msg + "`- " + response[len(response)-1]
|
msg = msg + "`- " + response[len(response)-1]
|
||||||
except Exception:
|
except Exception:
|
||||||
logSys.warn("Beautifier error. Please report the error")
|
logSys.warn("Beautifier error. Please report the error")
|
||||||
logSys.error("Beautify " + `response` + " with " + `self.inputCmd` +
|
logSys.error("Beautify " + `response` + " with " + `self.__inputCmd` +
|
||||||
" failed")
|
" failed")
|
||||||
msg = msg + `response`
|
msg = msg + `response`
|
||||||
return msg
|
return msg
|
||||||
|
|
||||||
def beautifyError(self, response):
|
def beautifyError(self, response):
|
||||||
logSys.debug("Beautify (error) " + `response` + " with " + `self.inputCmd`)
|
logSys.debug("Beautify (error) " + `response` + " with " + `self.__inputCmd`)
|
||||||
msg = response
|
msg = response
|
||||||
if isinstance(response, UnknownJailException):
|
if isinstance(response, UnknownJailException):
|
||||||
msg = "Sorry but the jail '" + response[0] + "' does not exist"
|
msg = "Sorry but the jail '" + response[0] + "' does not exist"
|
||||||
|
|
|
@ -36,7 +36,7 @@ class ConfigReader(SafeConfigParser):
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
SafeConfigParser.__init__(self)
|
SafeConfigParser.__init__(self)
|
||||||
self.opts = None
|
self.__opts = None
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def setBaseDir(dir):
|
def setBaseDir(dir):
|
||||||
|
|
|
@ -35,10 +35,10 @@ logSys = logging.getLogger("fail2ban.client.config")
|
||||||
class Configurator:
|
class Configurator:
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.settings = dict()
|
self.__settings = dict()
|
||||||
self.streams = dict()
|
self.__streams = dict()
|
||||||
self.fail2ban = Fail2banReader()
|
self.__fail2ban = Fail2banReader()
|
||||||
self.jails = JailsReader()
|
self.__jails = JailsReader()
|
||||||
|
|
||||||
def setBaseDir(self, dir):
|
def setBaseDir(self, dir):
|
||||||
ConfigReader.setBaseDir(dir)
|
ConfigReader.setBaseDir(dir)
|
||||||
|
@ -47,22 +47,22 @@ class Configurator:
|
||||||
return ConfigReader.getBaseDir()
|
return ConfigReader.getBaseDir()
|
||||||
|
|
||||||
def readAll(self):
|
def readAll(self):
|
||||||
self.fail2ban.read()
|
self.__fail2ban.read()
|
||||||
self.jails.read()
|
self.__jails.read()
|
||||||
|
|
||||||
def getAllOptions(self):
|
def getAllOptions(self):
|
||||||
self.settings["general"] = self.fail2ban.getOptions()
|
self.__settings["general"] = self.__fail2ban.getOptions()
|
||||||
self.settings["jails"] = self.jails.getOptions()
|
self.__settings["jails"] = self.__jails.getOptions()
|
||||||
|
|
||||||
def convertToProtocol(self):
|
def convertToProtocol(self):
|
||||||
self.streams["general"] = self.fail2ban.convert()
|
self.__streams["general"] = self.__fail2ban.convert()
|
||||||
self.streams["jails"] = self.jails.convert()
|
self.__streams["jails"] = self.__jails.convert()
|
||||||
|
|
||||||
def getConfigStream(self):
|
def getConfigStream(self):
|
||||||
cmds = list()
|
cmds = list()
|
||||||
for opt in self.streams["general"]:
|
for opt in self.__streams["general"]:
|
||||||
cmds.append(opt)
|
cmds.append(opt)
|
||||||
for opt in self.streams["jails"]:
|
for opt in self.__streams["jails"]:
|
||||||
cmds.append(opt)
|
cmds.append(opt)
|
||||||
return cmds
|
return cmds
|
||||||
|
|
|
@ -34,16 +34,16 @@ class CSocket:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
# Create an INET, STREAMing socket
|
# Create an INET, STREAMing socket
|
||||||
#self.csock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
#self.csock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
self.csock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
self.__csock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||||
#self.csock.connect(("localhost", 2222))
|
#self.csock.connect(("localhost", 2222))
|
||||||
self.csock.connect(CSocket.SOCKET_FILE)
|
self.__csock.connect(CSocket.SOCKET_FILE)
|
||||||
|
|
||||||
def send(self, msg):
|
def send(self, msg):
|
||||||
# Convert every list member to string
|
# Convert every list member to string
|
||||||
obj = pickle.dumps(map(str, msg))
|
obj = pickle.dumps(map(str, msg))
|
||||||
self.csock.send(obj + CSocket.END_STRING)
|
self.__csock.send(obj + CSocket.END_STRING)
|
||||||
ret = self.receive(self.csock)
|
ret = self.receive(self.__csock)
|
||||||
self.csock.close()
|
self.__csock.close()
|
||||||
return ret
|
return ret
|
||||||
|
|
||||||
def receive(self, socket):
|
def receive(self, socket):
|
||||||
|
|
|
@ -41,14 +41,14 @@ class Fail2banReader(ConfigReader):
|
||||||
def getOptions(self):
|
def getOptions(self):
|
||||||
opts = [["int", "loglevel", 1],
|
opts = [["int", "loglevel", 1],
|
||||||
["string", "logtarget", "STDERR"]]
|
["string", "logtarget", "STDERR"]]
|
||||||
self.opts = ConfigReader.getOptions(self, "Definition", opts)
|
self.__opts = ConfigReader.getOptions(self, "Definition", opts)
|
||||||
|
|
||||||
def convert(self):
|
def convert(self):
|
||||||
stream = list()
|
stream = list()
|
||||||
for opt in self.opts:
|
for opt in self.__opts:
|
||||||
if opt == "loglevel":
|
if opt == "loglevel":
|
||||||
stream.append(["set", "loglevel", self.opts[opt]])
|
stream.append(["set", "loglevel", self.__opts[opt]])
|
||||||
elif opt == "logtarget":
|
elif opt == "logtarget":
|
||||||
stream.append(["set", "logtarget", self.opts[opt]])
|
stream.append(["set", "logtarget", self.__opts[opt]])
|
||||||
return stream
|
return stream
|
||||||
|
|
|
@ -34,38 +34,38 @@ class FilterReader(ConfigReader):
|
||||||
|
|
||||||
def __init__(self, file, name):
|
def __init__(self, file, name):
|
||||||
ConfigReader.__init__(self)
|
ConfigReader.__init__(self)
|
||||||
self.file = file
|
self.__file = file
|
||||||
self.name = name
|
self.__name = name
|
||||||
|
|
||||||
def setFile(self, file):
|
def setFile(self, file):
|
||||||
self.file = file
|
self.__file = file
|
||||||
|
|
||||||
def getFile(self):
|
def getFile(self):
|
||||||
return self.file
|
return self.__file
|
||||||
|
|
||||||
def setName(self, name):
|
def setName(self, name):
|
||||||
self.name = name
|
self.__name = name
|
||||||
|
|
||||||
def getName(self):
|
def getName(self):
|
||||||
return self.name
|
return self.__name
|
||||||
|
|
||||||
def read(self):
|
def read(self):
|
||||||
return ConfigReader.read(self, "filter.d/" + self.file)
|
return ConfigReader.read(self, "filter.d/" + self.__file)
|
||||||
|
|
||||||
def getOptions(self, pOpts):
|
def getOptions(self, pOpts):
|
||||||
opts = [["string", "timeregex", None],
|
opts = [["string", "timeregex", None],
|
||||||
["string", "timepattern", None],
|
["string", "timepattern", None],
|
||||||
["string", "failregex", ""]]
|
["string", "failregex", ""]]
|
||||||
self.opts = ConfigReader.getOptions(self, "Definition", opts, pOpts)
|
self.__opts = ConfigReader.getOptions(self, "Definition", opts, pOpts)
|
||||||
|
|
||||||
def convert(self):
|
def convert(self):
|
||||||
stream = list()
|
stream = list()
|
||||||
for opt in self.opts:
|
for opt in self.__opts:
|
||||||
if opt == "timeregex":
|
if opt == "timeregex":
|
||||||
stream.append(["set", self.name, "timeregex", self.opts[opt]])
|
stream.append(["set", self.__name, "timeregex", self.__opts[opt]])
|
||||||
elif opt == "timepattern":
|
elif opt == "timepattern":
|
||||||
stream.append(["set", self.name, "timepattern", self.opts[opt]])
|
stream.append(["set", self.__name, "timepattern", self.__opts[opt]])
|
||||||
elif opt == "failregex":
|
elif opt == "failregex":
|
||||||
stream.append(["set", self.name, "failregex", self.opts[opt]])
|
stream.append(["set", self.__name, "failregex", self.__opts[opt]])
|
||||||
return stream
|
return stream
|
||||||
|
|
|
@ -39,21 +39,21 @@ class JailReader(ConfigReader):
|
||||||
|
|
||||||
def __init__(self, name):
|
def __init__(self, name):
|
||||||
ConfigReader.__init__(self)
|
ConfigReader.__init__(self)
|
||||||
self.name = name
|
self.__name = name
|
||||||
self.filter = None
|
self.__filter = None
|
||||||
self.actions = list()
|
self.__actions = list()
|
||||||
|
|
||||||
def setName(self, value):
|
def setName(self, value):
|
||||||
self.name = value
|
self.__name = value
|
||||||
|
|
||||||
def getName(self):
|
def getName(self):
|
||||||
return self.name
|
return self.__name
|
||||||
|
|
||||||
def read(self):
|
def read(self):
|
||||||
ConfigReader.read(self, "jail")
|
ConfigReader.read(self, "jail")
|
||||||
|
|
||||||
def isEnabled(self):
|
def isEnabled(self):
|
||||||
return self.opts["enabled"]
|
return self.__opts["enabled"]
|
||||||
|
|
||||||
def getOptions(self):
|
def getOptions(self):
|
||||||
opts = [["bool", "enabled", "false"],
|
opts = [["bool", "enabled", "false"],
|
||||||
|
@ -64,27 +64,27 @@ class JailReader(ConfigReader):
|
||||||
["string", "ignoreip", None],
|
["string", "ignoreip", None],
|
||||||
["string", "filter", ""],
|
["string", "filter", ""],
|
||||||
["string", "action", ""]]
|
["string", "action", ""]]
|
||||||
self.opts = ConfigReader.getOptions(self, self.name, opts)
|
self.__opts = ConfigReader.getOptions(self, self.__name, opts)
|
||||||
|
|
||||||
if self.isEnabled():
|
if self.isEnabled():
|
||||||
# Read filter
|
# Read filter
|
||||||
self.filter = FilterReader(self.opts["filter"], self.name)
|
self.__filter = FilterReader(self.__opts["filter"], self.__name)
|
||||||
ret = self.filter.read()
|
ret = self.__filter.read()
|
||||||
if ret:
|
if ret:
|
||||||
self.filter.getOptions(self.opts)
|
self.__filter.getOptions(self.__opts)
|
||||||
else:
|
else:
|
||||||
logSys.error("Unable to read the filter")
|
logSys.error("Unable to read the filter")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# Read action
|
# Read action
|
||||||
for act in self.opts["action"].split('\n'):
|
for act in self.__opts["action"].split('\n'):
|
||||||
try:
|
try:
|
||||||
splitAct = JailReader.splitAction(act)
|
splitAct = JailReader.splitAction(act)
|
||||||
action = ActionReader(splitAct, self.name)
|
action = ActionReader(splitAct, self.__name)
|
||||||
ret = action.read()
|
ret = action.read()
|
||||||
if ret:
|
if ret:
|
||||||
action.getOptions(self.opts)
|
action.getOptions(self.__opts)
|
||||||
self.actions.append(action)
|
self.__actions.append(action)
|
||||||
else:
|
else:
|
||||||
raise AttributeError("Unable to read action")
|
raise AttributeError("Unable to read action")
|
||||||
except AttributeError, e:
|
except AttributeError, e:
|
||||||
|
@ -94,24 +94,24 @@ class JailReader(ConfigReader):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def convert(self):
|
def convert(self):
|
||||||
stream = [["add", self.name]]
|
stream = [["add", self.__name]]
|
||||||
for opt in self.opts:
|
for opt in self.__opts:
|
||||||
if opt == "logpath":
|
if opt == "logpath":
|
||||||
pathList = glob.glob(self.opts[opt])
|
pathList = glob.glob(self.__opts[opt])
|
||||||
if len(pathList) == 0:
|
if len(pathList) == 0:
|
||||||
logSys.error("No file found for " + self.opts[opt])
|
logSys.error("No file found for " + self.__opts[opt])
|
||||||
for path in pathList:
|
for path in pathList:
|
||||||
stream.append(["set", self.name, "addlogpath", path])
|
stream.append(["set", self.__name, "addlogpath", path])
|
||||||
elif opt == "maxretry":
|
elif opt == "maxretry":
|
||||||
stream.append(["set", self.name, "maxretry", self.opts[opt]])
|
stream.append(["set", self.__name, "maxretry", self.__opts[opt]])
|
||||||
elif opt == "ignoreip":
|
elif opt == "ignoreip":
|
||||||
stream.append(["set", self.name, "addignoreip", self.opts[opt]])
|
stream.append(["set", self.__name, "addignoreip", self.__opts[opt]])
|
||||||
elif opt == "maxtime":
|
elif opt == "maxtime":
|
||||||
stream.append(["set", self.name, "maxtime", self.opts[opt]])
|
stream.append(["set", self.__name, "maxtime", self.__opts[opt]])
|
||||||
elif opt == "bantime":
|
elif opt == "bantime":
|
||||||
stream.append(["set", self.name, "bantime", self.opts[opt]])
|
stream.append(["set", self.__name, "bantime", self.__opts[opt]])
|
||||||
stream.extend(self.filter.convert())
|
stream.extend(self.__filter.convert())
|
||||||
for action in self.actions:
|
for action in self.__actions:
|
||||||
stream.extend(action.convert())
|
stream.extend(action.convert())
|
||||||
return stream
|
return stream
|
||||||
|
|
||||||
|
|
|
@ -35,14 +35,14 @@ class JailsReader(ConfigReader):
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
ConfigReader.__init__(self)
|
ConfigReader.__init__(self)
|
||||||
self.jails = list()
|
self.__jails = list()
|
||||||
|
|
||||||
def read(self):
|
def read(self):
|
||||||
ConfigReader.read(self, "jail")
|
ConfigReader.read(self, "jail")
|
||||||
|
|
||||||
def getOptions(self):
|
def getOptions(self):
|
||||||
opts = []
|
opts = []
|
||||||
self.opts = ConfigReader.getOptions(self, "Definition", opts)
|
self.__opts = ConfigReader.getOptions(self, "Definition", opts)
|
||||||
|
|
||||||
for sec in self.sections():
|
for sec in self.sections():
|
||||||
jail = JailReader(sec)
|
jail = JailReader(sec)
|
||||||
|
@ -51,7 +51,7 @@ class JailsReader(ConfigReader):
|
||||||
if ret:
|
if ret:
|
||||||
if jail.isEnabled():
|
if jail.isEnabled():
|
||||||
# We only add enabled jails
|
# We only add enabled jails
|
||||||
self.jails.append(jail)
|
self.__jails.append(jail)
|
||||||
else:
|
else:
|
||||||
logSys.error("Errors in jail '" + sec + "'. Skipping...")
|
logSys.error("Errors in jail '" + sec + "'. Skipping...")
|
||||||
|
|
||||||
|
@ -62,14 +62,14 @@ class JailsReader(ConfigReader):
|
||||||
|
|
||||||
def convert(self):
|
def convert(self):
|
||||||
stream = list()
|
stream = list()
|
||||||
for opt in self.opts:
|
for opt in self.__opts:
|
||||||
if opt == "":
|
if opt == "":
|
||||||
stream.append([])
|
stream.append([])
|
||||||
# Convert jails
|
# Convert jails
|
||||||
for jail in self.jails:
|
for jail in self.__jails:
|
||||||
stream.extend(jail.convert())
|
stream.extend(jail.convert())
|
||||||
# Start jails
|
# Start jails
|
||||||
for jail in self.jails:
|
for jail in self.__jails:
|
||||||
stream.append(["start", jail.getName()])
|
stream.append(["start", jail.getName()])
|
||||||
|
|
||||||
return stream
|
return stream
|
||||||
|
|
|
@ -50,14 +50,14 @@ class Fail2banClient:
|
||||||
prompt = "fail2ban> "
|
prompt = "fail2ban> "
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.argv = None
|
self.__argv = None
|
||||||
self.stream = None
|
self.__stream = None
|
||||||
self.conf = dict()
|
self.__conf = dict()
|
||||||
self.conf["conf"] = "/etc/fail2ban"
|
self.__conf["conf"] = "/etc/fail2ban"
|
||||||
self.conf["dump"] = False
|
self.__conf["dump"] = False
|
||||||
self.conf["force"] = False
|
self.__conf["force"] = False
|
||||||
self.conf["verbose"] = 2
|
self.__conf["verbose"] = 2
|
||||||
self.conf["interactive"] = False
|
self.__conf["interactive"] = False
|
||||||
|
|
||||||
def dispVersion(self):
|
def dispVersion(self):
|
||||||
print "Fail2Ban v" + version
|
print "Fail2Ban v" + version
|
||||||
|
@ -72,7 +72,7 @@ class Fail2banClient:
|
||||||
def dispUsage(self):
|
def dispUsage(self):
|
||||||
""" Prints Fail2Ban command line options and exits
|
""" Prints Fail2Ban command line options and exits
|
||||||
"""
|
"""
|
||||||
print "Usage: "+self.argv[0]+" [OPTIONS]... <COMMAND>"
|
print "Usage: "+self.__argv[0]+" [OPTIONS]... <COMMAND>"
|
||||||
print
|
print
|
||||||
print "Fail2Ban v" + version + " reads log file that contains password failure report"
|
print "Fail2Ban v" + version + " reads log file that contains password failure report"
|
||||||
print "and bans the corresponding IP addresses using firewall rules."
|
print "and bans the corresponding IP addresses using firewall rules."
|
||||||
|
@ -112,22 +112,22 @@ class Fail2banClient:
|
||||||
print "and bans the corresponding IP addresses using firewall rules."
|
print "and bans the corresponding IP addresses using firewall rules."
|
||||||
print
|
print
|
||||||
|
|
||||||
def getCmdLineOptions(self, optList):
|
def __getCmdLineOptions(self, optList):
|
||||||
""" Gets the command line options
|
""" Gets the command line options
|
||||||
"""
|
"""
|
||||||
for opt in optList:
|
for opt in optList:
|
||||||
if opt[0] == "-c":
|
if opt[0] == "-c":
|
||||||
self.conf["conf"] = opt[1]
|
self.__conf["conf"] = opt[1]
|
||||||
elif opt[0] == "-d":
|
elif opt[0] == "-d":
|
||||||
self.conf["dump"] = True
|
self.__conf["dump"] = True
|
||||||
elif opt[0] == "-v":
|
elif opt[0] == "-v":
|
||||||
self.conf["verbose"] = self.conf["verbose"] + 1
|
self.__conf["verbose"] = self.__conf["verbose"] + 1
|
||||||
elif opt[0] == "-q":
|
elif opt[0] == "-q":
|
||||||
self.conf["verbose"] = self.conf["verbose"] - 1
|
self.__conf["verbose"] = self.__conf["verbose"] - 1
|
||||||
elif opt[0] == "-x":
|
elif opt[0] == "-x":
|
||||||
self.conf["force"] = True
|
self.__conf["force"] = True
|
||||||
elif opt[0] == "-i":
|
elif opt[0] == "-i":
|
||||||
self.conf["interactive"] = True
|
self.__conf["interactive"] = True
|
||||||
elif opt[0] in ["-h", "--help"]:
|
elif opt[0] in ["-h", "--help"]:
|
||||||
self.dispUsage()
|
self.dispUsage()
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
|
@ -135,7 +135,7 @@ class Fail2banClient:
|
||||||
self.dispVersion()
|
self.dispVersion()
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
|
|
||||||
def ping(self):
|
def __ping(self):
|
||||||
return self.processCmd([["ping"]], False)
|
return self.processCmd([["ping"]], False)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
@ -170,30 +170,30 @@ class Fail2banClient:
|
||||||
# Process one command line and exit.
|
# Process one command line and exit.
|
||||||
# @param cmd the command line
|
# @param cmd the command line
|
||||||
|
|
||||||
def processCommand(self, cmd):
|
def __processCommand(self, cmd):
|
||||||
if len(cmd) == 1 and cmd[0] == "start":
|
if len(cmd) == 1 and cmd[0] == "start":
|
||||||
if self.ping():
|
if self.__ping():
|
||||||
logSys.info("Server already running")
|
logSys.info("Server already running")
|
||||||
return False
|
return False
|
||||||
else:
|
else:
|
||||||
self.startServerAsync(self.conf["force"])
|
self.__startServerAsync(self.__conf["force"])
|
||||||
# Read the config while the server is starting
|
# Read the config while the server is starting
|
||||||
self.readConfig()
|
self.__readConfig()
|
||||||
try:
|
try:
|
||||||
# Wait for the server to start
|
# Wait for the server to start
|
||||||
self.waitOnServer()
|
self.__waitOnServer()
|
||||||
# Configure the server
|
# Configure the server
|
||||||
self.processCmd(self.stream, False)
|
self.processCmd(self.__stream, False)
|
||||||
return True
|
return True
|
||||||
except ServerExecutionException:
|
except ServerExecutionException:
|
||||||
logSys.error("Could not start server. Try -x option")
|
logSys.error("Could not start server. Try -x option")
|
||||||
return False
|
return False
|
||||||
elif len(cmd) == 1 and cmd[0] == "reload":
|
elif len(cmd) == 1 and cmd[0] == "reload":
|
||||||
if self.ping():
|
if self.__ping():
|
||||||
self.readConfig()
|
self.__readConfig()
|
||||||
self.processCmd([['stop', 'all']], False)
|
self.processCmd([['stop', 'all']], False)
|
||||||
# Configure the server
|
# Configure the server
|
||||||
return self.processCmd(self.stream, False)
|
return self.processCmd(self.__stream, False)
|
||||||
else:
|
else:
|
||||||
logSys.error("Could not find server")
|
logSys.error("Could not find server")
|
||||||
return False
|
return False
|
||||||
|
@ -206,7 +206,7 @@ class Fail2banClient:
|
||||||
#
|
#
|
||||||
# Start the Fail2ban server in daemon mode.
|
# Start the Fail2ban server in daemon mode.
|
||||||
|
|
||||||
def startServerAsync(self, force = False):
|
def __startServerAsync(self, force = False):
|
||||||
args = list()
|
args = list()
|
||||||
|
|
||||||
args.append("fail2ban-server")
|
args.append("fail2ban-server")
|
||||||
|
@ -228,10 +228,10 @@ class Fail2banClient:
|
||||||
os.exit(-1)
|
os.exit(-1)
|
||||||
|
|
||||||
|
|
||||||
def waitOnServer(self):
|
def __waitOnServer(self):
|
||||||
# Wait for the server to start
|
# Wait for the server to start
|
||||||
cnt = 0
|
cnt = 0
|
||||||
while not self.ping():
|
while not self.__ping():
|
||||||
if cnt > 10:
|
if cnt > 10:
|
||||||
raise ServerExecutionException("Failed to start server")
|
raise ServerExecutionException("Failed to start server")
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
|
@ -240,20 +240,20 @@ class Fail2banClient:
|
||||||
|
|
||||||
def start(self, argv):
|
def start(self, argv):
|
||||||
# Command line options
|
# Command line options
|
||||||
self.argv = argv
|
self.__argv = argv
|
||||||
|
|
||||||
# Reads the command line options.
|
# Reads the command line options.
|
||||||
try:
|
try:
|
||||||
cmdOpts = 'hc:xdviqV'
|
cmdOpts = 'hc:xdviqV'
|
||||||
cmdLongOpts = ['help', 'version']
|
cmdLongOpts = ['help', 'version']
|
||||||
optList, args = getopt.getopt(self.argv[1:], cmdOpts, cmdLongOpts)
|
optList, args = getopt.getopt(self.__argv[1:], cmdOpts, cmdLongOpts)
|
||||||
except getopt.GetoptError:
|
except getopt.GetoptError:
|
||||||
self.dispUsage()
|
self.dispUsage()
|
||||||
return False
|
return False
|
||||||
|
|
||||||
self.getCmdLineOptions(optList)
|
self.__getCmdLineOptions(optList)
|
||||||
|
|
||||||
verbose = self.conf["verbose"]
|
verbose = self.__conf["verbose"]
|
||||||
if verbose <= 0:
|
if verbose <= 0:
|
||||||
logSys.setLevel(logging.ERROR)
|
logSys.setLevel(logging.ERROR)
|
||||||
elif verbose == 1:
|
elif verbose == 1:
|
||||||
|
@ -270,17 +270,17 @@ class Fail2banClient:
|
||||||
stdout.setFormatter(formatter)
|
stdout.setFormatter(formatter)
|
||||||
logSys.addHandler(stdout)
|
logSys.addHandler(stdout)
|
||||||
|
|
||||||
if self.conf["dump"]:
|
if self.__conf["dump"]:
|
||||||
self.readConfig()
|
self.__readConfig()
|
||||||
self.dumpConfig(self.stream)
|
self.dumpConfig(self.__stream)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
# Interactive mode
|
# Interactive mode
|
||||||
if self.conf["interactive"]:
|
if self.__conf["interactive"]:
|
||||||
try:
|
try:
|
||||||
ret = True
|
ret = True
|
||||||
if len(args) > 0:
|
if len(args) > 0:
|
||||||
ret = self.processCommand(args)
|
ret = self.__processCommand(args)
|
||||||
if ret:
|
if ret:
|
||||||
readline.parse_and_bind("tab: complete")
|
readline.parse_and_bind("tab: complete")
|
||||||
self.dispInteractive()
|
self.dispInteractive()
|
||||||
|
@ -290,7 +290,7 @@ class Fail2banClient:
|
||||||
# Exit
|
# Exit
|
||||||
return True
|
return True
|
||||||
if not cmd == "":
|
if not cmd == "":
|
||||||
self.processCommand(shlex.split(cmd))
|
self.__processCommand(shlex.split(cmd))
|
||||||
except (EOFError, KeyboardInterrupt):
|
except (EOFError, KeyboardInterrupt):
|
||||||
print
|
print
|
||||||
return True
|
return True
|
||||||
|
@ -299,16 +299,16 @@ class Fail2banClient:
|
||||||
if len(args) < 1:
|
if len(args) < 1:
|
||||||
self.dispUsage()
|
self.dispUsage()
|
||||||
return False
|
return False
|
||||||
return self.processCommand(args)
|
return self.__processCommand(args)
|
||||||
|
|
||||||
def readConfig(self):
|
def __readConfig(self):
|
||||||
# Read the configuration
|
# Read the configuration
|
||||||
cfg = Configurator()
|
cfg = Configurator()
|
||||||
cfg.setBaseDir(self.conf["conf"])
|
cfg.setBaseDir(self.__conf["conf"])
|
||||||
cfg.readAll()
|
cfg.readAll()
|
||||||
cfg.getAllOptions()
|
cfg.getAllOptions()
|
||||||
cfg.convertToProtocol()
|
cfg.convertToProtocol()
|
||||||
self.stream = cfg.getConfigStream()
|
self.__stream = cfg.getConfigStream()
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def dumpConfig(cmd):
|
def dumpConfig(cmd):
|
||||||
|
|
|
@ -37,7 +37,7 @@ from server.filter import Filter
|
||||||
class Fail2banRegex:
|
class Fail2banRegex:
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.filter = Filter(None)
|
self.__filter = Filter(None)
|
||||||
|
|
||||||
def dispUsage(self):
|
def dispUsage(self):
|
||||||
print "Usage: "+sys.argv[0]+" <logline> <failregex>"
|
print "Usage: "+sys.argv[0]+" <logline> <failregex>"
|
||||||
|
@ -46,12 +46,12 @@ class Fail2banRegex:
|
||||||
print "and bans the corresponding IP addresses using firewall rules."
|
print "and bans the corresponding IP addresses using firewall rules."
|
||||||
|
|
||||||
def setRegex(self, value):
|
def setRegex(self, value):
|
||||||
self.filter.setFailRegex(value)
|
self.__filter.setFailRegex(value)
|
||||||
|
|
||||||
def testRegex(self, line):
|
def testRegex(self, line):
|
||||||
print
|
print
|
||||||
try:
|
try:
|
||||||
ret = self.filter.findFailure(line)
|
ret = self.__filter.findFailure(line)
|
||||||
except IndexError:
|
except IndexError:
|
||||||
print "Sorry, but no <host> found in regex"
|
print "Sorry, but no <host> found in regex"
|
||||||
return False
|
return False
|
||||||
|
@ -68,7 +68,7 @@ class Fail2banRegex:
|
||||||
print "IP :" + ipList
|
print "IP :" + ipList
|
||||||
print
|
print
|
||||||
print "Date template hits:"
|
print "Date template hits:"
|
||||||
for template in self.filter.dateDetector.templates:
|
for template in self.__filter.dateDetector.templates:
|
||||||
print `template.getHits()` + " hit: " + template.getName()
|
print `template.getHits()` + " hit: " + template.getName()
|
||||||
print
|
print
|
||||||
print "Benchmark. Executing 1000..."
|
print "Benchmark. Executing 1000..."
|
||||||
|
@ -80,7 +80,7 @@ class Fail2banRegex:
|
||||||
minPos = 0
|
minPos = 0
|
||||||
for i in range(1000):
|
for i in range(1000):
|
||||||
start = time.time()
|
start = time.time()
|
||||||
ret = self.filter.findFailure(line)
|
ret = self.__filter.findFailure(line)
|
||||||
end = time.time()
|
end = time.time()
|
||||||
diff = (end - start) * 1000
|
diff = (end - start) * 1000
|
||||||
total = total + diff
|
total = total + diff
|
||||||
|
|
|
@ -45,11 +45,11 @@ from server.server import Server
|
||||||
class Fail2banServer:
|
class Fail2banServer:
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.server = None
|
self.__server = None
|
||||||
self.argv = None
|
self.__argv = None
|
||||||
self.conf = dict()
|
self.__conf = dict()
|
||||||
self.conf["background"] = True
|
self.__conf["background"] = True
|
||||||
self.conf["force"] = False
|
self.__conf["force"] = False
|
||||||
|
|
||||||
def dispVersion(self):
|
def dispVersion(self):
|
||||||
print "Fail2Ban v" + version
|
print "Fail2Ban v" + version
|
||||||
|
@ -64,7 +64,7 @@ class Fail2banServer:
|
||||||
def dispUsage(self):
|
def dispUsage(self):
|
||||||
""" Prints Fail2Ban command line options and exits
|
""" Prints Fail2Ban command line options and exits
|
||||||
"""
|
"""
|
||||||
print "Usage: "+self.argv[0]+" [OPTIONS]"
|
print "Usage: "+self.__argv[0]+" [OPTIONS]"
|
||||||
print
|
print
|
||||||
print "Fail2Ban v" + version + " reads log file that contains password failure report"
|
print "Fail2Ban v" + version + " reads log file that contains password failure report"
|
||||||
print "and bans the corresponding IP addresses using firewall rules."
|
print "and bans the corresponding IP addresses using firewall rules."
|
||||||
|
@ -81,16 +81,16 @@ class Fail2banServer:
|
||||||
print
|
print
|
||||||
print "Report bugs to <lostcontrol@users.sourceforge.net>"
|
print "Report bugs to <lostcontrol@users.sourceforge.net>"
|
||||||
|
|
||||||
def getCmdLineOptions(self, optList):
|
def __getCmdLineOptions(self, optList):
|
||||||
""" Gets the command line options
|
""" Gets the command line options
|
||||||
"""
|
"""
|
||||||
for opt in optList:
|
for opt in optList:
|
||||||
if opt[0] == "-b":
|
if opt[0] == "-b":
|
||||||
self.conf["background"] = True
|
self.__conf["background"] = True
|
||||||
if opt[0] == "-f":
|
if opt[0] == "-f":
|
||||||
self.conf["background"] = False
|
self.__conf["background"] = False
|
||||||
if opt[0] == "-x":
|
if opt[0] == "-x":
|
||||||
self.conf["force"] = True
|
self.__conf["force"] = True
|
||||||
if opt[0] in ["-h", "--help"]:
|
if opt[0] in ["-h", "--help"]:
|
||||||
self.dispUsage()
|
self.dispUsage()
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
|
@ -107,25 +107,25 @@ class Fail2banServer:
|
||||||
|
|
||||||
def start(self, argv):
|
def start(self, argv):
|
||||||
# Command line options
|
# Command line options
|
||||||
self.argv = argv
|
self.__argv = argv
|
||||||
|
|
||||||
# Reads the command line options.
|
# Reads the command line options.
|
||||||
try:
|
try:
|
||||||
cmdOpts = 'bfxhV'
|
cmdOpts = 'bfxhV'
|
||||||
cmdLongOpts = ['help', 'version']
|
cmdLongOpts = ['help', 'version']
|
||||||
optList, args = getopt.getopt(self.argv[1:], cmdOpts, cmdLongOpts)
|
optList, args = getopt.getopt(self.__argv[1:], cmdOpts, cmdLongOpts)
|
||||||
except getopt.GetoptError:
|
except getopt.GetoptError:
|
||||||
self.dispUsage()
|
self.dispUsage()
|
||||||
|
|
||||||
self.getCmdLineOptions(optList)
|
self.__getCmdLineOptions(optList)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
self.server = Server(self.conf["background"])
|
self.__server = Server(self.__conf["background"])
|
||||||
self.server.start(self.conf["force"])
|
self.__server.start(self.__conf["force"])
|
||||||
return True
|
return True
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
print e
|
print e
|
||||||
self.server.quit()
|
self.__server.quit()
|
||||||
return False
|
return False
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
|
@ -39,34 +39,34 @@ logSys = logging.getLogger("fail2ban.actions.action")
|
||||||
class Action:
|
class Action:
|
||||||
|
|
||||||
def __init__(self, name):
|
def __init__(self, name):
|
||||||
self.name = name
|
self.__name = name
|
||||||
self.cInfo = dict()
|
self.__cInfo = dict()
|
||||||
## Command executed in order to initialize the system.
|
## Command executed in order to initialize the system.
|
||||||
self.actionStart = ''
|
self.__actionStart = ''
|
||||||
## Command executed when an IP address gets banned.
|
## Command executed when an IP address gets banned.
|
||||||
self.actionBan = ''
|
self.__actionBan = ''
|
||||||
## Command executed when an IP address gets removed.
|
## Command executed when an IP address gets removed.
|
||||||
self.actionUnban = ''
|
self.__actionUnban = ''
|
||||||
## Command executed in order to check requirements.
|
## Command executed in order to check requirements.
|
||||||
self.actionCheck = ''
|
self.__actionCheck = ''
|
||||||
## Command executed in order to stop the system.
|
## Command executed in order to stop the system.
|
||||||
self.actionStop = ''
|
self.__actionStop = ''
|
||||||
logSys.debug("Created Action")
|
logSys.debug("Created Action")
|
||||||
|
|
||||||
def setName(self, name):
|
def setName(self, name):
|
||||||
self.name = name
|
self.__name = name
|
||||||
|
|
||||||
def getName(self):
|
def getName(self):
|
||||||
return self.name
|
return self.__name
|
||||||
|
|
||||||
def setCInfo(self, key, value):
|
def setCInfo(self, key, value):
|
||||||
self.cInfo[key] = value
|
self.__cInfo[key] = value
|
||||||
|
|
||||||
def getCInfo(self, key):
|
def getCInfo(self, key):
|
||||||
return self.cInfo[key]
|
return self.__cInfo[key]
|
||||||
|
|
||||||
def delCInfo(self, key):
|
def delCInfo(self, key):
|
||||||
del self.cInfo[key]
|
del self.__cInfo[key]
|
||||||
|
|
||||||
##
|
##
|
||||||
# Set the "start" command.
|
# Set the "start" command.
|
||||||
|
@ -74,7 +74,7 @@ class Action:
|
||||||
# @param value the command
|
# @param value the command
|
||||||
|
|
||||||
def setActionStart(self, value):
|
def setActionStart(self, value):
|
||||||
self.actionStart = value
|
self.__actionStart = value
|
||||||
logSys.info("Set actionStart = %s" % value)
|
logSys.info("Set actionStart = %s" % value)
|
||||||
|
|
||||||
##
|
##
|
||||||
|
@ -83,10 +83,10 @@ class Action:
|
||||||
# @return the command
|
# @return the command
|
||||||
|
|
||||||
def getActionStart(self):
|
def getActionStart(self):
|
||||||
return self.actionStart
|
return self.__actionStart
|
||||||
|
|
||||||
def execActionStart(self):
|
def execActionStart(self):
|
||||||
startCmd = Action.replaceTag(self.actionStart, self.cInfo)
|
startCmd = Action.replaceTag(self.__actionStart, self.__cInfo)
|
||||||
return Action.executeCmd(startCmd)
|
return Action.executeCmd(startCmd)
|
||||||
|
|
||||||
##
|
##
|
||||||
|
@ -95,7 +95,7 @@ class Action:
|
||||||
# @param value the command
|
# @param value the command
|
||||||
|
|
||||||
def setActionBan(self, value):
|
def setActionBan(self, value):
|
||||||
self.actionBan = value
|
self.__actionBan = value
|
||||||
logSys.info("Set actionBan = %s" % value)
|
logSys.info("Set actionBan = %s" % value)
|
||||||
|
|
||||||
##
|
##
|
||||||
|
@ -104,10 +104,10 @@ class Action:
|
||||||
# @return the command
|
# @return the command
|
||||||
|
|
||||||
def getActionBan(self):
|
def getActionBan(self):
|
||||||
return self.actionBan
|
return self.__actionBan
|
||||||
|
|
||||||
def execActionBan(self, aInfo):
|
def execActionBan(self, aInfo):
|
||||||
return self.processCmd(self.actionBan, aInfo);
|
return self.__processCmd(self.__actionBan, aInfo);
|
||||||
|
|
||||||
##
|
##
|
||||||
# Set the "unban" command.
|
# Set the "unban" command.
|
||||||
|
@ -115,7 +115,7 @@ class Action:
|
||||||
# @param value the command
|
# @param value the command
|
||||||
|
|
||||||
def setActionUnban(self, value):
|
def setActionUnban(self, value):
|
||||||
self.actionUnban = value
|
self.__actionUnban = value
|
||||||
logSys.info("Set actionUnban = %s" % value)
|
logSys.info("Set actionUnban = %s" % value)
|
||||||
|
|
||||||
##
|
##
|
||||||
|
@ -124,10 +124,10 @@ class Action:
|
||||||
# @return the command
|
# @return the command
|
||||||
|
|
||||||
def getActionUnban(self):
|
def getActionUnban(self):
|
||||||
return self.actionUnban
|
return self.__actionUnban
|
||||||
|
|
||||||
def execActionUnban(self, aInfo):
|
def execActionUnban(self, aInfo):
|
||||||
return self.processCmd(self.actionUnban, aInfo);
|
return self.__processCmd(self.__actionUnban, aInfo);
|
||||||
|
|
||||||
##
|
##
|
||||||
# Set the "check" command.
|
# Set the "check" command.
|
||||||
|
@ -135,7 +135,7 @@ class Action:
|
||||||
# @param value the command
|
# @param value the command
|
||||||
|
|
||||||
def setActionCheck(self, value):
|
def setActionCheck(self, value):
|
||||||
self.actionCheck = value
|
self.__actionCheck = value
|
||||||
logSys.info("Set actionCheck = %s" % value)
|
logSys.info("Set actionCheck = %s" % value)
|
||||||
|
|
||||||
##
|
##
|
||||||
|
@ -144,7 +144,7 @@ class Action:
|
||||||
# @return the command
|
# @return the command
|
||||||
|
|
||||||
def getActionCheck(self):
|
def getActionCheck(self):
|
||||||
return self.actionCheck
|
return self.__actionCheck
|
||||||
|
|
||||||
##
|
##
|
||||||
# Set the "stop" command.
|
# Set the "stop" command.
|
||||||
|
@ -152,7 +152,7 @@ class Action:
|
||||||
# @param value the command
|
# @param value the command
|
||||||
|
|
||||||
def setActionStop(self, value):
|
def setActionStop(self, value):
|
||||||
self.actionStop = value
|
self.__actionStop = value
|
||||||
logSys.info("Set actionStop = %s" % value)
|
logSys.info("Set actionStop = %s" % value)
|
||||||
|
|
||||||
##
|
##
|
||||||
|
@ -161,10 +161,10 @@ class Action:
|
||||||
# @return the command
|
# @return the command
|
||||||
|
|
||||||
def getActionStop(self):
|
def getActionStop(self):
|
||||||
return self.actionStop
|
return self.__actionStop
|
||||||
|
|
||||||
def execActionStop(self):
|
def execActionStop(self):
|
||||||
stopCmd = Action.replaceTag(self.actionStop, self.cInfo)
|
stopCmd = Action.replaceTag(self.__actionStop, self.__cInfo)
|
||||||
return Action.executeCmd(stopCmd)
|
return Action.executeCmd(stopCmd)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
@ -178,20 +178,20 @@ class Action:
|
||||||
string = string.replace("<br>", '\n')
|
string = string.replace("<br>", '\n')
|
||||||
return string
|
return string
|
||||||
|
|
||||||
def processCmd(self, cmd, aInfo = None):
|
def __processCmd(self, cmd, aInfo = None):
|
||||||
""" Executes an OS command.
|
""" Executes an OS command.
|
||||||
"""
|
"""
|
||||||
if cmd == "":
|
if cmd == "":
|
||||||
logSys.debug("Nothing to do")
|
logSys.debug("Nothing to do")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
checkCmd = Action.replaceTag(self.actionCheck, self.cInfo)
|
checkCmd = Action.replaceTag(self.__actionCheck, self.__cInfo)
|
||||||
if not Action.executeCmd(checkCmd):
|
if not Action.executeCmd(checkCmd):
|
||||||
logSys.error("Invariant check failed. Trying to restore a sane" +
|
logSys.error("Invariant check failed. Trying to restore a sane" +
|
||||||
" environment")
|
" environment")
|
||||||
stopCmd = Action.replaceTag(self.actionStop, self.cInfo)
|
stopCmd = Action.replaceTag(self.__actionStop, self.__cInfo)
|
||||||
Action.executeCmd(stopCmd)
|
Action.executeCmd(stopCmd)
|
||||||
startCmd = Action.replaceTag(self.actionStart, self.cInfo)
|
startCmd = Action.replaceTag(self.__actionStart, self.__cInfo)
|
||||||
Action.executeCmd(startCmd)
|
Action.executeCmd(startCmd)
|
||||||
if not Action.executeCmd(checkCmd):
|
if not Action.executeCmd(checkCmd):
|
||||||
logSys.fatal("Unable to restore environment")
|
logSys.fatal("Unable to restore environment")
|
||||||
|
@ -204,7 +204,7 @@ class Action:
|
||||||
realCmd = cmd
|
realCmd = cmd
|
||||||
|
|
||||||
# Replace static fields
|
# Replace static fields
|
||||||
realCmd = Action.replaceTag(realCmd, self.cInfo)
|
realCmd = Action.replaceTag(realCmd, self.__cInfo)
|
||||||
|
|
||||||
return Action.executeCmd(realCmd)
|
return Action.executeCmd(realCmd)
|
||||||
|
|
||||||
|
|
|
@ -52,29 +52,29 @@ class Actions(JailThread):
|
||||||
JailThread.__init__(self, jail)
|
JailThread.__init__(self, jail)
|
||||||
## The jail which contains this action.
|
## The jail which contains this action.
|
||||||
self.jail = jail
|
self.jail = jail
|
||||||
self.actions = list()
|
self.__actions = list()
|
||||||
## The ban manager.
|
## The ban manager.
|
||||||
self.banManager = BanManager()
|
self.__banManager = BanManager()
|
||||||
|
|
||||||
def addAction(self, name):
|
def addAction(self, name):
|
||||||
action = Action(name)
|
action = Action(name)
|
||||||
self.actions.append(action)
|
self.__actions.append(action)
|
||||||
|
|
||||||
def delAction(self, name):
|
def delAction(self, name):
|
||||||
for action in self.actions:
|
for action in self.__actions:
|
||||||
if action.getName() == name:
|
if action.getName() == name:
|
||||||
self.actions.remove(action)
|
self.__actions.remove(action)
|
||||||
break
|
break
|
||||||
|
|
||||||
def getAction(self, name):
|
def getAction(self, name):
|
||||||
for action in self.actions:
|
for action in self.__actions:
|
||||||
if action.getName() == name:
|
if action.getName() == name:
|
||||||
return action
|
return action
|
||||||
raise KeyError
|
raise KeyError
|
||||||
|
|
||||||
def getLastAction(self):
|
def getLastAction(self):
|
||||||
action = self.actions.pop()
|
action = self.__actions.pop()
|
||||||
self.actions.append(action)
|
self.__actions.append(action)
|
||||||
return action
|
return action
|
||||||
|
|
||||||
##
|
##
|
||||||
|
@ -83,7 +83,7 @@ class Actions(JailThread):
|
||||||
# @param value the time
|
# @param value the time
|
||||||
|
|
||||||
def setBanTime(self, value):
|
def setBanTime(self, value):
|
||||||
self.banManager.setBanTime(value)
|
self.__banManager.setBanTime(value)
|
||||||
logSys.info("Set banTime = %s" % value)
|
logSys.info("Set banTime = %s" % value)
|
||||||
|
|
||||||
##
|
##
|
||||||
|
@ -92,7 +92,7 @@ class Actions(JailThread):
|
||||||
# @return the time
|
# @return the time
|
||||||
|
|
||||||
def getBanTime(self):
|
def getBanTime(self):
|
||||||
return self.banManager.getBanTime()
|
return self.__banManager.getBanTime()
|
||||||
|
|
||||||
##
|
##
|
||||||
# Main loop.
|
# Main loop.
|
||||||
|
@ -102,20 +102,20 @@ class Actions(JailThread):
|
||||||
# @return True when the thread exits nicely
|
# @return True when the thread exits nicely
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
for action in self.actions:
|
for action in self.__actions:
|
||||||
action.execActionStart()
|
action.execActionStart()
|
||||||
self.setActive(True)
|
self.setActive(True)
|
||||||
while self.isActive():
|
while self.isActive():
|
||||||
if not self.isIdle:
|
if not self.getIdle():
|
||||||
#logSys.debug(self.jail.getName() + ": action")
|
#logSys.debug(self.jail.getName() + ": action")
|
||||||
ret = self.checkBan()
|
ret = self.__checkBan()
|
||||||
if not ret:
|
if not ret:
|
||||||
self.checkUnBan()
|
self.__checkUnBan()
|
||||||
time.sleep(self.sleepTime)
|
time.sleep(self.getSleepTime())
|
||||||
else:
|
else:
|
||||||
time.sleep(self.sleepTime)
|
time.sleep(self.getSleepTime())
|
||||||
self.flushBan()
|
self.__flushBan()
|
||||||
for action in self.actions:
|
for action in self.__actions:
|
||||||
action.execActionStop()
|
action.execActionStop()
|
||||||
logSys.debug(self.jail.getName() + ": action terminated")
|
logSys.debug(self.jail.getName() + ": action terminated")
|
||||||
return True
|
return True
|
||||||
|
@ -127,7 +127,7 @@ class Actions(JailThread):
|
||||||
# it executes the "ban" command and add a ticket to the BanManager.
|
# it executes the "ban" command and add a ticket to the BanManager.
|
||||||
# @return True if an IP address get banned
|
# @return True if an IP address get banned
|
||||||
|
|
||||||
def checkBan(self):
|
def __checkBan(self):
|
||||||
ticket = self.jail.getFailTicket()
|
ticket = self.jail.getFailTicket()
|
||||||
if ticket != False:
|
if ticket != False:
|
||||||
aInfo = dict()
|
aInfo = dict()
|
||||||
|
@ -135,9 +135,9 @@ class Actions(JailThread):
|
||||||
aInfo["ip"] = bTicket.getIP()
|
aInfo["ip"] = bTicket.getIP()
|
||||||
aInfo["failures"] = bTicket.getAttempt()
|
aInfo["failures"] = bTicket.getAttempt()
|
||||||
logSys.info("Ban %s" % aInfo["ip"])
|
logSys.info("Ban %s" % aInfo["ip"])
|
||||||
for action in self.actions:
|
for action in self.__actions:
|
||||||
action.execActionBan(aInfo)
|
action.execActionBan(aInfo)
|
||||||
self.banManager.addBanTicket(bTicket)
|
self.__banManager.addBanTicket(bTicket)
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
@ -146,12 +146,12 @@ class Actions(JailThread):
|
||||||
#
|
#
|
||||||
# Unban IP address which are outdated.
|
# Unban IP address which are outdated.
|
||||||
|
|
||||||
def checkUnBan(self):
|
def __checkUnBan(self):
|
||||||
for ticket in self.banManager.unBanList(time.time()):
|
for ticket in self.__banManager.unBanList(time.time()):
|
||||||
aInfo = dict()
|
aInfo = dict()
|
||||||
aInfo["ip"] = ticket.getIP()
|
aInfo["ip"] = ticket.getIP()
|
||||||
logSys.info("Unban %s" % aInfo["ip"])
|
logSys.info("Unban %s" % aInfo["ip"])
|
||||||
for action in self.actions:
|
for action in self.__actions:
|
||||||
action.execActionUnban(aInfo)
|
action.execActionUnban(aInfo)
|
||||||
|
|
||||||
##
|
##
|
||||||
|
@ -159,13 +159,13 @@ class Actions(JailThread):
|
||||||
#
|
#
|
||||||
# Unban all IP address which are still in the banning list.
|
# Unban all IP address which are still in the banning list.
|
||||||
|
|
||||||
def flushBan(self):
|
def __flushBan(self):
|
||||||
logSys.debug("Flush ban list")
|
logSys.debug("Flush ban list")
|
||||||
for ticket in self.banManager.flushBanList():
|
for ticket in self.__banManager.flushBanList():
|
||||||
aInfo = dict()
|
aInfo = dict()
|
||||||
aInfo["ip"] = ticket.getIP()
|
aInfo["ip"] = ticket.getIP()
|
||||||
logSys.info("Unban %s" % aInfo["ip"])
|
logSys.info("Unban %s" % aInfo["ip"])
|
||||||
for action in self.actions:
|
for action in self.__actions:
|
||||||
action.execActionUnban(aInfo)
|
action.execActionUnban(aInfo)
|
||||||
|
|
||||||
##
|
##
|
||||||
|
@ -176,7 +176,7 @@ class Actions(JailThread):
|
||||||
# @return a list with tuple
|
# @return a list with tuple
|
||||||
|
|
||||||
def status(self):
|
def status(self):
|
||||||
ret = [("Currently banned", self.banManager.size()),
|
ret = [("Currently banned", self.__banManager.size()),
|
||||||
("Total banned", self.banManager.getBanTotal())]
|
("Total banned", self.__banManager.getBanTotal())]
|
||||||
return ret
|
return ret
|
||||||
|
|
|
@ -46,13 +46,13 @@ class BanManager:
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
## Mutex used to protect the ban list.
|
## Mutex used to protect the ban list.
|
||||||
self.lock = Lock()
|
self.__lock = Lock()
|
||||||
## The ban list.
|
## The ban list.
|
||||||
self.banList = list()
|
self.__banList = list()
|
||||||
## The amount of time an IP address gets banned.
|
## The amount of time an IP address gets banned.
|
||||||
self.banTime = 600
|
self.__banTime = 600
|
||||||
## Total number of banned IP address
|
## Total number of banned IP address
|
||||||
self.banTotal = 0
|
self.__banTotal = 0
|
||||||
|
|
||||||
##
|
##
|
||||||
# Set the ban time.
|
# Set the ban time.
|
||||||
|
@ -61,9 +61,9 @@ class BanManager:
|
||||||
# @param value the time
|
# @param value the time
|
||||||
|
|
||||||
def setBanTime(self, value):
|
def setBanTime(self, value):
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
self.banTime = int(value)
|
self.__banTime = int(value)
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
##
|
##
|
||||||
# Get the ban time.
|
# Get the ban time.
|
||||||
|
@ -73,10 +73,10 @@ class BanManager:
|
||||||
|
|
||||||
def getBanTime(self):
|
def getBanTime(self):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
return self.banTime
|
return self.__banTime
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
##
|
##
|
||||||
# Set the total number of banned address.
|
# Set the total number of banned address.
|
||||||
|
@ -84,9 +84,9 @@ class BanManager:
|
||||||
# @param value total number
|
# @param value total number
|
||||||
|
|
||||||
def setBanTotal(self, value):
|
def setBanTotal(self, value):
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
self.banTotal = value
|
self.__banTotal = value
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
##
|
##
|
||||||
# Get the total number of banned address.
|
# Get the total number of banned address.
|
||||||
|
@ -95,10 +95,10 @@ class BanManager:
|
||||||
|
|
||||||
def getBanTotal(self):
|
def getBanTotal(self):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
return self.banTotal
|
return self.__banTotal
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
##
|
##
|
||||||
# Create a ban ticket.
|
# Create a ban ticket.
|
||||||
|
@ -126,14 +126,14 @@ class BanManager:
|
||||||
|
|
||||||
def addBanTicket(self, ticket):
|
def addBanTicket(self, ticket):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
if not self.__inBanList(ticket):
|
if not self.__inBanList(ticket):
|
||||||
self.banList.append(ticket)
|
self.__banList.append(ticket)
|
||||||
self.banTotal += 1
|
self.__banTotal += 1
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
##
|
##
|
||||||
# Delete a ban ticket.
|
# Delete a ban ticket.
|
||||||
|
@ -142,7 +142,7 @@ class BanManager:
|
||||||
# @param ticket the ticket
|
# @param ticket the ticket
|
||||||
|
|
||||||
def __delBanTicket(self, ticket):
|
def __delBanTicket(self, ticket):
|
||||||
self.banList.remove(ticket)
|
self.__banList.remove(ticket)
|
||||||
|
|
||||||
##
|
##
|
||||||
# Get the size of the ban list.
|
# Get the size of the ban list.
|
||||||
|
@ -151,10 +151,10 @@ class BanManager:
|
||||||
|
|
||||||
def size(self):
|
def size(self):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
return len(self.banList)
|
return len(self.__banList)
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
##
|
##
|
||||||
# Check if a ticket is in the list.
|
# Check if a ticket is in the list.
|
||||||
|
@ -165,7 +165,7 @@ class BanManager:
|
||||||
# @return True if a ticket already exists
|
# @return True if a ticket already exists
|
||||||
|
|
||||||
def __inBanList(self, ticket):
|
def __inBanList(self, ticket):
|
||||||
for i in self.banList:
|
for i in self.__banList:
|
||||||
if ticket.getIP() == i.getIP():
|
if ticket.getIP() == i.getIP():
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
@ -180,15 +180,15 @@ class BanManager:
|
||||||
|
|
||||||
def unBanList(self, time):
|
def unBanList(self, time):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
uBList = list()
|
uBList = list()
|
||||||
for ticket in self.banList:
|
for ticket in self.__banList:
|
||||||
if ticket.getTime() < time - self.banTime:
|
if ticket.getTime() < time - self.__banTime:
|
||||||
uBList.append(ticket)
|
uBList.append(ticket)
|
||||||
self.__delBanTicket(ticket)
|
self.__delBanTicket(ticket)
|
||||||
return uBList
|
return uBList
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
##
|
##
|
||||||
# Flush the ban list.
|
# Flush the ban list.
|
||||||
|
@ -198,9 +198,9 @@ class BanManager:
|
||||||
|
|
||||||
def flushBanList(self):
|
def flushBanList(self):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
uBList = self.banList
|
uBList = self.__banList
|
||||||
self.banList = list()
|
self.__banList = list()
|
||||||
return uBList
|
return uBList
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
|
@ -38,9 +38,9 @@ logSys = logging.getLogger("fail2ban.filter.datedetector")
|
||||||
class DateDetector:
|
class DateDetector:
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.lock = Lock()
|
self.__lock = Lock()
|
||||||
self.templates = list()
|
self.__templates = list()
|
||||||
self.defTemplate = DateTemplate()
|
self.__defTemplate = DateTemplate()
|
||||||
|
|
||||||
def addDefaultTemplate(self):
|
def addDefaultTemplate(self):
|
||||||
# standard
|
# standard
|
||||||
|
@ -48,67 +48,67 @@ class DateDetector:
|
||||||
template.setName("Month Day Hour:Minute:Second")
|
template.setName("Month Day Hour:Minute:Second")
|
||||||
template.setRegex("^\S{3}\s{1,2}\d{1,2} \d{2}:\d{2}:\d{2}")
|
template.setRegex("^\S{3}\s{1,2}\d{1,2} \d{2}:\d{2}:\d{2}")
|
||||||
template.setPattern("%b %d %H:%M:%S")
|
template.setPattern("%b %d %H:%M:%S")
|
||||||
self.templates.append(template)
|
self.__templates.append(template)
|
||||||
# asctime
|
# asctime
|
||||||
template = DateStrptime()
|
template = DateStrptime()
|
||||||
template.setName("Weekday Month Day Hour:Minute:Second Year")
|
template.setName("Weekday Month Day Hour:Minute:Second Year")
|
||||||
template.setRegex("\S{3} \S{3} \d{2} \d{2}:\d{2}:\d{2} \d{4}")
|
template.setRegex("\S{3} \S{3} \d{2} \d{2}:\d{2}:\d{2} \d{4}")
|
||||||
template.setPattern("%a %b %d %H:%M:%S %Y")
|
template.setPattern("%a %b %d %H:%M:%S %Y")
|
||||||
self.templates.append(template)
|
self.__templates.append(template)
|
||||||
# TAI64N
|
# TAI64N
|
||||||
template = DateTai64n()
|
template = DateTai64n()
|
||||||
template.setName("TAI64N")
|
template.setName("TAI64N")
|
||||||
self.templates.append(template)
|
self.__templates.append(template)
|
||||||
# Epoch
|
# Epoch
|
||||||
template = DateEpoch()
|
template = DateEpoch()
|
||||||
template.setName("Epoch")
|
template.setName("Epoch")
|
||||||
self.templates.append(template)
|
self.__templates.append(template)
|
||||||
|
|
||||||
def setDefaultRegex(self, value):
|
def setDefaultRegex(self, value):
|
||||||
self.defTemplate.setRegex(value)
|
self.__defTemplate.setRegex(value)
|
||||||
|
|
||||||
def getDefaultRegex(self):
|
def getDefaultRegex(self):
|
||||||
return self.defTemplate.getRegex()
|
return self.__defTemplate.getRegex()
|
||||||
|
|
||||||
def setDefaultPattern(self, value):
|
def setDefaultPattern(self, value):
|
||||||
self.defTemplate.setPattern(value)
|
self.__defTemplate.setPattern(value)
|
||||||
|
|
||||||
def getDefaultPattern(self):
|
def getDefaultPattern(self):
|
||||||
return self.defTemplate.getPattern()
|
return self.__defTemplate.getPattern()
|
||||||
|
|
||||||
def matchTime(self, line):
|
def matchTime(self, line):
|
||||||
if self.defTemplate.isValid():
|
if self.__defTemplate.isValid():
|
||||||
return self.defTemplate.matchDate(line)
|
return self.__defTemplate.matchDate(line)
|
||||||
else:
|
else:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
for template in self.templates:
|
for template in self.__templates:
|
||||||
match = template.matchDate(line)
|
match = template.matchDate(line)
|
||||||
if match <> None:
|
if match <> None:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
return match
|
return match
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def getTime(self, line):
|
def getTime(self, line):
|
||||||
if self.defTemplate.isValid():
|
if self.__defTemplate.isValid():
|
||||||
try:
|
try:
|
||||||
date = self.defTemplate.getDate(line)
|
date = self.__defTemplate.getDate(line)
|
||||||
return date
|
return date
|
||||||
except ValueError:
|
except ValueError:
|
||||||
return None
|
return None
|
||||||
else:
|
else:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
for template in self.templates:
|
for template in self.__templates:
|
||||||
try:
|
try:
|
||||||
date = template.getDate(line)
|
date = template.getDate(line)
|
||||||
if date == None:
|
if date == None:
|
||||||
continue
|
continue
|
||||||
template.incHits()
|
template.incHits()
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
return date
|
return date
|
||||||
except ValueError:
|
except ValueError:
|
||||||
pass
|
pass
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def getUnixTime(self, line):
|
def getUnixTime(self, line):
|
||||||
|
@ -123,8 +123,8 @@ class DateDetector:
|
||||||
# in this object and thus should be called from time to time.
|
# in this object and thus should be called from time to time.
|
||||||
|
|
||||||
def sortTemplate(self):
|
def sortTemplate(self):
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
logSys.debug("Sorting the template list")
|
logSys.debug("Sorting the template list")
|
||||||
self.templates.sort(cmp = lambda x, y: cmp(x.getHits(), y.getHits()),
|
self.__templates.sort(cmp = lambda x, y: cmp(x.getHits(), y.getHits()),
|
||||||
reverse=True)
|
reverse=True)
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
|
@ -37,7 +37,7 @@ class DateStrptime(DateTemplate):
|
||||||
date = None
|
date = None
|
||||||
dateMatch = self.matchDate(line)
|
dateMatch = self.matchDate(line)
|
||||||
if dateMatch:
|
if dateMatch:
|
||||||
date = list(time.strptime(dateMatch.group(), self.pattern))
|
date = list(time.strptime(dateMatch.group(), self.getPattern()))
|
||||||
if date[0] < 2000:
|
if date[0] < 2000:
|
||||||
# There is probably no year field in the logs
|
# There is probably no year field in the logs
|
||||||
date[0] = time.gmtime()[0]
|
date[0] = time.gmtime()[0]
|
||||||
|
|
|
@ -29,42 +29,42 @@ import re, time
|
||||||
class DateTemplate:
|
class DateTemplate:
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.name = ""
|
self.__name = ""
|
||||||
self.regex = ""
|
self.__regex = ""
|
||||||
self.cRegex = None
|
self.__cRegex = None
|
||||||
self.pattern = ""
|
self.__pattern = ""
|
||||||
self.hits = 0
|
self.__hits = 0
|
||||||
|
|
||||||
def setName(self, name):
|
def setName(self, name):
|
||||||
self.name = name
|
self.__name = name
|
||||||
|
|
||||||
def getName(self):
|
def getName(self):
|
||||||
return self.name
|
return self.__name
|
||||||
|
|
||||||
def setRegex(self, regex):
|
def setRegex(self, regex):
|
||||||
self.regex = regex
|
self.__regex = regex
|
||||||
self.cRegex = re.compile(regex)
|
self.__cRegex = re.compile(regex)
|
||||||
|
|
||||||
def getRegex(self):
|
def getRegex(self):
|
||||||
return self.regex
|
return self.__regex
|
||||||
|
|
||||||
def setPattern(self, pattern):
|
def setPattern(self, pattern):
|
||||||
self.pattern = pattern
|
self.__pattern = pattern
|
||||||
|
|
||||||
def getPattern(self):
|
def getPattern(self):
|
||||||
return self.pattern
|
return self.__pattern
|
||||||
|
|
||||||
def isValid(self):
|
def isValid(self):
|
||||||
return self.regex != "" and self.pattern != ""
|
return self.__regex != "" and self.__pattern != ""
|
||||||
|
|
||||||
def incHits(self):
|
def incHits(self):
|
||||||
self.hits = self.hits + 1
|
self.__hits = self.__hits + 1
|
||||||
|
|
||||||
def getHits(self):
|
def getHits(self):
|
||||||
return self.hits
|
return self.__hits
|
||||||
|
|
||||||
def matchDate(self, line):
|
def matchDate(self, line):
|
||||||
dateMatch = self.cRegex.search(line)
|
dateMatch = self.__cRegex.search(line)
|
||||||
return dateMatch
|
return dateMatch
|
||||||
|
|
||||||
def getDate(self, line):
|
def getDate(self, line):
|
||||||
|
|
|
@ -32,22 +32,22 @@ logSys = logging.getLogger("fail2ban")
|
||||||
class FailData:
|
class FailData:
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.retry = 0
|
self.__retry = 0
|
||||||
self.lastTime = 0
|
self.__lastTime = 0
|
||||||
|
|
||||||
def setRetry(self, value):
|
def setRetry(self, value):
|
||||||
self.retry = value
|
self.__retry = value
|
||||||
|
|
||||||
def getRetry(self):
|
def getRetry(self):
|
||||||
return self.retry
|
return self.__retry
|
||||||
|
|
||||||
def inc(self):
|
def inc(self):
|
||||||
self.retry += 1
|
self.__retry += 1
|
||||||
|
|
||||||
def setLastTime(self, value):
|
def setLastTime(self, value):
|
||||||
if value > self.lastTime:
|
if value > self.__lastTime:
|
||||||
self.lastTime = value
|
self.__lastTime = value
|
||||||
|
|
||||||
def getLastTime(self):
|
def getLastTime(self):
|
||||||
return self.lastTime
|
return self.__lastTime
|
||||||
|
|
|
@ -35,89 +35,89 @@ logSys = logging.getLogger("fail2ban.filter")
|
||||||
class FailManager:
|
class FailManager:
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.lock = Lock()
|
self.__lock = Lock()
|
||||||
self.failList = dict()
|
self.__failList = dict()
|
||||||
self.maxRetry = 3
|
self.__maxRetry = 3
|
||||||
self.maxTime = 600
|
self.__maxTime = 600
|
||||||
self.failTotal = 0
|
self.__failTotal = 0
|
||||||
|
|
||||||
def setFailTotal(self, value):
|
def setFailTotal(self, value):
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
self.failTotal = value
|
self.__failTotal = value
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def getFailTotal(self):
|
def getFailTotal(self):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
return self.failTotal
|
return self.__failTotal
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def setMaxRetry(self, value):
|
def setMaxRetry(self, value):
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
self.maxRetry = value
|
self.__maxRetry = value
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def getMaxRetry(self):
|
def getMaxRetry(self):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
return self.maxRetry
|
return self.__maxRetry
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def setMaxTime(self, value):
|
def setMaxTime(self, value):
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
self.maxTime = value
|
self.__maxTime = value
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def getMaxTime(self):
|
def getMaxTime(self):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
return self.maxTime
|
return self.__maxTime
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def addFailure(self, ticket):
|
def addFailure(self, ticket):
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
ip = ticket.getIP()
|
ip = ticket.getIP()
|
||||||
unixTime = ticket.getTime()
|
unixTime = ticket.getTime()
|
||||||
if self.failList.has_key(ip):
|
if self.__failList.has_key(ip):
|
||||||
fData = self.failList[ip]
|
fData = self.__failList[ip]
|
||||||
fData.inc()
|
fData.inc()
|
||||||
fData.setLastTime(unixTime)
|
fData.setLastTime(unixTime)
|
||||||
else:
|
else:
|
||||||
fData = FailData()
|
fData = FailData()
|
||||||
fData.inc()
|
fData.inc()
|
||||||
fData.setLastTime(unixTime)
|
fData.setLastTime(unixTime)
|
||||||
self.failList[ip] = fData
|
self.__failList[ip] = fData
|
||||||
self.failTotal += 1
|
self.__failTotal += 1
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def size(self):
|
def size(self):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
return len(self.failList)
|
return len(self.__failList)
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def cleanup(self, time):
|
def cleanup(self, time):
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
tmp = self.failList.copy()
|
tmp = self.__failList.copy()
|
||||||
for item in tmp:
|
for item in tmp:
|
||||||
if tmp[item].getLastTime() < time - self.maxTime:
|
if tmp[item].getLastTime() < time - self.__maxTime:
|
||||||
self.__delFailure(item)
|
self.__delFailure(item)
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def __delFailure(self, ip):
|
def __delFailure(self, ip):
|
||||||
if self.failList.has_key(ip):
|
if self.__failList.has_key(ip):
|
||||||
del self.failList[ip]
|
del self.__failList[ip]
|
||||||
|
|
||||||
def toBan(self):
|
def toBan(self):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
for ip in self.failList:
|
for ip in self.__failList:
|
||||||
data = self.failList[ip]
|
data = self.__failList[ip]
|
||||||
if data.getRetry() >= self.maxRetry:
|
if data.getRetry() >= self.__maxRetry:
|
||||||
self.__delFailure(ip)
|
self.__delFailure(ip)
|
||||||
# Create a FailTicket from BanData
|
# Create a FailTicket from BanData
|
||||||
failTicket = FailTicket(ip, data.getLastTime())
|
failTicket = FailTicket(ip, data.getLastTime())
|
||||||
|
@ -125,7 +125,7 @@ class FailManager:
|
||||||
return failTicket
|
return failTicket
|
||||||
raise FailManagerEmpty
|
raise FailManagerEmpty
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
class FailManagerEmpty(Exception):
|
class FailManagerEmpty(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
|
@ -293,7 +293,7 @@ class Filter(JailThread):
|
||||||
# and reset the position to 0 in that case. Use the log message
|
# and reset the position to 0 in that case. Use the log message
|
||||||
# timestamp in order to detect this.
|
# timestamp in order to detect this.
|
||||||
|
|
||||||
def setFilePos(self):
|
def __setFilePos(self):
|
||||||
line = self.crtHandler.readline()
|
line = self.crtHandler.readline()
|
||||||
lastDate = self.lastDate[self.crtFilename]
|
lastDate = self.lastDate[self.crtFilename]
|
||||||
lineDate = self.dateDetector.getUnixTime(line)
|
lineDate = self.dateDetector.getUnixTime(line)
|
||||||
|
@ -309,7 +309,7 @@ class Filter(JailThread):
|
||||||
##
|
##
|
||||||
# Get the file position.
|
# Get the file position.
|
||||||
|
|
||||||
def getFilePos(self):
|
def __getFilePos(self):
|
||||||
return self.crtHandler.tell()
|
return self.crtHandler.tell()
|
||||||
|
|
||||||
##
|
##
|
||||||
|
@ -319,11 +319,11 @@ class Filter(JailThread):
|
||||||
# time.time()-self.findTime. When a failure is detected, a FailTicket
|
# time.time()-self.findTime. When a failure is detected, a FailTicket
|
||||||
# is created and is added to the FailManager.
|
# is created and is added to the FailManager.
|
||||||
|
|
||||||
def getFailures(self, filename):
|
def __getFailures(self, filename):
|
||||||
ipList = dict()
|
ipList = dict()
|
||||||
logSys.debug(filename)
|
logSys.debug(filename)
|
||||||
self.openLogFile(filename)
|
self.openLogFile(filename)
|
||||||
self.setFilePos()
|
self.__setFilePos()
|
||||||
lastLine = None
|
lastLine = None
|
||||||
for line in self.crtHandler:
|
for line in self.crtHandler:
|
||||||
try:
|
try:
|
||||||
|
@ -347,7 +347,7 @@ class Filter(JailThread):
|
||||||
continue
|
continue
|
||||||
logSys.debug("Found "+ip)
|
logSys.debug("Found "+ip)
|
||||||
self.failManager.addFailure(FailTicket(ip, unixTime))
|
self.failManager.addFailure(FailTicket(ip, unixTime))
|
||||||
self.lastPos[filename] = self.getFilePos()
|
self.lastPos[filename] = self.__getFilePos()
|
||||||
if lastLine:
|
if lastLine:
|
||||||
self.lastDate[filename] = self.dateDetector.getTime(lastLine)
|
self.lastDate[filename] = self.dateDetector.getTime(lastLine)
|
||||||
self.closeLogFile()
|
self.closeLogFile()
|
||||||
|
|
|
@ -61,7 +61,7 @@ class FilterGamin(Filter):
|
||||||
logSys.debug("Got event: " + `event` + " for " + path)
|
logSys.debug("Got event: " + `event` + " for " + path)
|
||||||
if event in (gamin.GAMCreated, gamin.GAMChanged, gamin.GAMExists):
|
if event in (gamin.GAMCreated, gamin.GAMChanged, gamin.GAMExists):
|
||||||
logSys.debug("File changed: " + path)
|
logSys.debug("File changed: " + path)
|
||||||
self.getFailures(path)
|
self.__getFailures(path)
|
||||||
self.modified = True
|
self.modified = True
|
||||||
|
|
||||||
|
|
||||||
|
@ -72,11 +72,11 @@ class FilterGamin(Filter):
|
||||||
|
|
||||||
def addLogPath(self, path):
|
def addLogPath(self, path):
|
||||||
try:
|
try:
|
||||||
self.logPath.index(path)
|
self.getLogPath().index(path)
|
||||||
logSys.error(path + " already exists")
|
logSys.error(path + " already exists")
|
||||||
except ValueError:
|
except ValueError:
|
||||||
self.monitor.watch_file(path, self.callback)
|
self.monitor.watch_file(path, self.callback)
|
||||||
self.logPath.append(path)
|
self.getLogPath().append(path)
|
||||||
# Initialize default values
|
# Initialize default values
|
||||||
self.lastDate[path] = 0
|
self.lastDate[path] = 0
|
||||||
self.lastModTime[path] = 0
|
self.lastModTime[path] = 0
|
||||||
|
@ -91,7 +91,7 @@ class FilterGamin(Filter):
|
||||||
def delLogPath(self, path):
|
def delLogPath(self, path):
|
||||||
try:
|
try:
|
||||||
self.monitor.stop_watch(path)
|
self.monitor.stop_watch(path)
|
||||||
self.logPath.remove(path)
|
self.getLogPath().remove(path)
|
||||||
del self.lastDate[path]
|
del self.lastDate[path]
|
||||||
del self.lastModTime[path]
|
del self.lastModTime[path]
|
||||||
del self.lastPos[path]
|
del self.lastPos[path]
|
||||||
|
@ -110,7 +110,7 @@ class FilterGamin(Filter):
|
||||||
def run(self):
|
def run(self):
|
||||||
self.setActive(True)
|
self.setActive(True)
|
||||||
while self.isActive():
|
while self.isActive():
|
||||||
if not self.isIdle:
|
if not self.getIdle():
|
||||||
# We cannot block here because we want to be able to
|
# We cannot block here because we want to be able to
|
||||||
# exit.
|
# exit.
|
||||||
if self.monitor.event_pending():
|
if self.monitor.event_pending():
|
||||||
|
@ -124,8 +124,8 @@ class FilterGamin(Filter):
|
||||||
self.failManager.cleanup(time.time())
|
self.failManager.cleanup(time.time())
|
||||||
self.dateDetector.sortTemplate()
|
self.dateDetector.sortTemplate()
|
||||||
self.modified = False
|
self.modified = False
|
||||||
time.sleep(self.sleepTime)
|
time.sleep(self.getSleepTime())
|
||||||
else:
|
else:
|
||||||
time.sleep(self.sleepTime)
|
time.sleep(self.getSleepTime())
|
||||||
logSys.debug(self.jail.getName() + ": filter terminated")
|
logSys.debug(self.jail.getName() + ": filter terminated")
|
||||||
return True
|
return True
|
||||||
|
|
|
@ -53,7 +53,7 @@ class FilterPoll(Filter):
|
||||||
def __init__(self, jail):
|
def __init__(self, jail):
|
||||||
Filter.__init__(self, jail)
|
Filter.__init__(self, jail)
|
||||||
|
|
||||||
self.file404Cnt = dict()
|
self.__file404Cnt = dict()
|
||||||
|
|
||||||
logSys.info("Created FilterPoll")
|
logSys.info("Created FilterPoll")
|
||||||
|
|
||||||
|
@ -64,15 +64,15 @@ class FilterPoll(Filter):
|
||||||
|
|
||||||
def addLogPath(self, path):
|
def addLogPath(self, path):
|
||||||
try:
|
try:
|
||||||
self.logPath.index(path)
|
self.getLogPath().index(path)
|
||||||
logSys.error(path + " already exists")
|
logSys.error(path + " already exists")
|
||||||
except ValueError:
|
except ValueError:
|
||||||
self.logPath.append(path)
|
self.getLogPath().append(path)
|
||||||
# Initialize default values
|
# Initialize default values
|
||||||
self.lastDate[path] = 0
|
self.lastDate[path] = 0
|
||||||
self.lastModTime[path] = 0
|
self.lastModTime[path] = 0
|
||||||
self.lastPos[path] = 0
|
self.lastPos[path] = 0
|
||||||
self.file404Cnt[path] = 0
|
self.__file404Cnt[path] = 0
|
||||||
logSys.info("Added logfile = %s" % path)
|
logSys.info("Added logfile = %s" % path)
|
||||||
|
|
||||||
##
|
##
|
||||||
|
@ -82,11 +82,11 @@ class FilterPoll(Filter):
|
||||||
|
|
||||||
def delLogPath(self, path):
|
def delLogPath(self, path):
|
||||||
try:
|
try:
|
||||||
self.logPath.remove(path)
|
self.getLogPath().remove(path)
|
||||||
del self.lastDate[path]
|
del self.lastDate[path]
|
||||||
del self.lastModTime[path]
|
del self.lastModTime[path]
|
||||||
del self.lastPos[path]
|
del self.lastPos[path]
|
||||||
del self.file404Cnt[path]
|
del self.__file404Cnt[path]
|
||||||
logSys.info("Removed logfile = %s" % path)
|
logSys.info("Removed logfile = %s" % path)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
logSys.error(path + " is not monitored")
|
logSys.error(path + " is not monitored")
|
||||||
|
@ -102,11 +102,11 @@ class FilterPoll(Filter):
|
||||||
def run(self):
|
def run(self):
|
||||||
self.setActive(True)
|
self.setActive(True)
|
||||||
while self.isActive():
|
while self.isActive():
|
||||||
if not self.isIdle:
|
if not self.getIdle():
|
||||||
# Get file modification
|
# Get file modification
|
||||||
for file in self.logPath:
|
for file in self.getLogPath():
|
||||||
if self.isModified(file):
|
if self.isModified(file):
|
||||||
self.getFailures(file)
|
self.__getFailures(file)
|
||||||
prevModified = True
|
prevModified = True
|
||||||
|
|
||||||
if self.modified:
|
if self.modified:
|
||||||
|
@ -117,9 +117,9 @@ class FilterPoll(Filter):
|
||||||
self.failManager.cleanup(time.time())
|
self.failManager.cleanup(time.time())
|
||||||
self.dateDetector.sortTemplate()
|
self.dateDetector.sortTemplate()
|
||||||
prevModified = False
|
prevModified = False
|
||||||
time.sleep(self.sleepTime)
|
time.sleep(self.getSleepTime())
|
||||||
else:
|
else:
|
||||||
time.sleep(self.sleepTime)
|
time.sleep(self.getSleepTime())
|
||||||
logSys.debug(self.jail.getName() + ": filter terminated")
|
logSys.debug(self.jail.getName() + ": filter terminated")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
@ -132,7 +132,7 @@ class FilterPoll(Filter):
|
||||||
def isModified(self, filename):
|
def isModified(self, filename):
|
||||||
try:
|
try:
|
||||||
logStats = os.stat(filename)
|
logStats = os.stat(filename)
|
||||||
self.file404Cnt[filename] = 0
|
self.__file404Cnt[filename] = 0
|
||||||
if self.lastModTime[filename] == logStats.st_mtime:
|
if self.lastModTime[filename] == logStats.st_mtime:
|
||||||
return False
|
return False
|
||||||
else:
|
else:
|
||||||
|
@ -141,9 +141,9 @@ class FilterPoll(Filter):
|
||||||
return True
|
return True
|
||||||
except OSError:
|
except OSError:
|
||||||
logSys.error("Unable to get stat on " + filename)
|
logSys.error("Unable to get stat on " + filename)
|
||||||
self.file404Cnt[filename] = self.file404Cnt[filename] + 1
|
self.__file404Cnt[filename] = self.__file404Cnt[filename] + 1
|
||||||
if self.file404Cnt[filename] > 2:
|
if self.__file404Cnt[filename] > 2:
|
||||||
logSys.warn("Too much read error. Set the jail idle")
|
logSys.warn("Too much read error. Set the jail idle")
|
||||||
self.jail.setIdle(True)
|
self.jail.setIdle(True)
|
||||||
self.file404Cnt[filename] = 0
|
self.__file404Cnt[filename] = 0
|
||||||
return False
|
return False
|
||||||
|
|
110
server/jail.py
110
server/jail.py
|
@ -35,114 +35,114 @@ logSys = logging.getLogger("fail2ban.jail")
|
||||||
class Jail:
|
class Jail:
|
||||||
|
|
||||||
def __init__(self, name):
|
def __init__(self, name):
|
||||||
self.lock = Lock()
|
self.__lock = Lock()
|
||||||
self.name = name
|
self.__name = name
|
||||||
self.queue = Queue.Queue()
|
self.__queue = Queue.Queue()
|
||||||
try:
|
try:
|
||||||
import gamin
|
import gamin
|
||||||
logSys.info("Gamin available. Using it instead of poller")
|
logSys.info("Gamin available. Using it instead of poller")
|
||||||
from filtergamin import FilterGamin
|
from filtergamin import FilterGamin
|
||||||
self.filter = FilterGamin(self)
|
self.__filter = FilterGamin(self)
|
||||||
except ImportError:
|
except ImportError:
|
||||||
logSys.info("Gamin not available. Using poller")
|
logSys.info("Gamin not available. Using poller")
|
||||||
from filterpoll import FilterPoll
|
from filterpoll import FilterPoll
|
||||||
self.filter = FilterPoll(self)
|
self.__filter = FilterPoll(self)
|
||||||
self.action = Actions(self)
|
self.__action = Actions(self)
|
||||||
|
|
||||||
def setName(self, name):
|
def setName(self, name):
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
self.name = name
|
self.__name = name
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def getName(self):
|
def getName(self):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
return self.name
|
return self.__name
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def setFilter(self, filter):
|
def setFilter(self, filter):
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
self.filter = filter
|
self.__filter = filter
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def getFilter(self):
|
def getFilter(self):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
return self.filter
|
return self.__filter
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def setAction(self, action):
|
def setAction(self, action):
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
self.action = action
|
self.__action = action
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def getAction(self):
|
def getAction(self):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
return self.action
|
return self.__action
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def putFailTicket(self, ticket):
|
def putFailTicket(self, ticket):
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
self.queue.put(ticket)
|
self.__queue.put(ticket)
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def getFailTicket(self):
|
def getFailTicket(self):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
try:
|
try:
|
||||||
return self.queue.get(False)
|
return self.__queue.get(False)
|
||||||
except Queue.Empty:
|
except Queue.Empty:
|
||||||
return False
|
return False
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def start(self):
|
def start(self):
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
self.filter.start()
|
self.__filter.start()
|
||||||
self.action.start()
|
self.__action.start()
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def stop(self):
|
def stop(self):
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
self.filter.stop()
|
self.__filter.stop()
|
||||||
self.action.stop()
|
self.__action.stop()
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
self.filter.join()
|
self.__filter.join()
|
||||||
self.action.join()
|
self.__action.join()
|
||||||
|
|
||||||
def isActive(self):
|
def isActive(self):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
isActive0 = self.filter.isActive()
|
isActive0 = self.__filter.isActive()
|
||||||
isActive1 = self.action.isActive()
|
isActive1 = self.__action.isActive()
|
||||||
return isActive0 or isActive1
|
return isActive0 or isActive1
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def setIdle(self, value):
|
def setIdle(self, value):
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
self.filter.setIdle(value)
|
self.__filter.setIdle(value)
|
||||||
self.action.setIdle(value)
|
self.__action.setIdle(value)
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def getIdle(self):
|
def getIdle(self):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
return self.filter.getIdle() or self.action.getIdle()
|
return self.__filter.getIdle() or self.__action.getIdle()
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def getStatus(self):
|
def getStatus(self):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
fStatus = self.filter.status()
|
fStatus = self.__filter.status()
|
||||||
aStatus = self.action.status()
|
aStatus = self.__action.status()
|
||||||
ret = [("filter", fStatus),
|
ret = [("filter", fStatus),
|
||||||
("action", aStatus)]
|
("action", aStatus)]
|
||||||
return ret
|
return ret
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
|
@ -31,73 +31,73 @@ from threading import Lock
|
||||||
class Jails:
|
class Jails:
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.lock = Lock()
|
self.__lock = Lock()
|
||||||
self.jails = dict()
|
self.__jails = dict()
|
||||||
|
|
||||||
def add(self, name):
|
def add(self, name):
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
if self.jails.has_key(name):
|
if self.__jails.has_key(name):
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
raise DuplicateJailException(name)
|
raise DuplicateJailException(name)
|
||||||
else:
|
else:
|
||||||
self.jails[name] = Jail(name)
|
self.__jails[name] = Jail(name)
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def remove(self, name):
|
def remove(self, name):
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
if self.jails.has_key(name):
|
if self.__jails.has_key(name):
|
||||||
del self.jails[name]
|
del self.__jails[name]
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
else:
|
else:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
raise UnknownJailException(name)
|
raise UnknownJailException(name)
|
||||||
|
|
||||||
def get(self, name):
|
def get(self, name):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
if self.jails.has_key(name):
|
if self.__jails.has_key(name):
|
||||||
jail = self.jails[name]
|
jail = self.__jails[name]
|
||||||
return jail
|
return jail
|
||||||
else:
|
else:
|
||||||
raise UnknownJailException(name)
|
raise UnknownJailException(name)
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def getAction(self, name):
|
def getAction(self, name):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
if self.jails.has_key(name):
|
if self.__jails.has_key(name):
|
||||||
action = self.jails[name].getAction()
|
action = self.__jails[name].getAction()
|
||||||
return action
|
return action
|
||||||
else:
|
else:
|
||||||
raise UnknownJailException(name)
|
raise UnknownJailException(name)
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def getFilter(self, name):
|
def getFilter(self, name):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
if self.jails.has_key(name):
|
if self.__jails.has_key(name):
|
||||||
action = self.jails[name].getFilter()
|
action = self.__jails[name].getFilter()
|
||||||
return action
|
return action
|
||||||
else:
|
else:
|
||||||
raise UnknownJailException(name)
|
raise UnknownJailException(name)
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def getAll(self):
|
def getAll(self):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
return self.jails.copy()
|
return self.__jails.copy()
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
def size(self):
|
def size(self):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
return len(self.jails)
|
return len(self.__jails)
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
|
|
||||||
class DuplicateJailException(Exception):
|
class DuplicateJailException(Exception):
|
||||||
|
|
|
@ -37,11 +37,11 @@ class JailThread(Thread):
|
||||||
def __init__(self, jail):
|
def __init__(self, jail):
|
||||||
Thread.__init__(self)
|
Thread.__init__(self)
|
||||||
## Control the state of the thread.
|
## Control the state of the thread.
|
||||||
self.isRunning = False
|
self.__isRunning = False
|
||||||
## Control the idle state of the thread.
|
## Control the idle state of the thread.
|
||||||
self.isIdle = False
|
self.__isIdle = False
|
||||||
## The time the thread sleeps in the loop.
|
## The time the thread sleeps in the loop.
|
||||||
self.sleepTime = 1
|
self.__sleepTime = 1
|
||||||
|
|
||||||
##
|
##
|
||||||
# Set the time that the thread sleeps.
|
# Set the time that the thread sleeps.
|
||||||
|
@ -51,7 +51,7 @@ class JailThread(Thread):
|
||||||
# @param value the polling time (second)
|
# @param value the polling time (second)
|
||||||
|
|
||||||
def setSleepTime(self, value):
|
def setSleepTime(self, value):
|
||||||
self.sleepTime = value
|
self.__sleepTime = value
|
||||||
logSys.info("Set sleeptime = " + value)
|
logSys.info("Set sleeptime = " + value)
|
||||||
|
|
||||||
##
|
##
|
||||||
|
@ -60,7 +60,7 @@ class JailThread(Thread):
|
||||||
# @return the polling time
|
# @return the polling time
|
||||||
|
|
||||||
def getSleepTime(self):
|
def getSleepTime(self):
|
||||||
return self.sleeptime
|
return self.__sleepTime
|
||||||
|
|
||||||
##
|
##
|
||||||
# Set the idle flag.
|
# Set the idle flag.
|
||||||
|
@ -69,7 +69,7 @@ class JailThread(Thread):
|
||||||
# @param value boolean value
|
# @param value boolean value
|
||||||
|
|
||||||
def setIdle(self, value):
|
def setIdle(self, value):
|
||||||
self.isIdle = value
|
self.__isIdle = value
|
||||||
|
|
||||||
##
|
##
|
||||||
# Get the idle state.
|
# Get the idle state.
|
||||||
|
@ -77,7 +77,7 @@ class JailThread(Thread):
|
||||||
# @return the idle state
|
# @return the idle state
|
||||||
|
|
||||||
def getIdle(self):
|
def getIdle(self):
|
||||||
return self.isIdle
|
return self.__isIdle
|
||||||
|
|
||||||
##
|
##
|
||||||
# Stop the thread.
|
# Stop the thread.
|
||||||
|
@ -85,7 +85,7 @@ class JailThread(Thread):
|
||||||
# Stop the exection of the thread and quit.
|
# Stop the exection of the thread and quit.
|
||||||
|
|
||||||
def stop(self):
|
def stop(self):
|
||||||
self.isRunning = False
|
self.__isRunning = False
|
||||||
|
|
||||||
##
|
##
|
||||||
# Set the isRunning flag.
|
# Set the isRunning flag.
|
||||||
|
@ -93,7 +93,7 @@ class JailThread(Thread):
|
||||||
# @param value True if the thread is running
|
# @param value True if the thread is running
|
||||||
|
|
||||||
def setActive(self, value):
|
def setActive(self, value):
|
||||||
self.isRunning = value
|
self.__isRunning = value
|
||||||
|
|
||||||
##
|
##
|
||||||
# Check if the thread is active.
|
# Check if the thread is active.
|
||||||
|
@ -102,7 +102,7 @@ class JailThread(Thread):
|
||||||
# @return True if the thread is running
|
# @return True if the thread is running
|
||||||
|
|
||||||
def isActive(self):
|
def isActive(self):
|
||||||
return self.isRunning
|
return self.__isRunning
|
||||||
|
|
||||||
##
|
##
|
||||||
# Get the status of the thread
|
# Get the status of the thread
|
||||||
|
|
126
server/server.py
126
server/server.py
|
@ -34,21 +34,21 @@ logSys = logging.getLogger("fail2ban.server")
|
||||||
class Server:
|
class Server:
|
||||||
|
|
||||||
def __init__(self, daemon = False):
|
def __init__(self, daemon = False):
|
||||||
self.jails = Jails()
|
self.__jails = Jails()
|
||||||
self.daemon = daemon
|
self.__daemon = daemon
|
||||||
self.transm = Transmitter(self)
|
self.__transm = Transmitter(self)
|
||||||
self.logLevel = 3
|
self.__logLevel = 3
|
||||||
self.logTarget = "STDOUT"
|
self.__logTarget = "STDOUT"
|
||||||
# Set logging level
|
# Set logging level
|
||||||
self.setLogLevel(self.logLevel)
|
self.setLogLevel(self.__logLevel)
|
||||||
self.setLogTarget(self.logTarget)
|
self.setLogTarget(self.__logTarget)
|
||||||
|
|
||||||
def start(self, force):
|
def start(self, force):
|
||||||
logSys.info("Starting Fail2ban")
|
logSys.info("Starting Fail2ban")
|
||||||
# First set the mask to only allow access to owner
|
# First set the mask to only allow access to owner
|
||||||
os.umask(0077)
|
os.umask(0077)
|
||||||
if self.daemon:
|
if self.__daemon:
|
||||||
ret = self.createDaemon()
|
ret = self.__createDaemon()
|
||||||
if ret:
|
if ret:
|
||||||
logSys.info("Daemon started")
|
logSys.info("Daemon started")
|
||||||
else:
|
else:
|
||||||
|
@ -56,166 +56,166 @@ class Server:
|
||||||
raise ServerInitializationError("Could not create daemon")
|
raise ServerInitializationError("Could not create daemon")
|
||||||
# Start the communication
|
# Start the communication
|
||||||
logSys.debug("Starting communication")
|
logSys.debug("Starting communication")
|
||||||
self.transm.start(force)
|
self.__transm.start(force)
|
||||||
logSys.info("Exiting Fail2ban")
|
logSys.info("Exiting Fail2ban")
|
||||||
|
|
||||||
def quit(self):
|
def quit(self):
|
||||||
self.stopAllJail()
|
self.stopAllJail()
|
||||||
self.transm.stop()
|
self.__transm.stop()
|
||||||
|
|
||||||
def addJail(self, name):
|
def addJail(self, name):
|
||||||
self.jails.add(name)
|
self.__jails.add(name)
|
||||||
|
|
||||||
def delJail(self, name):
|
def delJail(self, name):
|
||||||
self.jails.remove(name)
|
self.__jails.remove(name)
|
||||||
|
|
||||||
def startJail(self, name):
|
def startJail(self, name):
|
||||||
if not self.isActive(name):
|
if not self.isActive(name):
|
||||||
self.jails.get(name).start()
|
self.__jails.get(name).start()
|
||||||
|
|
||||||
def stopJail(self, name):
|
def stopJail(self, name):
|
||||||
if self.isActive(name):
|
if self.isActive(name):
|
||||||
self.jails.get(name).stop()
|
self.__jails.get(name).stop()
|
||||||
self.delJail(name)
|
self.delJail(name)
|
||||||
|
|
||||||
def stopAllJail(self):
|
def stopAllJail(self):
|
||||||
for jail in self.jails.getAll():
|
for jail in self.__jails.getAll():
|
||||||
self.stopJail(jail)
|
self.stopJail(jail)
|
||||||
|
|
||||||
def isActive(self, name):
|
def isActive(self, name):
|
||||||
return self.jails.get(name).isActive()
|
return self.__jails.get(name).isActive()
|
||||||
|
|
||||||
def setIdleJail(self, name, value):
|
def setIdleJail(self, name, value):
|
||||||
self.jails.get(name).setIdle(value)
|
self.__jails.get(name).setIdle(value)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def getIdleJail(self, name):
|
def getIdleJail(self, name):
|
||||||
return self.jails.get(name).getIdle()
|
return self.__jails.get(name).getIdle()
|
||||||
|
|
||||||
# Filter
|
# Filter
|
||||||
def addIgnoreIP(self, name, ip):
|
def addIgnoreIP(self, name, ip):
|
||||||
self.jails.getFilter(name).addIgnoreIP(ip)
|
self.__jails.getFilter(name).addIgnoreIP(ip)
|
||||||
|
|
||||||
def delIgnoreIP(self, name, ip):
|
def delIgnoreIP(self, name, ip):
|
||||||
self.jails.getFilter(name).delIgnoreIP(ip)
|
self.__jails.getFilter(name).delIgnoreIP(ip)
|
||||||
|
|
||||||
def getIgnoreIP(self, name):
|
def getIgnoreIP(self, name):
|
||||||
return self.jails.getFilter(name).getIgnoreIP()
|
return self.__jails.getFilter(name).getIgnoreIP()
|
||||||
|
|
||||||
def addLogPath(self, name, file):
|
def addLogPath(self, name, file):
|
||||||
self.jails.getFilter(name).addLogPath(file)
|
self.__jails.getFilter(name).addLogPath(file)
|
||||||
|
|
||||||
def delLogPath(self, name, file):
|
def delLogPath(self, name, file):
|
||||||
self.jails.getFilter(name).delLogPath(file)
|
self.__jails.getFilter(name).delLogPath(file)
|
||||||
|
|
||||||
def getLogPath(self, name):
|
def getLogPath(self, name):
|
||||||
return self.jails.getFilter(name).getLogPath()
|
return self.__jails.getFilter(name).getLogPath()
|
||||||
|
|
||||||
def setTimeRegex(self, name, value):
|
def setTimeRegex(self, name, value):
|
||||||
self.jails.getFilter(name).setTimeRegex(value)
|
self.__jails.getFilter(name).setTimeRegex(value)
|
||||||
|
|
||||||
def getTimeRegex(self, name):
|
def getTimeRegex(self, name):
|
||||||
return self.jails.getFilter(name).getTimeRegex()
|
return self.__jails.getFilter(name).getTimeRegex()
|
||||||
|
|
||||||
def setTimePattern(self, name, value):
|
def setTimePattern(self, name, value):
|
||||||
self.jails.getFilter(name).setTimePattern(value)
|
self.__jails.getFilter(name).setTimePattern(value)
|
||||||
|
|
||||||
def getTimePattern(self, name):
|
def getTimePattern(self, name):
|
||||||
return self.jails.getFilter(name).getTimePattern()
|
return self.__jails.getFilter(name).getTimePattern()
|
||||||
|
|
||||||
def setFindTime(self, name, value):
|
def setFindTime(self, name, value):
|
||||||
self.jails.getFilter(name).setFindTime(value)
|
self.__jails.getFilter(name).setFindTime(value)
|
||||||
|
|
||||||
def getFindTime(self):
|
def getFindTime(self):
|
||||||
return self.jails.getFilter(name).getFindTime()
|
return self.__jails.getFilter(name).getFindTime()
|
||||||
|
|
||||||
def setFailRegex(self, name, value):
|
def setFailRegex(self, name, value):
|
||||||
self.jails.getFilter(name).setFailRegex(value)
|
self.__jails.getFilter(name).setFailRegex(value)
|
||||||
|
|
||||||
def getFailRegex(self, name):
|
def getFailRegex(self, name):
|
||||||
return self.jails.getFilter(name).getFailRegex()
|
return self.__jails.getFilter(name).getFailRegex()
|
||||||
|
|
||||||
def setMaxRetry(self, name, value):
|
def setMaxRetry(self, name, value):
|
||||||
self.jails.getFilter(name).setMaxRetry(value)
|
self.__jails.getFilter(name).setMaxRetry(value)
|
||||||
|
|
||||||
def getMaxRetry(self, name):
|
def getMaxRetry(self, name):
|
||||||
return self.jails.getFilter(name).getMaxRetry()
|
return self.__jails.getFilter(name).getMaxRetry()
|
||||||
|
|
||||||
def setMaxTime(self, name, value):
|
def setMaxTime(self, name, value):
|
||||||
self.jails.getFilter(name).setMaxTime(value)
|
self.__jails.getFilter(name).setMaxTime(value)
|
||||||
|
|
||||||
def getMaxTime(self, name):
|
def getMaxTime(self, name):
|
||||||
return self.jails.getFilter(name).getMaxTime()
|
return self.__jails.getFilter(name).getMaxTime()
|
||||||
|
|
||||||
# Action
|
# Action
|
||||||
def addAction(self, name, value):
|
def addAction(self, name, value):
|
||||||
self.jails.getAction(name).addAction(value)
|
self.__jails.getAction(name).addAction(value)
|
||||||
|
|
||||||
def getLastAction(self, name):
|
def getLastAction(self, name):
|
||||||
return self.jails.getAction(name).getLastAction()
|
return self.__jails.getAction(name).getLastAction()
|
||||||
|
|
||||||
def delAction(self, name, value):
|
def delAction(self, name, value):
|
||||||
self.jails.getAction(name).delAction(value)
|
self.__jails.getAction(name).delAction(value)
|
||||||
|
|
||||||
def setCInfo(self, name, action, key, value):
|
def setCInfo(self, name, action, key, value):
|
||||||
self.jails.getAction(name).getAction(action).setCInfo(key, value)
|
self.__jails.getAction(name).getAction(action).setCInfo(key, value)
|
||||||
|
|
||||||
def getCInfo(self, name, action, key):
|
def getCInfo(self, name, action, key):
|
||||||
return self.jails.getAction(name).getAction(action).getCInfo(key)
|
return self.__jails.getAction(name).getAction(action).getCInfo(key)
|
||||||
|
|
||||||
def delCInfo(self, name, action, key):
|
def delCInfo(self, name, action, key):
|
||||||
self.jails.getAction(name).getAction(action).delCInfo(key)
|
self.__jails.getAction(name).getAction(action).delCInfo(key)
|
||||||
|
|
||||||
def setBanTime(self, name, value):
|
def setBanTime(self, name, value):
|
||||||
self.jails.getAction(name).setBanTime(value)
|
self.__jails.getAction(name).setBanTime(value)
|
||||||
|
|
||||||
def getBanTime(self, name):
|
def getBanTime(self, name):
|
||||||
return self.jails.getAction(name).getBanTime()
|
return self.__jails.getAction(name).getBanTime()
|
||||||
|
|
||||||
def setActionStart(self, name, action, value):
|
def setActionStart(self, name, action, value):
|
||||||
self.jails.getAction(name).getAction(action).setActionStart(value)
|
self.__jails.getAction(name).getAction(action).setActionStart(value)
|
||||||
|
|
||||||
def getActionStart(self, name, action):
|
def getActionStart(self, name, action):
|
||||||
return self.jails.getAction(name).getAction(action).getActionStart()
|
return self.__jails.getAction(name).getAction(action).getActionStart()
|
||||||
|
|
||||||
def setActionStop(self, name, action, value):
|
def setActionStop(self, name, action, value):
|
||||||
self.jails.getAction(name).getAction(action).setActionStop(value)
|
self.__jails.getAction(name).getAction(action).setActionStop(value)
|
||||||
|
|
||||||
def getActionStop(self, name, action):
|
def getActionStop(self, name, action):
|
||||||
return self.jails.getAction(name).getAction(action).getActionStop()
|
return self.__jails.getAction(name).getAction(action).getActionStop()
|
||||||
|
|
||||||
def setActionCheck(self, name, action, value):
|
def setActionCheck(self, name, action, value):
|
||||||
self.jails.getAction(name).getAction(action).setActionCheck(value)
|
self.__jails.getAction(name).getAction(action).setActionCheck(value)
|
||||||
|
|
||||||
def getActionCheck(self, name, action):
|
def getActionCheck(self, name, action):
|
||||||
return self.jails.getAction(name).getAction(action).getActionCheck()
|
return self.__jails.getAction(name).getAction(action).getActionCheck()
|
||||||
|
|
||||||
def setActionBan(self, name, action, value):
|
def setActionBan(self, name, action, value):
|
||||||
self.jails.getAction(name).getAction(action).setActionBan(value)
|
self.__jails.getAction(name).getAction(action).setActionBan(value)
|
||||||
|
|
||||||
def getActionBan(self, name, action):
|
def getActionBan(self, name, action):
|
||||||
return self.jails.getAction(name).getAction(action).getActionBan()
|
return self.__jails.getAction(name).getAction(action).getActionBan()
|
||||||
|
|
||||||
def setActionUnban(self, name, action, value):
|
def setActionUnban(self, name, action, value):
|
||||||
self.jails.getAction(name).getAction(action).setActionUnban(value)
|
self.__jails.getAction(name).getAction(action).setActionUnban(value)
|
||||||
|
|
||||||
def getActionUnban(self, name, action):
|
def getActionUnban(self, name, action):
|
||||||
return self.jails.getAction(name).getAction(action).getActionUnban()
|
return self.__jails.getAction(name).getAction(action).getActionUnban()
|
||||||
|
|
||||||
# Status
|
# Status
|
||||||
def status(self):
|
def status(self):
|
||||||
jailList = ''
|
jailList = ''
|
||||||
for jail in self.jails.getAll():
|
for jail in self.__jails.getAll():
|
||||||
jailList += jail + ', '
|
jailList += jail + ', '
|
||||||
length = len(jailList)
|
length = len(jailList)
|
||||||
if not length == 0:
|
if not length == 0:
|
||||||
jailList = jailList[:length-2]
|
jailList = jailList[:length-2]
|
||||||
ret = [("Number of jail", self.jails.size()),
|
ret = [("Number of jail", self.__jails.size()),
|
||||||
("Jail list", jailList)]
|
("Jail list", jailList)]
|
||||||
return ret
|
return ret
|
||||||
|
|
||||||
def statusJail(self, name):
|
def statusJail(self, name):
|
||||||
return self.jails.get(name).getStatus()
|
return self.__jails.get(name).getStatus()
|
||||||
|
|
||||||
# Logging
|
# Logging
|
||||||
|
|
||||||
|
@ -231,7 +231,7 @@ class Server:
|
||||||
# @param value the level
|
# @param value the level
|
||||||
|
|
||||||
def setLogLevel(self, value):
|
def setLogLevel(self, value):
|
||||||
self.logLevel = value
|
self.__logLevel = value
|
||||||
logLevel = logging.DEBUG
|
logLevel = logging.DEBUG
|
||||||
if value == 0:
|
if value == 0:
|
||||||
logLevel = logging.FATAL
|
logLevel = logging.FATAL
|
||||||
|
@ -250,12 +250,12 @@ class Server:
|
||||||
# @return the log level
|
# @return the log level
|
||||||
|
|
||||||
def getLogLevel(self):
|
def getLogLevel(self):
|
||||||
return self.logLevel
|
return self.__logLevel
|
||||||
|
|
||||||
def setLogTarget(self, target):
|
def setLogTarget(self, target):
|
||||||
# Remove previous handler
|
# Remove previous handler
|
||||||
logging.getLogger("fail2ban").handlers = []
|
logging.getLogger("fail2ban").handlers = []
|
||||||
self.logTarget = target
|
self.__logTarget = target
|
||||||
if target == "SYSLOG":
|
if target == "SYSLOG":
|
||||||
hdlr = logging.handlers.SysLogHandler()
|
hdlr = logging.handlers.SysLogHandler()
|
||||||
elif target == "STDOUT":
|
elif target == "STDOUT":
|
||||||
|
@ -278,9 +278,9 @@ class Server:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def getLogTarget(self):
|
def getLogTarget(self):
|
||||||
return self.logTarget
|
return self.__logTarget
|
||||||
|
|
||||||
def createDaemon(self):
|
def __createDaemon(self):
|
||||||
""" Detach a process from the controlling terminal and run it in the
|
""" Detach a process from the controlling terminal and run it in the
|
||||||
background as a daemon.
|
background as a daemon.
|
||||||
|
|
||||||
|
|
|
@ -37,8 +37,8 @@ class SSocket(Thread):
|
||||||
|
|
||||||
def __init__(self, transmitter):
|
def __init__(self, transmitter):
|
||||||
Thread.__init__(self)
|
Thread.__init__(self)
|
||||||
self.transmit = transmitter
|
self.__transmit = transmitter
|
||||||
self.isRunning = False
|
self.__isRunning = False
|
||||||
logSys.debug("Created SSocket")
|
logSys.debug("Created SSocket")
|
||||||
|
|
||||||
def initialize(self, force = False):
|
def initialize(self, force = False):
|
||||||
|
@ -66,11 +66,11 @@ class SSocket(Thread):
|
||||||
self.ssock.listen(5)
|
self.ssock.listen(5)
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
self.isRunning = True
|
self.__isRunning = True
|
||||||
while self.isRunning:
|
while self.__isRunning:
|
||||||
try:
|
try:
|
||||||
(csock, address) = self.ssock.accept()
|
(csock, address) = self.ssock.accept()
|
||||||
thread = SocketWorker(csock, self.transmit)
|
thread = SocketWorker(csock, self.__transmit)
|
||||||
thread.start()
|
thread.start()
|
||||||
except socket.timeout:
|
except socket.timeout:
|
||||||
# Do nothing here
|
# Do nothing here
|
||||||
|
@ -90,29 +90,29 @@ class SSocket(Thread):
|
||||||
# @bug It seems to be some concurrency problem with this flag
|
# @bug It seems to be some concurrency problem with this flag
|
||||||
|
|
||||||
def stop(self):
|
def stop(self):
|
||||||
self.isRunning = False
|
self.__isRunning = False
|
||||||
|
|
||||||
|
|
||||||
class SocketWorker(Thread):
|
class SocketWorker(Thread):
|
||||||
|
|
||||||
def __init__(self, csock, transmitter):
|
def __init__(self, csock, transmitter):
|
||||||
Thread.__init__(self)
|
Thread.__init__(self)
|
||||||
self.csock = csock
|
self.__csock = csock
|
||||||
self.transmit = transmitter
|
self.__transmit = transmitter
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
logSys.debug("Starting new thread to handle the request")
|
logSys.debug("Starting new thread to handle the request")
|
||||||
msg = self.receive(self.csock)
|
msg = self.__receive(self.__csock)
|
||||||
msg = self.transmit.proceed(msg)
|
msg = self.__transmit.proceed(msg)
|
||||||
self.send(self.csock, msg)
|
self.__send(self.__csock, msg)
|
||||||
self.csock.close()
|
self.__csock.close()
|
||||||
logSys.debug("Connection closed")
|
logSys.debug("Connection closed")
|
||||||
|
|
||||||
def send(self, socket, msg):
|
def __send(self, socket, msg):
|
||||||
obj = pickle.dumps(msg)
|
obj = pickle.dumps(msg)
|
||||||
socket.send(obj + SSocket.END_STRING)
|
socket.send(obj + SSocket.END_STRING)
|
||||||
|
|
||||||
def receive(self, socket):
|
def __receive(self, socket):
|
||||||
msg = ''
|
msg = ''
|
||||||
while msg.rfind(SSocket.END_STRING) == -1:
|
while msg.rfind(SSocket.END_STRING) == -1:
|
||||||
chunk = socket.recv(6)
|
chunk = socket.recv(6)
|
||||||
|
|
|
@ -32,25 +32,25 @@ logSys = logging.getLogger("fail2ban")
|
||||||
class Ticket:
|
class Ticket:
|
||||||
|
|
||||||
def __init__(self, ip, time):
|
def __init__(self, ip, time):
|
||||||
self.ip = ip
|
self.__ip = ip
|
||||||
self.time = time
|
self.__time = time
|
||||||
self.attempt = 0
|
self.__attempt = 0
|
||||||
|
|
||||||
def setIP(self, value):
|
def setIP(self, value):
|
||||||
self.ip = value
|
self.__ip = value
|
||||||
|
|
||||||
def getIP(self):
|
def getIP(self):
|
||||||
return self.ip
|
return self.__ip
|
||||||
|
|
||||||
def setTime(self, value):
|
def setTime(self, value):
|
||||||
self.time = value
|
self.__time = value
|
||||||
|
|
||||||
def getTime(self):
|
def getTime(self):
|
||||||
return self.time
|
return self.__time
|
||||||
|
|
||||||
def setAttempt(self, value):
|
def setAttempt(self, value):
|
||||||
self.attempt = value
|
self.__attempt = value
|
||||||
|
|
||||||
def getAttempt(self):
|
def getAttempt(self):
|
||||||
return self.attempt
|
return self.__attempt
|
||||||
|
|
|
@ -35,9 +35,9 @@ logSys = logging.getLogger("fail2ban.comm")
|
||||||
class Transmitter:
|
class Transmitter:
|
||||||
|
|
||||||
def __init__(self, server):
|
def __init__(self, server):
|
||||||
self.lock = Lock()
|
self.__lock = Lock()
|
||||||
self.server = server
|
self.__server = server
|
||||||
self.socket = SSocket(self)
|
self.__socket = SSocket(self)
|
||||||
|
|
||||||
##
|
##
|
||||||
# Start the transmittion server.
|
# Start the transmittion server.
|
||||||
|
@ -46,14 +46,14 @@ class Transmitter:
|
||||||
|
|
||||||
def start(self, force):
|
def start(self, force):
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
self.socket.initialize(force)
|
self.__socket.initialize(force)
|
||||||
self.socket.start()
|
self.__socket.start()
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
self.socket.join()
|
self.__socket.join()
|
||||||
except SSocketErrorException:
|
except SSocketErrorException:
|
||||||
logSys.error("Could not start server")
|
logSys.error("Could not start server")
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
##
|
##
|
||||||
# Stop the transmitter.
|
# Stop the transmitter.
|
||||||
|
@ -62,224 +62,224 @@ class Transmitter:
|
||||||
# happen which disappear when using join() in this function.
|
# happen which disappear when using join() in this function.
|
||||||
|
|
||||||
def stop(self):
|
def stop(self):
|
||||||
self.socket.stop()
|
self.__socket.stop()
|
||||||
self.socket.join()
|
self.__socket.join()
|
||||||
|
|
||||||
def proceed(self, action):
|
def proceed(self, action):
|
||||||
# Deserialize object
|
# Deserialize object
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.__lock.acquire()
|
||||||
logSys.debug("Action: " + `action`)
|
logSys.debug("Action: " + `action`)
|
||||||
try:
|
try:
|
||||||
ret = self.actionHandler(action)
|
ret = self.__actionHandler(action)
|
||||||
ack = 0, ret
|
ack = 0, ret
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
logSys.warn("Invalid command: " + `action`)
|
logSys.warn("Invalid command: " + `action`)
|
||||||
ack = 1, e
|
ack = 1, e
|
||||||
return ack
|
return ack
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.__lock.release()
|
||||||
|
|
||||||
##
|
##
|
||||||
# Handle an action.
|
# Handle an action.
|
||||||
#
|
#
|
||||||
#
|
#
|
||||||
|
|
||||||
def actionHandler(self, action):
|
def __actionHandler(self, action):
|
||||||
if action[0] == "ping":
|
if action[0] == "ping":
|
||||||
return "pong"
|
return "pong"
|
||||||
elif action[0] == "add":
|
elif action[0] == "add":
|
||||||
name = action[1]
|
name = action[1]
|
||||||
if name == "all":
|
if name == "all":
|
||||||
raise Exception("Reserved name")
|
raise Exception("Reserved name")
|
||||||
self.server.addJail(name)
|
self.__server.addJail(name)
|
||||||
return name
|
return name
|
||||||
elif action[0] == "start":
|
elif action[0] == "start":
|
||||||
name = action[1]
|
name = action[1]
|
||||||
self.server.startJail(name)
|
self.__server.startJail(name)
|
||||||
return None
|
return None
|
||||||
elif action[0] == "stop":
|
elif action[0] == "stop":
|
||||||
if len(action) == 1:
|
if len(action) == 1:
|
||||||
self.server.quit()
|
self.__server.quit()
|
||||||
elif action[1] == "all":
|
elif action[1] == "all":
|
||||||
self.server.stopAllJail()
|
self.__server.stopAllJail()
|
||||||
else:
|
else:
|
||||||
name = action[1]
|
name = action[1]
|
||||||
self.server.stopJail(name)
|
self.__server.stopJail(name)
|
||||||
return None
|
return None
|
||||||
elif action[0] == "sleep":
|
elif action[0] == "sleep":
|
||||||
value = action[1]
|
value = action[1]
|
||||||
time.sleep(int(value))
|
time.sleep(int(value))
|
||||||
return None
|
return None
|
||||||
elif action[0] == "set":
|
elif action[0] == "set":
|
||||||
return self.actionSet(action[1:])
|
return self.__actionSet(action[1:])
|
||||||
elif action[0] == "get":
|
elif action[0] == "get":
|
||||||
return self.actionGet(action[1:])
|
return self.__actionGet(action[1:])
|
||||||
elif action[0] == "status":
|
elif action[0] == "status":
|
||||||
return self.status(action[1:])
|
return self.status(action[1:])
|
||||||
raise Exception("Invalid command")
|
raise Exception("Invalid command")
|
||||||
|
|
||||||
def actionSet(self, action):
|
def __actionSet(self, action):
|
||||||
name = action[0]
|
name = action[0]
|
||||||
# Logging
|
# Logging
|
||||||
if name == "loglevel":
|
if name == "loglevel":
|
||||||
value = int(action[1])
|
value = int(action[1])
|
||||||
self.server.setLogLevel(value)
|
self.__server.setLogLevel(value)
|
||||||
return self.server.getLogLevel()
|
return self.__server.getLogLevel()
|
||||||
elif name == "logtarget":
|
elif name == "logtarget":
|
||||||
value = action[1]
|
value = action[1]
|
||||||
self.server.setLogTarget(value)
|
self.__server.setLogTarget(value)
|
||||||
return self.server.getLogTarget()
|
return self.__server.getLogTarget()
|
||||||
# Jail
|
# Jail
|
||||||
elif action[1] == "idle":
|
elif action[1] == "idle":
|
||||||
if action[2] == "on":
|
if action[2] == "on":
|
||||||
self.server.setIdleJail(name, True)
|
self.__server.setIdleJail(name, True)
|
||||||
elif action[2] == "off":
|
elif action[2] == "off":
|
||||||
self.server.setIdleJail(name, False)
|
self.__server.setIdleJail(name, False)
|
||||||
return self.server.getIdleJail(name)
|
return self.__server.getIdleJail(name)
|
||||||
# Filter
|
# Filter
|
||||||
elif action[1] == "addignoreip":
|
elif action[1] == "addignoreip":
|
||||||
value = action[2]
|
value = action[2]
|
||||||
self.server.addIgnoreIP(name, value)
|
self.__server.addIgnoreIP(name, value)
|
||||||
return self.server.getIgnoreIP(name)
|
return self.__server.getIgnoreIP(name)
|
||||||
elif action[1] == "delignoreip":
|
elif action[1] == "delignoreip":
|
||||||
value = action[2]
|
value = action[2]
|
||||||
self.server.delIgnoreIP(name, value)
|
self.__server.delIgnoreIP(name, value)
|
||||||
return self.server.getIgnoreIP(name)
|
return self.__server.getIgnoreIP(name)
|
||||||
elif action[1] == "addlogpath":
|
elif action[1] == "addlogpath":
|
||||||
value = action[2:]
|
value = action[2:]
|
||||||
for path in value:
|
for path in value:
|
||||||
self.server.addLogPath(name, path)
|
self.__server.addLogPath(name, path)
|
||||||
return self.server.getLogPath(name)
|
return self.__server.getLogPath(name)
|
||||||
elif action[1] == "dellogpath":
|
elif action[1] == "dellogpath":
|
||||||
value = action[2]
|
value = action[2]
|
||||||
self.server.delLogPath(name, value)
|
self.__server.delLogPath(name, value)
|
||||||
return self.server.getLogPath(name)
|
return self.__server.getLogPath(name)
|
||||||
elif action[1] == "timeregex":
|
elif action[1] == "timeregex":
|
||||||
value = action[2]
|
value = action[2]
|
||||||
self.server.setTimeRegex(name, value)
|
self.__server.setTimeRegex(name, value)
|
||||||
return self.server.getTimeRegex(name)
|
return self.__server.getTimeRegex(name)
|
||||||
elif action[1] == "timepattern":
|
elif action[1] == "timepattern":
|
||||||
value = action[2]
|
value = action[2]
|
||||||
self.server.setTimePattern(name, value)
|
self.__server.setTimePattern(name, value)
|
||||||
return self.server.getTimePattern(name)
|
return self.__server.getTimePattern(name)
|
||||||
elif action[1] == "failregex":
|
elif action[1] == "failregex":
|
||||||
value = action[2]
|
value = action[2]
|
||||||
self.server.setFailRegex(name, value)
|
self.__server.setFailRegex(name, value)
|
||||||
return self.server.getFailRegex(name)
|
return self.__server.getFailRegex(name)
|
||||||
elif action[1] == "maxtime":
|
elif action[1] == "maxtime":
|
||||||
value = action[2]
|
value = action[2]
|
||||||
self.server.setMaxTime(name, int(value))
|
self.__server.setMaxTime(name, int(value))
|
||||||
return self.server.getMaxTime(name)
|
return self.__server.getMaxTime(name)
|
||||||
elif action[1] == "findtime":
|
elif action[1] == "findtime":
|
||||||
value = action[2]
|
value = action[2]
|
||||||
self.server.setFindTime(name, int(value))
|
self.__server.setFindTime(name, int(value))
|
||||||
return self.server.getFindTime(name)
|
return self.__server.getFindTime(name)
|
||||||
elif action[1] == "maxretry":
|
elif action[1] == "maxretry":
|
||||||
value = action[2]
|
value = action[2]
|
||||||
self.server.setMaxRetry(name, int(value))
|
self.__server.setMaxRetry(name, int(value))
|
||||||
return self.server.getMaxRetry(name)
|
return self.__server.getMaxRetry(name)
|
||||||
# Action
|
# Action
|
||||||
elif action[1] == "bantime":
|
elif action[1] == "bantime":
|
||||||
value = action[2]
|
value = action[2]
|
||||||
self.server.setBanTime(name, int(value))
|
self.__server.setBanTime(name, int(value))
|
||||||
return self.server.getBanTime(name)
|
return self.__server.getBanTime(name)
|
||||||
elif action[1] == "addaction":
|
elif action[1] == "addaction":
|
||||||
value = action[2]
|
value = action[2]
|
||||||
self.server.addAction(name, value)
|
self.__server.addAction(name, value)
|
||||||
return self.server.getLastAction(name).getName()
|
return self.__server.getLastAction(name).getName()
|
||||||
elif action[1] == "delaction":
|
elif action[1] == "delaction":
|
||||||
self.server.delAction(name, value)
|
self.__server.delAction(name, value)
|
||||||
return None
|
return None
|
||||||
elif action[1] == "setcinfo":
|
elif action[1] == "setcinfo":
|
||||||
act = action[2]
|
act = action[2]
|
||||||
key = action[3]
|
key = action[3]
|
||||||
value = action[4]
|
value = action[4]
|
||||||
self.server.setCInfo(name, act, key, value)
|
self.__server.setCInfo(name, act, key, value)
|
||||||
return self.server.getCInfo(name, act, key)
|
return self.__server.getCInfo(name, act, key)
|
||||||
elif action[1] == "delcinfo":
|
elif action[1] == "delcinfo":
|
||||||
act = action[2]
|
act = action[2]
|
||||||
key = action[3]
|
key = action[3]
|
||||||
self.server.delCInfo(name, act, key)
|
self.__server.delCInfo(name, act, key)
|
||||||
return None
|
return None
|
||||||
elif action[1] == "actionstart":
|
elif action[1] == "actionstart":
|
||||||
act = action[2]
|
act = action[2]
|
||||||
value = action[3]
|
value = action[3]
|
||||||
self.server.setActionStart(name, act, value)
|
self.__server.setActionStart(name, act, value)
|
||||||
return self.server.getActionStart(name, act)
|
return self.__server.getActionStart(name, act)
|
||||||
elif action[1] == "actionstop":
|
elif action[1] == "actionstop":
|
||||||
act = action[2]
|
act = action[2]
|
||||||
value = action[3]
|
value = action[3]
|
||||||
self.server.setActionStop(name, act, value)
|
self.__server.setActionStop(name, act, value)
|
||||||
return self.server.getActionStop(name, act)
|
return self.__server.getActionStop(name, act)
|
||||||
elif action[1] == "actioncheck":
|
elif action[1] == "actioncheck":
|
||||||
act = action[2]
|
act = action[2]
|
||||||
value = action[3]
|
value = action[3]
|
||||||
self.server.setActionCheck(name, act, value)
|
self.__server.setActionCheck(name, act, value)
|
||||||
return self.server.getActionCheck(name, act)
|
return self.__server.getActionCheck(name, act)
|
||||||
elif action[1] == "actionban":
|
elif action[1] == "actionban":
|
||||||
act = action[2]
|
act = action[2]
|
||||||
value = action[3]
|
value = action[3]
|
||||||
self.server.setActionBan(name, act, value)
|
self.__server.setActionBan(name, act, value)
|
||||||
return self.server.getActionBan(name, act)
|
return self.__server.getActionBan(name, act)
|
||||||
elif action[1] == "actionunban":
|
elif action[1] == "actionunban":
|
||||||
act = action[2]
|
act = action[2]
|
||||||
value = action[3]
|
value = action[3]
|
||||||
self.server.setActionUnban(name, act, value)
|
self.__server.setActionUnban(name, act, value)
|
||||||
return self.server.getActionUnban(name, act)
|
return self.__server.getActionUnban(name, act)
|
||||||
raise Exception("Invalid command (no set action or not yet implemented)")
|
raise Exception("Invalid command (no set action or not yet implemented)")
|
||||||
|
|
||||||
def actionGet(self, action):
|
def __actionGet(self, action):
|
||||||
name = action[0]
|
name = action[0]
|
||||||
# Logging
|
# Logging
|
||||||
if name == "loglevel":
|
if name == "loglevel":
|
||||||
return self.server.getLogLevel()
|
return self.__server.getLogLevel()
|
||||||
elif name == "logtarget":
|
elif name == "logtarget":
|
||||||
return self.server.getLogTarget()
|
return self.__server.getLogTarget()
|
||||||
# Filter
|
# Filter
|
||||||
elif action[1] == "logpath":
|
elif action[1] == "logpath":
|
||||||
return self.server.getLogPath(name)
|
return self.__server.getLogPath(name)
|
||||||
elif action[1] == "ignoreip":
|
elif action[1] == "ignoreip":
|
||||||
return self.server.getIgnoreIP(name)
|
return self.__server.getIgnoreIP(name)
|
||||||
elif action[1] == "timeregex":
|
elif action[1] == "timeregex":
|
||||||
return self.server.getTimeRegex(name)
|
return self.__server.getTimeRegex(name)
|
||||||
elif action[1] == "timepattern":
|
elif action[1] == "timepattern":
|
||||||
return self.server.getTimePattern(name)
|
return self.__server.getTimePattern(name)
|
||||||
elif action[1] == "failregex":
|
elif action[1] == "failregex":
|
||||||
return self.server.getFailRegex(name)
|
return self.__server.getFailRegex(name)
|
||||||
elif action[1] == "maxtime":
|
elif action[1] == "maxtime":
|
||||||
return self.server.getMaxTime(name)
|
return self.__server.getMaxTime(name)
|
||||||
elif action[1] == "findtime":
|
elif action[1] == "findtime":
|
||||||
return self.server.getFindTime(name)
|
return self.__server.getFindTime(name)
|
||||||
elif action[1] == "maxretry":
|
elif action[1] == "maxretry":
|
||||||
return self.server.getMaxRetry(name)
|
return self.__server.getMaxRetry(name)
|
||||||
# Action
|
# Action
|
||||||
elif action[1] == "bantime":
|
elif action[1] == "bantime":
|
||||||
return self.server.getBanTime(name)
|
return self.__server.getBanTime(name)
|
||||||
elif action[1] == "addaction":
|
elif action[1] == "addaction":
|
||||||
return self.server.getLastAction(name).getName()
|
return self.__server.getLastAction(name).getName()
|
||||||
elif action[1] == "actionstart":
|
elif action[1] == "actionstart":
|
||||||
act = action[2]
|
act = action[2]
|
||||||
return self.server.getActionStart(name, act)
|
return self.__server.getActionStart(name, act)
|
||||||
elif action[1] == "actionstop":
|
elif action[1] == "actionstop":
|
||||||
act = action[2]
|
act = action[2]
|
||||||
return self.server.getActionStop(name, act)
|
return self.__server.getActionStop(name, act)
|
||||||
elif action[1] == "actioncheck":
|
elif action[1] == "actioncheck":
|
||||||
act = action[2]
|
act = action[2]
|
||||||
return self.server.getActionCheck(name, act)
|
return self.__server.getActionCheck(name, act)
|
||||||
elif action[1] == "actionban":
|
elif action[1] == "actionban":
|
||||||
act = action[2]
|
act = action[2]
|
||||||
return self.server.getActionBan(name, act)
|
return self.__server.getActionBan(name, act)
|
||||||
elif action[1] == "actionunban":
|
elif action[1] == "actionunban":
|
||||||
act = action[2]
|
act = action[2]
|
||||||
return self.server.getActionUnban(name, act)
|
return self.__server.getActionUnban(name, act)
|
||||||
raise Exception("Invalid command (no get action or not yet implemented)")
|
raise Exception("Invalid command (no get action or not yet implemented)")
|
||||||
|
|
||||||
def status(self, action):
|
def status(self, action):
|
||||||
if len(action) == 0:
|
if len(action) == 0:
|
||||||
return self.server.status()
|
return self.__server.status()
|
||||||
else:
|
else:
|
||||||
name = action[0]
|
name = action[0]
|
||||||
return self.server.statusJail(name)
|
return self.__server.statusJail(name)
|
||||||
raise Exception("Invalid command (no status)")
|
raise Exception("Invalid command (no status)")
|
||||||
|
|
Loading…
Reference in New Issue