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