2005-07-06 23:10:19 +00:00
|
|
|
# This file is part of Fail2Ban.
|
|
|
|
#
|
|
|
|
# Fail2Ban is free software; you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation; either version 2 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# Fail2Ban is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with Fail2Ban; if not, write to the Free Software
|
|
|
|
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
|
|
|
|
|
|
|
# Author: Cyril Jaquier
|
2005-08-19 08:40:09 +00:00
|
|
|
# Modified by: Yaroslav Halchenko (SYSLOG, findtime)
|
2005-09-20 16:37:44 +00:00
|
|
|
#
|
|
|
|
# $Revision: 1.20.2.18 $
|
2005-07-06 23:10:19 +00:00
|
|
|
|
|
|
|
__author__ = "Cyril Jaquier"
|
2005-09-20 16:37:44 +00:00
|
|
|
__version__ = "$Revision: 1.20.2.18 $"
|
|
|
|
__date__ = "$Date: 2005/09/13 20:42:33 $"
|
2005-07-06 23:10:19 +00:00
|
|
|
__copyright__ = "Copyright (c) 2004 Cyril Jaquier"
|
|
|
|
__license__ = "GPL"
|
|
|
|
|
2005-10-12 14:16:52 +00:00
|
|
|
import time, sys, getopt, os, string, signal, logging, logging.handlers, copy
|
2005-07-06 23:10:19 +00:00
|
|
|
from ConfigParser import *
|
|
|
|
|
2005-07-23 19:15:22 +00:00
|
|
|
from version import version
|
2005-07-13 10:01:01 +00:00
|
|
|
from firewall.firewall import Firewall
|
2005-07-06 23:10:19 +00:00
|
|
|
from logreader.logreader import LogReader
|
|
|
|
from confreader.configreader import ConfigReader
|
2005-07-13 10:01:01 +00:00
|
|
|
from utils.mail import Mail
|
2005-08-06 19:43:43 +00:00
|
|
|
from utils.pidlock import PIDLock
|
2005-07-23 19:15:22 +00:00
|
|
|
from utils.dns import *
|
|
|
|
from utils.process import *
|
2005-07-06 23:10:19 +00:00
|
|
|
|
2005-08-06 19:43:43 +00:00
|
|
|
# Get the instance of the logger.
|
|
|
|
logSys = logging.getLogger("fail2ban")
|
|
|
|
|
|
|
|
# Get PID lock file instance
|
|
|
|
pidLock = PIDLock()
|
2005-07-13 10:01:01 +00:00
|
|
|
|
|
|
|
# Global variables
|
|
|
|
logFwList = list()
|
|
|
|
conf = dict()
|
|
|
|
|
|
|
|
def dispUsage():
|
|
|
|
""" Prints Fail2Ban command line options and exits
|
|
|
|
"""
|
2005-07-07 03:06:56 +00:00
|
|
|
print "Usage: "+sys.argv[0]+" [OPTIONS]"
|
2005-07-06 23:10:19 +00:00
|
|
|
print
|
|
|
|
print "Fail2Ban v"+version+" reads log file that contains password failure report"
|
2005-07-13 09:21:21 +00:00
|
|
|
print "and bans the corresponding IP addresses using firewall rules."
|
2005-07-06 23:10:19 +00:00
|
|
|
print
|
2005-08-06 19:43:43 +00:00
|
|
|
print " -b start in background"
|
|
|
|
print " -d start in debug mode"
|
2005-07-06 23:10:19 +00:00
|
|
|
print " -c <FILE> read configuration file FILE"
|
|
|
|
print " -p <FILE> create PID lock in FILE"
|
|
|
|
print " -h display this help message"
|
|
|
|
print " -i <IP(s)> IP(s) to ignore"
|
2005-08-06 19:43:43 +00:00
|
|
|
print " -k kill a currently running instance"
|
2005-07-06 23:10:19 +00:00
|
|
|
print " -r <VALUE> allow a max of VALUE password failure"
|
|
|
|
print " -t <TIME> ban IP for TIME seconds"
|
|
|
|
print " -v verbose. Use twice for greater effect"
|
2005-07-13 10:01:01 +00:00
|
|
|
print " -V print software version"
|
2005-07-06 23:10:19 +00:00
|
|
|
print
|
|
|
|
print "Report bugs to <lostcontrol@users.sourceforge.net>"
|
|
|
|
sys.exit(0)
|
|
|
|
|
2005-07-13 10:01:01 +00:00
|
|
|
def dispVersion():
|
|
|
|
""" Prints Fail2Ban version and exits
|
|
|
|
"""
|
|
|
|
print sys.argv[0]+" "+version
|
|
|
|
sys.exit(0)
|
|
|
|
|
2005-07-06 23:10:19 +00:00
|
|
|
def checkForRoot():
|
|
|
|
""" Check for root user.
|
|
|
|
"""
|
|
|
|
uid = `os.getuid()`
|
|
|
|
if uid == '0':
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
|
|
|
|
def sigTERMhandler(signum, frame):
|
|
|
|
""" Handles the TERM signal when in daemon mode in order to
|
|
|
|
exit properly.
|
|
|
|
"""
|
|
|
|
logSys.debug("Signal handler called with sig "+`signum`)
|
2005-09-20 16:37:44 +00:00
|
|
|
killApp()
|
2005-07-06 23:10:19 +00:00
|
|
|
|
2005-10-12 14:16:52 +00:00
|
|
|
def initializeFwRules():
|
|
|
|
""" Initializes firewalls by running cmdstart and then
|
|
|
|
fwstart for each section
|
|
|
|
"""
|
|
|
|
# Execute global start command
|
|
|
|
executeCmd(conf["cmdstart"], conf["debug"])
|
|
|
|
# Execute start command of each section
|
|
|
|
for element in logFwList:
|
|
|
|
l = element[4]
|
|
|
|
executeCmd(l["fwstart"], conf["debug"])
|
|
|
|
|
|
|
|
|
|
|
|
def reBan():
|
|
|
|
""" For each section asks the Firewall to reban known IPs
|
|
|
|
"""
|
|
|
|
for element in logFwList:
|
|
|
|
element[2].reBan(conf["debug"])
|
|
|
|
|
2005-10-12 05:11:16 +00:00
|
|
|
def restoreFwRules():
|
|
|
|
""" Flush the ban list
|
2005-07-06 23:10:19 +00:00
|
|
|
"""
|
|
|
|
logSys.warn("Restoring firewall rules...")
|
2005-07-13 10:01:01 +00:00
|
|
|
for element in logFwList:
|
2005-10-12 14:16:52 +00:00
|
|
|
try:
|
|
|
|
element[2].flushBanList(conf["debug"])
|
|
|
|
except ExternalError, e:
|
|
|
|
# nothing bad really - we can survive :-)
|
|
|
|
pass
|
2005-07-13 10:01:01 +00:00
|
|
|
# Execute end command of each section
|
|
|
|
for element in logFwList:
|
|
|
|
l = element[4]
|
|
|
|
executeCmd(l["fwend"], conf["debug"])
|
2005-10-12 05:11:16 +00:00
|
|
|
# Execute global end command
|
2005-07-13 10:01:01 +00:00
|
|
|
executeCmd(conf["cmdend"], conf["debug"])
|
2005-10-12 05:11:16 +00:00
|
|
|
|
|
|
|
def killApp():
|
2005-10-12 14:16:52 +00:00
|
|
|
""" Flush the ban list, remove the PID lock file and exit
|
2005-10-12 05:11:16 +00:00
|
|
|
nicely.
|
|
|
|
"""
|
|
|
|
# Restore Fw rules
|
|
|
|
restoreFwRules()
|
2005-10-12 14:16:52 +00:00
|
|
|
# Remove the PID lock
|
|
|
|
pidLock.remove()
|
|
|
|
logSys.info("Exiting...")
|
|
|
|
logging.shutdown()
|
2005-07-06 23:10:19 +00:00
|
|
|
sys.exit(0)
|
|
|
|
|
2005-07-13 10:01:01 +00:00
|
|
|
def getCmdLineOptions(optList):
|
|
|
|
""" Gets the command line options
|
2005-07-06 23:10:19 +00:00
|
|
|
"""
|
|
|
|
for opt in optList:
|
|
|
|
if opt[0] == "-v":
|
|
|
|
conf["verbose"] = conf["verbose"] + 1
|
|
|
|
if opt[0] == "-b":
|
|
|
|
conf["background"] = True
|
|
|
|
if opt[0] == "-d":
|
|
|
|
conf["debug"] = True
|
|
|
|
if opt[0] == "-t":
|
|
|
|
try:
|
|
|
|
conf["bantime"] = int(opt[1])
|
|
|
|
except ValueError:
|
|
|
|
logSys.warn("banTime must be an integer")
|
|
|
|
logSys.warn("Using default value")
|
|
|
|
if opt[0] == "-i":
|
|
|
|
conf["ignoreip"] = opt[1]
|
|
|
|
if opt[0] == "-r":
|
2005-09-09 21:15:41 +00:00
|
|
|
conf["maxfailures"] = int(opt[1])
|
2005-07-06 23:10:19 +00:00
|
|
|
if opt[0] == "-p":
|
|
|
|
conf["pidlock"] = opt[1]
|
|
|
|
if opt[0] == "-k":
|
2005-08-06 19:43:43 +00:00
|
|
|
conf["kill"] = True
|
2005-07-06 23:10:19 +00:00
|
|
|
|
2005-10-12 14:16:52 +00:00
|
|
|
def main():
|
2005-07-13 10:01:01 +00:00
|
|
|
""" Fail2Ban main function
|
|
|
|
"""
|
2005-08-06 19:43:43 +00:00
|
|
|
|
|
|
|
# Add the default logging handler
|
|
|
|
stdout = logging.StreamHandler(sys.stdout)
|
|
|
|
logSys.addHandler(stdout)
|
|
|
|
|
|
|
|
# Default formatter
|
2005-08-19 10:34:03 +00:00
|
|
|
formatterstring='%(levelname)s: %(message)s'
|
|
|
|
formatter = logging.Formatter('%(asctime)s ' + formatterstring)
|
2005-08-06 19:43:43 +00:00
|
|
|
stdout.setFormatter(formatter)
|
2005-07-13 10:01:01 +00:00
|
|
|
|
|
|
|
conf["verbose"] = 0
|
|
|
|
conf["conffile"] = "/etc/fail2ban.conf"
|
|
|
|
|
|
|
|
# Reads the command line options.
|
|
|
|
try:
|
2005-07-23 19:15:22 +00:00
|
|
|
cmdOpts = 'hvVbdkc:t:i:r:p:'
|
2005-07-13 10:01:01 +00:00
|
|
|
cmdLongOpts = ['help','version']
|
|
|
|
optList, args = getopt.getopt(sys.argv[1:], cmdOpts, cmdLongOpts)
|
|
|
|
except getopt.GetoptError:
|
|
|
|
dispUsage()
|
|
|
|
|
|
|
|
# Pre-parsing of command line options for the -c option
|
|
|
|
for opt in optList:
|
2005-09-09 21:15:41 +00:00
|
|
|
if opt[0] == "-c":
|
|
|
|
conf["conffile"] = opt[1]
|
2005-08-06 21:51:51 +00:00
|
|
|
if opt[0] in ["-h", "--help"]:
|
|
|
|
dispUsage()
|
|
|
|
if opt[0] in ["-V", "--version"]:
|
|
|
|
dispVersion()
|
2005-07-13 10:01:01 +00:00
|
|
|
|
|
|
|
# Reads the config file and create a LogReader instance for
|
|
|
|
# each log file to check.
|
|
|
|
confReader = ConfigReader(conf["conffile"]);
|
|
|
|
confReader.openConf()
|
|
|
|
|
|
|
|
# Options
|
|
|
|
optionValues = (["bool", "background", False],
|
2005-08-06 19:43:43 +00:00
|
|
|
["str", "logtargets", "/var/log/fail2ban.log"],
|
2005-08-19 07:14:17 +00:00
|
|
|
["str", "syslog-target", "/dev/log"],
|
|
|
|
["int", "syslog-facility", 1],
|
2005-07-13 10:01:01 +00:00
|
|
|
["bool", "debug", False],
|
2005-09-29 05:26:18 +00:00
|
|
|
["int", "verbose", conf["verbose"]],
|
2005-07-13 10:01:01 +00:00
|
|
|
["str", "pidlock", "/var/run/fail2ban.pid"],
|
2005-09-09 21:15:41 +00:00
|
|
|
["int", "maxfailures", 5],
|
2005-07-13 10:01:01 +00:00
|
|
|
["int", "bantime", 600],
|
2005-08-19 08:40:09 +00:00
|
|
|
["int", "findtime", 600],
|
2005-07-13 10:01:01 +00:00
|
|
|
["str", "ignoreip", ""],
|
|
|
|
["int", "polltime", 1],
|
|
|
|
["str", "cmdstart", ""],
|
|
|
|
["str", "cmdend", ""])
|
2005-09-29 05:26:18 +00:00
|
|
|
|
2005-07-13 10:01:01 +00:00
|
|
|
# Gets global configuration options
|
|
|
|
conf.update(confReader.getLogOptions("DEFAULT", optionValues))
|
|
|
|
|
|
|
|
# Gets command line options
|
|
|
|
getCmdLineOptions(optList)
|
2005-07-23 19:15:22 +00:00
|
|
|
|
2005-08-06 19:43:43 +00:00
|
|
|
# PID lock
|
|
|
|
pidLock.setPath(conf["pidlock"])
|
2005-09-29 05:26:18 +00:00
|
|
|
|
2005-08-06 19:43:43 +00:00
|
|
|
# Now we can kill properly a running instance if needed
|
|
|
|
try:
|
|
|
|
conf["kill"]
|
|
|
|
pid = pidLock.exists()
|
|
|
|
if pid:
|
|
|
|
killPID(int(pid))
|
|
|
|
logSys.warn("Killed Fail2Ban with PID "+pid)
|
|
|
|
sys.exit(0)
|
|
|
|
else:
|
|
|
|
logSys.error("No running Fail2Ban found")
|
|
|
|
sys.exit(-1)
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
|
2005-10-12 14:16:52 +00:00
|
|
|
# Start Fail2Ban in daemon mode
|
|
|
|
if conf["background"]:
|
|
|
|
retCode = createDaemon()
|
|
|
|
signal.signal(signal.SIGTERM, sigTERMhandler)
|
|
|
|
if not retCode:
|
|
|
|
logSys.error("Unable to start daemon")
|
2005-10-12 05:11:16 +00:00
|
|
|
sys.exit(-1)
|
2005-10-12 14:16:52 +00:00
|
|
|
|
|
|
|
# First setup Log targets
|
|
|
|
# Bug fix for #1234699
|
|
|
|
os.umask(0077)
|
|
|
|
for target in conf["logtargets"].split():
|
|
|
|
# target formatter
|
|
|
|
# By default global formatter is taken. Is different for SYSLOG
|
|
|
|
tformatter = formatter
|
|
|
|
if target == "STDERR":
|
|
|
|
hdlr = logging.StreamHandler(sys.stderr)
|
|
|
|
elif target == "SYSLOG":
|
|
|
|
# SYSLOG target can be either
|
|
|
|
# a socket (file, so it starts with /)
|
|
|
|
# or hostname
|
|
|
|
# or hostname:port
|
|
|
|
syslogtargets = re.findall("(/[\w/]*)|([^/ ][^: ]*)(:(\d+)){,1}",
|
|
|
|
conf["syslog-target"])
|
|
|
|
# we are waiting for a single match
|
|
|
|
syslogtargets = syslogtargets[0]
|
|
|
|
|
|
|
|
# assign facility if it was defined
|
|
|
|
if conf["syslog-facility"] < 0:
|
|
|
|
facility = handlers.SysLogHandler.LOG_USER
|
|
|
|
else:
|
|
|
|
facility = conf["syslog-facility"]
|
|
|
|
|
|
|
|
if len(syslogtargets) == 0: # everything default
|
|
|
|
hdlr = logging.handlers.SysLogHandler()
|
|
|
|
else:
|
|
|
|
if not ( syslogtargets[0] == "" ): # got socket
|
|
|
|
syslogtarget = syslogtargets[0]
|
|
|
|
else: # got hostname and maybe a port
|
|
|
|
if syslogtargets[3] == "": # no port specified
|
|
|
|
port = 514
|
|
|
|
else:
|
|
|
|
port = int(syslogtargets[3])
|
|
|
|
syslogtarget = (syslogtargets[1], port)
|
|
|
|
hdlr = logging.handlers.SysLogHandler(syslogtarget, facility)
|
|
|
|
tformatter = logging.Formatter("fail2ban[%(process)d]: " +
|
|
|
|
formatterstring);
|
2005-10-12 05:11:16 +00:00
|
|
|
else:
|
2005-10-12 14:16:52 +00:00
|
|
|
# Target should be a file
|
|
|
|
try:
|
|
|
|
open(target, "a")
|
|
|
|
hdlr = logging.FileHandler(target)
|
|
|
|
except IOError:
|
|
|
|
logSys.error("Unable to log to " + target)
|
|
|
|
continue
|
|
|
|
# Set formatter and add handler to logger
|
|
|
|
hdlr.setFormatter(tformatter)
|
|
|
|
logSys.addHandler(hdlr)
|
|
|
|
|
|
|
|
# Process some options
|
|
|
|
|
|
|
|
# Verbose level
|
|
|
|
if conf["verbose"]:
|
|
|
|
logSys.warn("Verbose level is "+`conf["verbose"]`)
|
|
|
|
if conf["verbose"] == 1:
|
|
|
|
logSys.setLevel(logging.INFO)
|
|
|
|
elif conf["verbose"] > 1:
|
|
|
|
logSys.setLevel(logging.DEBUG)
|
|
|
|
|
|
|
|
# Set debug log level
|
|
|
|
if conf["debug"]:
|
|
|
|
logSys.setLevel(logging.DEBUG)
|
|
|
|
formatterstring = ('%(levelname)s: [%(filename)s (%(lineno)d)] ' +
|
|
|
|
'%(message)s')
|
|
|
|
formatter = logging.Formatter("%(asctime)s " + formatterstring)
|
|
|
|
stdout.setFormatter(formatter)
|
|
|
|
logSys.warn("DEBUG MODE: FIREWALL COMMANDS ARE _NOT_ EXECUTED BUT " +
|
|
|
|
"ONLY DISPLAYED IN THE LOG MESSAGES")
|
2005-09-29 05:26:18 +00:00
|
|
|
|
2005-07-13 10:01:01 +00:00
|
|
|
# Ignores IP list
|
|
|
|
ignoreIPList = conf["ignoreip"].split(' ')
|
2005-08-19 08:40:09 +00:00
|
|
|
|
2005-10-12 14:16:52 +00:00
|
|
|
# Checks for root user. This is necessary because log files
|
|
|
|
# are owned by root and firewall needs root access.
|
|
|
|
if not checkForRoot():
|
|
|
|
logSys.error("You must be root")
|
|
|
|
if not conf["debug"]:
|
|
|
|
sys.exit(-1)
|
|
|
|
|
|
|
|
# Checks that no instance of Fail2Ban is currently running.
|
|
|
|
pid = pidLock.exists()
|
|
|
|
if pid:
|
|
|
|
logSys.error("Fail2Ban already running with PID "+pid)
|
|
|
|
sys.exit(-1)
|
|
|
|
else:
|
|
|
|
ret = pidLock.create()
|
|
|
|
if not ret:
|
|
|
|
# Unable to create PID lock. Exit
|
|
|
|
sys.exit(-1)
|
|
|
|
|
2005-08-06 19:43:43 +00:00
|
|
|
logSys.debug("ConfFile is " + conf["conffile"])
|
|
|
|
logSys.debug("BanTime is " + `conf["bantime"]`)
|
2005-08-19 08:40:09 +00:00
|
|
|
logSys.debug("FindTime is " + `conf["findtime"]`)
|
2005-09-09 21:15:41 +00:00
|
|
|
logSys.debug("MaxFailure is " + `conf["maxfailures"]`)
|
2005-07-06 23:10:19 +00:00
|
|
|
|
2005-07-13 10:01:01 +00:00
|
|
|
# Options
|
|
|
|
optionValues = (["bool", "enabled", False],
|
|
|
|
["str", "host", "localhost"],
|
|
|
|
["int", "port", "25"],
|
|
|
|
["str", "from", "root"],
|
|
|
|
["str", "to", "root"],
|
|
|
|
["str", "subject", "[Fail2Ban] Banned <ip>"],
|
|
|
|
["str", "message", "Fail2Ban notification"])
|
2005-07-06 23:10:19 +00:00
|
|
|
|
2005-07-13 10:01:01 +00:00
|
|
|
# Gets global configuration options
|
|
|
|
mailConf = confReader.getLogOptions("MAIL", optionValues)
|
2005-07-06 23:10:19 +00:00
|
|
|
|
2005-07-13 10:01:01 +00:00
|
|
|
# Create mailer if enabled
|
|
|
|
if mailConf["enabled"]:
|
|
|
|
logSys.debug("Mail enabled")
|
|
|
|
mail = Mail(mailConf["host"], mailConf["port"])
|
|
|
|
mail.setFromAddr(mailConf["from"])
|
|
|
|
mail.setToAddr(mailConf["to"])
|
|
|
|
logSys.debug("to: " + mailConf["to"] + " from: " + mailConf["from"])
|
|
|
|
|
|
|
|
# Options
|
2005-08-06 19:43:43 +00:00
|
|
|
optionValues = (["bool", "enabled", False],
|
2005-07-13 10:01:01 +00:00
|
|
|
["str", "logfile", "/dev/null"],
|
2005-09-09 21:15:41 +00:00
|
|
|
["int", "maxfailures", conf["maxfailures"]],
|
|
|
|
["int", "bantime", conf["bantime"]],
|
|
|
|
["int", "findtime", conf["findtime"]],
|
2005-07-13 10:01:01 +00:00
|
|
|
["str", "timeregex", ""],
|
|
|
|
["str", "timepattern", ""],
|
|
|
|
["str", "failregex", ""],
|
|
|
|
["str", "fwstart", ""],
|
|
|
|
["str", "fwend", ""],
|
|
|
|
["str", "fwban", ""],
|
2005-10-12 05:11:16 +00:00
|
|
|
["str", "fwunban", ""],
|
|
|
|
["str", "fwcheck", ""])
|
2005-09-20 16:37:44 +00:00
|
|
|
|
2005-09-29 15:35:56 +00:00
|
|
|
logSys.info("Fail2Ban v" + version + " is running")
|
|
|
|
|
2005-09-29 15:41:02 +00:00
|
|
|
enabledSections = []
|
2005-07-13 10:01:01 +00:00
|
|
|
# Gets the options of each sections
|
|
|
|
for t in confReader.getSections():
|
|
|
|
l = confReader.getLogOptions(t, optionValues)
|
|
|
|
if l["enabled"]:
|
|
|
|
# Creates a logreader object
|
2005-09-29 15:41:02 +00:00
|
|
|
enabledSections.append(t)
|
2005-07-13 10:01:01 +00:00
|
|
|
lObj = LogReader(l["logfile"], l["timeregex"], l["timepattern"],
|
2005-09-09 21:15:41 +00:00
|
|
|
l["failregex"], l["maxfailures"], l["findtime"])
|
2005-07-13 10:01:01 +00:00
|
|
|
# Creates a firewall object
|
2005-10-12 05:11:16 +00:00
|
|
|
fObj = Firewall(l["fwban"], l["fwunban"], l["fwcheck"], l["bantime"])
|
2005-07-13 10:01:01 +00:00
|
|
|
# Links them into a list. I'm not really happy
|
|
|
|
# with this :/
|
|
|
|
logFwList.append([t, lObj, fObj, dict(), l])
|
2005-07-06 23:10:19 +00:00
|
|
|
|
2005-09-29 15:44:07 +00:00
|
|
|
logSys.info("Enabled sections: %s"%enabledSections)
|
2005-09-29 15:35:56 +00:00
|
|
|
|
2005-07-06 23:10:19 +00:00
|
|
|
# We add 127.0.0.1 to the ignore list has we do not want
|
|
|
|
# to be ban ourself.
|
2005-07-13 10:01:01 +00:00
|
|
|
for element in logFwList:
|
|
|
|
element[1].addIgnoreIP("127.0.0.1")
|
2005-07-06 23:10:19 +00:00
|
|
|
while len(ignoreIPList) > 0:
|
|
|
|
ip = ignoreIPList.pop()
|
2005-07-23 19:15:22 +00:00
|
|
|
# Bug fix for #1239557
|
|
|
|
if isValidIP(ip):
|
|
|
|
for element in logFwList:
|
|
|
|
element[1].addIgnoreIP(ip)
|
2005-09-09 21:15:41 +00:00
|
|
|
else:
|
|
|
|
logSys.warn(ip + " is not a valid IP address")
|
2005-07-06 23:10:19 +00:00
|
|
|
|
2005-10-12 14:16:52 +00:00
|
|
|
initializeFwRules()
|
|
|
|
|
|
|
|
# yoh: I don't think that this parameters need to be configured
|
|
|
|
# and probably maxRestarts should be removed
|
|
|
|
legitRestartTime = 10 # legitimate minimal restart time
|
|
|
|
maxRestarts = 100 # max number of times to perform restart
|
|
|
|
|
|
|
|
lastRestartTime = time.time()
|
|
|
|
restarts = 0
|
2005-07-06 23:10:19 +00:00
|
|
|
# Main loop
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
sys.stdout.flush()
|
|
|
|
sys.stderr.flush()
|
|
|
|
|
|
|
|
# Checks if some IP have to be remove from ban
|
|
|
|
# list.
|
2005-07-13 10:01:01 +00:00
|
|
|
for element in logFwList:
|
|
|
|
element[2].checkForUnBan(conf["debug"])
|
|
|
|
|
2005-07-06 23:10:19 +00:00
|
|
|
# If the log file has not been modified since the
|
|
|
|
# last time, we sleep for 1 second. This is active
|
|
|
|
# polling so not very effective.
|
|
|
|
modList = list()
|
2005-07-13 10:01:01 +00:00
|
|
|
for element in logFwList:
|
|
|
|
if element[1].isModified():
|
2005-07-06 23:10:19 +00:00
|
|
|
modList.append(element)
|
|
|
|
|
|
|
|
if len(modList) == 0:
|
|
|
|
time.sleep(conf["polltime"])
|
|
|
|
continue
|
|
|
|
|
|
|
|
# Gets the failure list from the log file. For a given IP,
|
|
|
|
# takes only the service which has the most password failures.
|
|
|
|
for element in modList:
|
2005-07-13 10:01:01 +00:00
|
|
|
e = element[1].getFailures()
|
2005-07-06 23:10:19 +00:00
|
|
|
for key in e.iterkeys():
|
2005-07-13 10:01:01 +00:00
|
|
|
if element[3].has_key(key):
|
|
|
|
element[3][key] = (element[3][key][0] + e[key][0],
|
|
|
|
e[key][1])
|
2005-07-06 23:10:19 +00:00
|
|
|
else:
|
2005-07-13 10:01:01 +00:00
|
|
|
element[3][key] = (e[key][0], e[key][1])
|
2005-07-06 23:10:19 +00:00
|
|
|
|
|
|
|
# Remove the oldest failure attempts from the global list.
|
|
|
|
# We iterate the failure list and ban IP that make
|
|
|
|
# *retryAllowed* login failures.
|
2005-07-13 10:01:01 +00:00
|
|
|
unixTime = time.time()
|
|
|
|
for element in logFwList:
|
|
|
|
fails = element[3].copy()
|
|
|
|
findTime = element[1].getFindTime()
|
|
|
|
for attempt in fails:
|
|
|
|
failTime = fails[attempt][1]
|
|
|
|
if failTime < unixTime - findTime:
|
|
|
|
del element[3][attempt]
|
2005-08-06 19:43:43 +00:00
|
|
|
elif fails[attempt][0] >= element[1].getMaxRetry():
|
2005-09-27 15:45:26 +00:00
|
|
|
aInfo = {"section": element[0],
|
|
|
|
"ip": attempt,
|
2005-07-13 10:01:01 +00:00
|
|
|
"failures": element[3][attempt][0],
|
|
|
|
"failtime": failTime}
|
|
|
|
logSys.info(element[0] + ": " + aInfo["ip"] +
|
|
|
|
" has " + `aInfo["failures"]` +
|
|
|
|
" login failure(s). Banned.")
|
|
|
|
element[2].addBanIP(aInfo, conf["debug"])
|
|
|
|
# Send a mail notification
|
|
|
|
if 'mail' in locals():
|
|
|
|
mail.sendmail(mailConf["subject"],
|
|
|
|
mailConf["message"], aInfo)
|
|
|
|
del element[3][attempt]
|
2005-10-12 14:16:52 +00:00
|
|
|
except ExternalError, e:
|
|
|
|
# Something wrong while dealing with Iptables.
|
|
|
|
# May be chain got removed?
|
|
|
|
logSys.error("Fail2Ban got a problem: " + e.__str__())
|
|
|
|
if (unixTime - lastRestartTime > legitRestartTime) and (restarts < maxRestarts):
|
|
|
|
logSys.error("Reinitializing firewalls for the %dst time "%restarts)
|
|
|
|
lastRestartTime = time.time()
|
|
|
|
else:
|
|
|
|
logSys.error("Exiting: restarts follow too often, or too many restart attempts")
|
|
|
|
killApp()
|
|
|
|
|
|
|
|
# save firewalls to keep a list of IPs for rebanning
|
|
|
|
logFwListCopy = copy.deepcopy(logFwList)
|
|
|
|
# restore as much as possible
|
2005-10-12 05:11:16 +00:00
|
|
|
restoreFwRules()
|
2005-10-12 14:16:52 +00:00
|
|
|
# reinitialize all the chains
|
|
|
|
initializeFwRules()
|
|
|
|
# restore the lists of baned IPs
|
|
|
|
logFwList = logFwListCopy
|
|
|
|
# reBan known IPs
|
|
|
|
reBan()
|
2005-07-06 23:10:19 +00:00
|
|
|
except KeyboardInterrupt:
|
|
|
|
# When the user press <ctrl>+<c> we exit nicely.
|
|
|
|
killApp()
|