fail2ban/server/server.py

500 lines
15 KiB
Python
Raw Normal View History

# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*-
# vi: set ft=python sts=4 ts=4 sw=4 noet :
# This file is part of Fail2Ban.
#
# Fail2Ban is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Fail2Ban is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Fail2Ban; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#
__author__ = "Cyril Jaquier"
__copyright__ = "Copyright (c) 2004 Cyril Jaquier"
__license__ = "GPL"
from threading import Lock, RLock
from jails import Jails
from transmitter import Transmitter
from asyncserver import AsyncServer
from asyncserver import AsyncServerException
from common import version
import logging, logging.handlers, sys, os, signal
# Gets the instance of the logger.
logSys = logging.getLogger("fail2ban.server")
class Server:
def __init__(self, daemon = False):
self.__loggingLock = Lock()
self.__lock = RLock()
self.__jails = Jails()
self.__daemon = daemon
self.__transm = Transmitter(self)
self.__asyncServer = AsyncServer(self.__transm)
self.__logLevel = None
self.__logTarget = None
# Set logging level
self.setLogLevel(3)
self.setLogTarget("STDOUT")
def __sigTERMhandler(self, signum, frame):
logSys.debug("Caught signal %d. Exiting" % signum)
self.quit()
2013-02-17 22:14:01 +00:00
def start(self, sock, pidfile, force = False):
logSys.info("Starting Fail2ban v" + version.version)
# Install signal handlers
signal.signal(signal.SIGTERM, self.__sigTERMhandler)
signal.signal(signal.SIGINT, self.__sigTERMhandler)
# First set the mask to only allow access to owner
os.umask(0077)
if self.__daemon: # pragma: no cover
logSys.info("Starting in daemon mode")
ret = self.__createDaemon()
if ret:
logSys.info("Daemon started")
else:
logSys.error("Could not create daemon")
raise ServerInitializationError("Could not create daemon")
# Creates a PID file.
try:
2013-02-17 22:14:01 +00:00
logSys.debug("Creating PID file %s" % pidfile)
pidFile = open(pidfile, 'w')
pidFile.write("%s\n" % os.getpid())
pidFile.close()
except IOError, e:
logSys.error("Unable to create PID file: %s" % e)
# Start the communication
logSys.debug("Starting communication")
try:
self.__asyncServer.start(sock, force)
except AsyncServerException, e:
logSys.error("Could not start server: %s", e)
# Removes the PID file.
try:
2013-02-17 22:14:01 +00:00
logSys.debug("Remove PID file %s" % pidfile)
os.remove(pidfile)
except OSError, e:
logSys.error("Unable to remove PID file: %s" % e)
logSys.info("Exiting Fail2ban")
def quit(self):
# Stop communication first because if jail's unban action
# tries to communicate via fail2ban-client we get a lockup
# among threads. So the simplest resolution is to stop all
# communications first (which should be ok anyways since we
# are exiting)
# See https://github.com/fail2ban/fail2ban/issues/7
self.__asyncServer.stop()
# Now stop all the jails
self.stopAllJail()
# Only now shutdown the logging.
try:
self.__loggingLock.acquire()
logging.shutdown()
finally:
self.__loggingLock.release()
def addJail(self, name, backend):
self.__jails.add(name, backend)
def delJail(self, name):
self.__jails.remove(name)
def startJail(self, name):
try:
self.__lock.acquire()
if not self.isAlive(name):
self.__jails.get(name).start()
finally:
self.__lock.release()
def stopJail(self, name):
logSys.debug("Stopping jail %s" % name)
try:
self.__lock.acquire()
if self.isAlive(name):
self.__jails.get(name).stop()
self.delJail(name)
finally:
self.__lock.release()
def stopAllJail(self):
logSys.info("Stopping all jails")
try:
self.__lock.acquire()
for jail in self.__jails.getAll():
self.stopJail(jail)
finally:
self.__lock.release()
def isAlive(self, name):
return self.__jails.get(name).isAlive()
def setIdleJail(self, name, value):
self.__jails.get(name).setIdle(value)
return True
def getIdleJail(self, name):
return self.__jails.get(name).getIdle()
# Filter
def addIgnoreIP(self, name, ip):
self.__jails.getFilter(name).addIgnoreIP(ip)
def delIgnoreIP(self, name, ip):
self.__jails.getFilter(name).delIgnoreIP(ip)
def getIgnoreIP(self, name):
return self.__jails.getFilter(name).getIgnoreIP()
def addLogPath(self, name, fileName):
self.__jails.getFilter(name).addLogPath(fileName)
def delLogPath(self, name, fileName):
self.__jails.getFilter(name).delLogPath(fileName)
def getLogPath(self, name):
return [m.getFileName()
for m in self.__jails.getFilter(name).getLogPath()]
def setFindTime(self, name, value):
self.__jails.getFilter(name).setFindTime(value)
def getFindTime(self, name):
return self.__jails.getFilter(name).getFindTime()
def setIgnoreCommand(self, name, value):
self.__jails.getFilter(name).setIgnoreCommand(value)
def getIgnoreCommand(self, name):
return self.__jails.getFilter(name).getIgnoreCommand()
def addFailRegex(self, name, value):
self.__jails.getFilter(name).addFailRegex(value)
def delFailRegex(self, name, index):
self.__jails.getFilter(name).delFailRegex(index)
def getFailRegex(self, name):
return self.__jails.getFilter(name).getFailRegex()
def addIgnoreRegex(self, name, value):
self.__jails.getFilter(name).addIgnoreRegex(value)
def delIgnoreRegex(self, name, index):
self.__jails.getFilter(name).delIgnoreRegex(index)
def getIgnoreRegex(self, name):
return self.__jails.getFilter(name).getIgnoreRegex()
ENH: Add usedns parameter for the jails following commits were squashed from feature branch use_dns commit 068c105eb58b85aaf5ad9df02e7f4122a4efea81 Author: Lee Clemens <java@leeclemens.net> Date: Tue Jan 10 22:19:04 2012 -0500 Prevent warning when IP is read from log commit 635ed36a8c7280658d501318d882f6e9dd426343 Author: Lee Clemens <java@leeclemens.net> Date: Tue Jan 10 22:17:08 2012 -0500 Removed logDebug commit 24656d2812c18e0f9312ce36d42ef51ecb68b354 Merge: 7957fbe c429f5c Author: Lee Clemens <java@leeclemens.net> Date: Tue Jan 10 21:13:11 2012 -0500 Merge branch 'enh/use_dns' of github:leeclemens/fail2ban into enh/use_dns Conflicts: testcases/filtertestcase.py commit 7957fbe821b0cebf162f64b4627a345db551c2d0 Author: Lee Clemens <java@leeclemens.net> Date: Tue Jan 10 21:09:58 2012 -0500 filtertestcase fixes from yarikoptic commit 6ce9d04640789c1eb587454d2ec95d61f7b67ce8 Author: Yaroslav Halchenko <debian@onerussian.com> Date: Tue Jan 10 19:26:05 2012 -0500 RF: for consistency use_dns -> usedns I guess it was might fault of inconsistency suggesting that name. Other options/commands do not have _ in the names, so let it be consistent with the rest for now commit cfb2c75b49942b127fff6da4e4e349c667606b5d Author: Lee Clemens <java@leeclemens.net> Date: Tue Jan 10 19:18:41 2012 -0500 Updated DNSUtilsTests to test use_dns and added positive test to testTextToIp commit f6186eff14ff1ff9da42f30c7f6268fd792104e6 Author: Lee Clemens <java@leeclemens.net> Date: Tue Jan 10 19:02:04 2012 -0500 Changed wording of 'DNS Reverse lookup used' message commit 82c62d29dc49582594ff86fb24dc710654ea6269 Author: Lee Clemens <java@leeclemens.net> Date: Tue Jan 10 18:53:17 2012 -0500 Removed extraneous "n" commit dc0ae2193227cbf8e837bdd173403edbd68afd9a Author: Lee Clemens <java@leeclemens.net> Date: Mon Jan 9 23:07:59 2012 -0500 ENH: use_dns - removed debugging statements commit 594e25818cd6b5dd366194d7e74af99294c5a394 Author: Lee Clemens <java@leeclemens.net> Date: Mon Jan 9 22:53:39 2012 -0500 Added use_dns protocol to set and get per jail during runtime commit 48ff80ffac25d8c3d538e5c05678514f6c9628f6 Author: Lee Clemens <java@leeclemens.net> Date: Mon Jan 9 22:41:18 2012 -0500 Completed use_dns for initial startup - with debugging statements commit 0bdab4c2d7f0d0c29d4999e70db5f748b51fe1b5 Author: Lee Clemens <java@leeclemens.net> Date: Mon Jan 9 20:05:35 2012 -0500 ENH: Added use_dns option commit 6d6b734ea51a2f2792ed34d9a4227bb7a3361adb Author: Lee Clemens <java@leeclemens.net> Date: Mon Jan 9 20:01:34 2012 -0500 ENH: Added use_dns option commit 11ad2b61254ee03fa761e0c3a7e4905dd89bc54a Author: Lee Clemens <java@leeclemens.net> Date: Mon Jan 9 19:17:30 2012 -0500 Added useDns flag to testcase commit b48fa9b6af242fc04c1d1fe1ddf8f7bc1c8fdeed Author: Lee Clemens <java@leeclemens.net> Date: Sun Jan 8 15:13:27 2012 -0500 Added use_dns option in jail.conf commit c429f5c91ae935b359e28376b2120eb3d6ea0ad7 Merge: 4b18afb 0021906 Author: leeclemens <java@leeclemens.net> Date: Tue Jan 10 16:32:22 2012 -0800 Merge pull request #3 from yarikoptic/enh/use_dns let's be consistent ;-) commit 0021906358e50c9f53d2fa98ba853a16f6388078 Author: Yaroslav Halchenko <debian@onerussian.com> Date: Tue Jan 10 19:26:05 2012 -0500 RF: for consistency use_dns -> usedns I guess it was might fault of inconsistency suggesting that name. Other options/commands do not have _ in the names, so let it be consistent with the rest for now commit 4b18afb28a5be525913ad552459bfb3287ccfda5 Author: Lee Clemens <java@leeclemens.net> Date: Tue Jan 10 19:18:41 2012 -0500 Updated DNSUtilsTests to test use_dns and added positive test to testTextToIp commit 4fae37e46fef62058738040325a3c9cd2be11d45 Author: Lee Clemens <java@leeclemens.net> Date: Tue Jan 10 19:02:04 2012 -0500 Changed wording of 'DNS Reverse lookup used' message commit e94806ce4804ff3bdc124a0f5265602987245525 Author: Lee Clemens <java@leeclemens.net> Date: Tue Jan 10 18:53:17 2012 -0500 Removed extraneous "n" commit 4d30c5290725b7d92b0a8f49c1eb5a6a2d12b32e Author: Lee Clemens <java@leeclemens.net> Date: Mon Jan 9 23:07:59 2012 -0500 ENH: use_dns - removed debugging statements commit 76696d452ae59e0fa161e1f85e31c6411352f966 Author: Lee Clemens <java@leeclemens.net> Date: Mon Jan 9 22:53:39 2012 -0500 Added use_dns protocol to set and get per jail during runtime commit 06316180870a0349630e27f7ef078624c6f006cd Author: Lee Clemens <java@leeclemens.net> Date: Mon Jan 9 22:41:18 2012 -0500 Completed use_dns for initial startup - with debugging statements commit d23d495547fe382ea6669c30eeac5033284b4c5f Author: Lee Clemens <java@leeclemens.net> Date: Mon Jan 9 20:05:35 2012 -0500 ENH: Added use_dns option commit 9538553bc5a71faf23b5b810b83d7acb133c8d56 Author: Lee Clemens <java@leeclemens.net> Date: Mon Jan 9 20:01:34 2012 -0500 ENH: Added use_dns option commit ae1e857e53e0c014da5b717976536be172a37dc1 Author: Lee Clemens <java@leeclemens.net> Date: Mon Jan 9 19:17:30 2012 -0500 Added useDns flag to testcase commit ace43eb94128f32538182472fd35e97c220bbf34 Author: Lee Clemens <java@leeclemens.net> Date: Sun Jan 8 15:13:27 2012 -0500 Added use_dns option in jail.conf
2012-01-13 04:23:41 +00:00
def setUseDns(self, name, value):
self.__jails.getFilter(name).setUseDns(value)
def getUseDns(self, name):
return self.__jails.getFilter(name).getUseDns()
def setMaxRetry(self, name, value):
self.__jails.getFilter(name).setMaxRetry(value)
def getMaxRetry(self, name):
return self.__jails.getFilter(name).getMaxRetry()
# Action
def addAction(self, name, value):
self.__jails.getAction(name).addAction(value)
def getLastAction(self, name):
return self.__jails.getAction(name).getLastAction()
def delAction(self, name, value):
self.__jails.getAction(name).delAction(value)
def setCInfo(self, name, action, 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)
def delCInfo(self, name, action, key):
self.__jails.getAction(name).getAction(action).delCInfo(key)
def setBanTime(self, name, value):
self.__jails.getAction(name).setBanTime(value)
def setBanIP(self, name, value):
return self.__jails.getFilter(name).addBannedIP(value)
def setUnbanIP(self, name, value):
return self.__jails.getAction(name).removeBannedIP(value)
def getBanTime(self, name):
return self.__jails.getAction(name).getBanTime()
def setActionStart(self, name, action, value):
self.__jails.getAction(name).getAction(action).setActionStart(value)
def getActionStart(self, name, action):
return self.__jails.getAction(name).getAction(action).getActionStart()
def setActionStop(self, name, action, value):
self.__jails.getAction(name).getAction(action).setActionStop(value)
def getActionStop(self, name, action):
return self.__jails.getAction(name).getAction(action).getActionStop()
def setActionCheck(self, name, action, value):
self.__jails.getAction(name).getAction(action).setActionCheck(value)
def getActionCheck(self, name, action):
return self.__jails.getAction(name).getAction(action).getActionCheck()
def setActionBan(self, name, action, value):
self.__jails.getAction(name).getAction(action).setActionBan(value)
def getActionBan(self, name, action):
return self.__jails.getAction(name).getAction(action).getActionBan()
def setActionUnban(self, name, action, value):
self.__jails.getAction(name).getAction(action).setActionUnban(value)
def getActionUnban(self, name, action):
return self.__jails.getAction(name).getAction(action).getActionUnban()
# Status
def status(self):
try:
self.__lock.acquire()
jailList = ''
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()),
("Jail list", jailList)]
return ret
finally:
self.__lock.release()
def statusJail(self, name):
return self.__jails.get(name).getStatus()
# Logging
##
# Set the logging level.
#
# Incrementing the value gives more messages.
# 0 = FATAL
# 1 = ERROR
# 2 = WARNING
# 3 = INFO
# 4 = DEBUG
# @param value the level
def setLogLevel(self, value):
try:
self.__loggingLock.acquire()
self.__logLevel = value
logLevel = logging.DEBUG
if value == 0:
logLevel = logging.FATAL
elif value == 1:
logLevel = logging.ERROR
elif value == 2:
logLevel = logging.WARNING
elif value == 3:
logLevel = logging.INFO
logging.getLogger("fail2ban").setLevel(logLevel)
finally:
self.__loggingLock.release()
##
# Get the logging level.
#
# @see setLogLevel
# @return the log level
def getLogLevel(self):
try:
self.__loggingLock.acquire()
return self.__logLevel
finally:
self.__loggingLock.release()
##
# Sets the logging target.
#
# target can be a file, SYSLOG, STDOUT or STDERR.
# @param target the logging target
def setLogTarget(self, target):
try:
self.__loggingLock.acquire()
# set a format which is simpler for console use
formatter = logging.Formatter("%(asctime)s %(name)-16s[%(process)d]: %(levelname)-7s %(message)s")
if target == "SYSLOG":
# Syslog daemons already add date to the message.
formatter = logging.Formatter("%(name)s[%(process)d]: %(levelname)s %(message)s")
facility = logging.handlers.SysLogHandler.LOG_DAEMON
hdlr = logging.handlers.SysLogHandler("/dev/log", facility=facility)
elif target == "STDOUT":
hdlr = logging.StreamHandler(sys.stdout)
elif target == "STDERR":
hdlr = logging.StreamHandler(sys.stderr)
else:
# Target should be a file
try:
open(target, "a").close()
hdlr = logging.handlers.RotatingFileHandler(target)
except IOError:
logSys.error("Unable to log to " + target)
logSys.info("Logging to previous target " + self.__logTarget)
return False
# Removes previous handlers -- in reverse order since removeHandler
# alter the list in-place and that can confuses the iterable
for handler in logging.getLogger("fail2ban").handlers[::-1]:
# Remove the handler.
logging.getLogger("fail2ban").removeHandler(handler)
# And try to close -- it might be closed already
try:
handler.flush()
handler.close()
except (ValueError, KeyError): # pragma: no cover
# Is known to be thrown after logging was shutdown once
# with older Pythons -- seems to be safe to ignore there
# At least it was still failing on 2.6.2-0ubuntu1 (jaunty)
if sys.version_info >= (2,6,3):
raise
# tell the handler to use this format
hdlr.setFormatter(formatter)
logging.getLogger("fail2ban").addHandler(hdlr)
# Does not display this message at startup.
if not self.__logTarget is None:
logSys.info("Changed logging target to %s for Fail2ban v%s" %
(target, version.version))
# Sets the logging target.
self.__logTarget = target
return True
finally:
self.__loggingLock.release()
def getLogTarget(self):
try:
self.__loggingLock.acquire()
return self.__logTarget
finally:
self.__loggingLock.release()
def flushLogs(self):
if self.__logTarget not in ['STDERR', 'STDOUT', 'SYSLOG']:
for handler in logging.getLogger("fail2ban").handlers:
handler.doRollover()
return "rolled over"
else:
for handler in logging.getLogger("fail2ban").handlers:
handler.flush()
return "flushed"
def __createDaemon(self): # pragma: no cover
""" Detach a process from the controlling terminal and run it in the
background as a daemon.
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731
"""
# When the first child terminates, all processes in the second child
# are sent a SIGHUP, so it's ignored.
# We need to set this in the parent process, so it gets inherited by the
# child process, and this makes sure that it is effect even if the parent
# terminates quickly.
signal.signal(signal.SIGHUP, signal.SIG_IGN)
try:
# Fork a child process so the parent can exit. This will return control
# to the command line or shell. This is required so that the new process
# is guaranteed not to be a process group leader. We have this guarantee
# because the process GID of the parent is inherited by the child, but
# the child gets a new PID, making it impossible for its PID to equal its
# PGID.
pid = os.fork()
except OSError, e:
return((e.errno, e.strerror)) # ERROR (return a tuple)
if pid == 0: # The first child.
# Next we call os.setsid() to become the session leader of this new
# session. The process also becomes the process group leader of the
# new process group. Since a controlling terminal is associated with a
# session, and this new session has not yet acquired a controlling
# terminal our process now has no controlling terminal. This shouldn't
# fail, since we're guaranteed that the child is not a process group
# leader.
os.setsid()
try:
# Fork a second child to prevent zombies. Since the first child is
# a session leader without a controlling terminal, it's possible for
# it to acquire one by opening a terminal in the future. This second
# fork guarantees that the child is no longer a session leader, thus
# preventing the daemon from ever acquiring a controlling terminal.
pid = os.fork() # Fork a second child.
except OSError, e:
return((e.errno, e.strerror)) # ERROR (return a tuple)
if (pid == 0): # The second child.
# Ensure that the daemon doesn't keep any directory in use. Failure
# to do this could make a filesystem unmountable.
os.chdir("/")
else:
os._exit(0) # Exit parent (the first child) of the second child.
else:
os._exit(0) # Exit parent of the first child.
# Close all open files. Try the system configuration variable, SC_OPEN_MAX,
# for the maximum number of open files to close. If it doesn't exist, use
# the default value (configurable).
try:
maxfd = os.sysconf("SC_OPEN_MAX")
except (AttributeError, ValueError):
maxfd = 256 # default maximum
for fd in range(0, maxfd):
try:
os.close(fd)
except OSError: # ERROR (ignore)
pass
# Redirect the standard file descriptors to /dev/null.
os.open("/dev/null", os.O_RDONLY) # standard input (0)
os.open("/dev/null", os.O_RDWR) # standard output (1)
os.open("/dev/null", os.O_RDWR) # standard error (2)
return True
class ServerInitializationError(Exception):
pass