Merge commit '0.8.6-69-gb4099da' into debian-devel

* commit '0.8.6-69-gb4099da': (57 commits)
  DOC: Adjusted header for config/*.conf to mention .local and way to comment
  Fixed addBannedIP to add enough failures to trigger a ban, rather than just one failure.
  Fix Gentoo initd script (drop extra_commands)
  ENH: catch failed ssh logins due to being listed in DenyUsers. Close gh-47 (Closes: #669063)
  DOC: comment in jail.conf for the need of multiple jails for asterisk
  Add the INCLUDE section to use __pid_re feature
  Disable asterisk jail by default
  Change jail for asterisk, add support for SIP and SIP-TLS on TCP and UDP ports
  Change NOTICE by NOTICE%(__pid_re)s
  Added a warning for the recidive jail
  BF: fail2ban-regex -- adding forgotten char for -v
  Remove custom bantime
  Add sample log file for asterisk
  Add $ at the end of the failregex
  ENH: fail2ban-regex -- quieter by default and added --verbose mode
  ENH: minor, just pythonized some parts of fail2ban-regex summary
  ENH: rudimentary __repr__ for Filter and Jail + moved usedns into set method
  BF: allow trailing whitespace in few missing it regexes for sshd.conf
  BF+ENH: added %m-%d-%Y pattern + do not add %Y for Feb 29 fix if already present in the pattern
  minor comment into TODO
  ...
debian-devel
Yaroslav Halchenko 2012-06-06 23:39:22 -04:00
commit 59baf83110
70 changed files with 644 additions and 214 deletions

View File

@ -20,6 +20,7 @@ client/configurator.py
client/csocket.py
server/asyncserver.py
server/filter.py
server/filterpyinotify.py
server/filtergamin.py
server/filterpoll.py
server/iso8601.py

5
README
View File

@ -22,6 +22,11 @@ Required:
>=python-2.3 (http://www.python.org)
Optional:
pyinotify:
>=linux-2.6.13
>=python-2.4
>=pyinotify-0.8.3 (https://github.com/seb-m/pyinotify)
Gamin:
>=gamin-0.0.21 (http://www.gnome.org/~veillard/gamin)
To install, just do:

6
TODO
View File

@ -19,10 +19,8 @@ Legend:
- Add timeout to external commands (signal alarm, watchdog thread, etc)
- New backend: pyinotify
- Uniformize filters and actions name. Use the software name (openssh, postfix,
proftp)
proftp) and possible qualifier (e.g. auth) after a '-'
- Added <USER> tag for failregex. Add features using this information. Maybe add
more tags
@ -52,3 +50,5 @@ Legend:
# better return values in function
# refactoring in server.py, actions.py, filter.py
* New backend: pyinotify

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Yaroslav Halchenko
# Modified: Cyril Jaquier

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
# Modified by: Yaroslav Halchenko (SafeConfigParserWithIncludes)

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#
@ -65,6 +65,7 @@ class JailReader(ConfigReader):
["int", "maxretry", 3],
["int", "findtime", 600],
["int", "bantime", 600],
["string", "usedns", "warn"],
["string", "failregex", None],
["string", "ignoreregex", None],
["string", "ignoreip", None],
@ -122,6 +123,8 @@ class JailReader(ConfigReader):
stream.append(["set", self.__name, "findtime", self.__opts[opt]])
elif opt == "bantime":
stream.append(["set", self.__name, "bantime", self.__opts[opt]])
elif opt == "usedns":
stream.append(["set", self.__name, "usedns", self.__opts[opt]])
elif opt == "failregex":
stream.append(["set", self.__name, "addfailregex", self.__opts[opt]])
elif opt == "ignoreregex":

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
# Author: Arturo 'Buanzo' Busleiman

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#
@ -62,6 +62,7 @@ protocol = [
["set <JAIL> delignoreregex <INDEX>", "removes the regular expression at <INDEX> for ignoreregex"],
["set <JAIL> findtime <TIME>", "sets the number of seconds <TIME> for which the filter will look back for <JAIL>"],
["set <JAIL> bantime <TIME>", "sets the number of seconds <TIME> a host will be banned for <JAIL>"],
["set <JAIL> usedns <VALUE>", "sets the usedns mode for <JAIL>"],
["set <JAIL> banip <IP>", "manually Ban <IP> for <JAIL>"],
["set <JAIL> maxretry <RETRY>", "sets the number of failures <RETRY> before banning the host for <JAIL>"],
["set <JAIL> addaction <ACT>", "adds a new action named <NAME> for <JAIL>"],
@ -80,6 +81,7 @@ protocol = [
["get <JAIL> ignoreregex", "gets the list of regular expressions which matches patterns to ignore for <JAIL>"],
["get <JAIL> findtime", "gets the time for which the filter will look back for failures for <JAIL>"],
["get <JAIL> bantime", "gets the time a host is banned for <JAIL>"],
["get <JAIL> usedns", "gets the usedns setting for <JAIL>"],
["get <JAIL> maxretry", "gets the number of failures allowed for <JAIL>"],
["get <JAIL> addaction", "gets the last action which has been added for <JAIL>"],
["get <JAIL> actionstart <ACT>", "gets the start command for the action <ACT> for <JAIL>"],

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -204,7 +204,7 @@ dest = reports@dshield.org
# Option: tmpfile
# Notes.: Base name of temporary files used for buffering
# Values: [ STRING ] Default: /tmp/fail2ban-dshield
# Values: [ STRING ] Default: /var/run/fail2ban/tmp-dshield
#
tmpfile = /var/run/fail2ban/tmp-dshield

View File

@ -139,6 +139,6 @@ mnwurl = http://mynetwatchman.com/insertwebreport.asp
# Option: tmpfile
# Notes.: Base name of temporary files
# Values: [ STRING ] Default: /tmp/fail2ban-mynetwatchman
# Values: [ STRING ] Default: /var/run/fail2ban/tmp-mynetwatchman
#
tmpfile = /var/run/fail2ban/tmp-mynetwatchman

View File

@ -1,8 +1,12 @@
# Fail2Ban configuration file
# Fail2Ban main configuration file
#
# Author: Cyril Jaquier
# Comments: use '#' for comment lines and ';' for inline comments
#
# $Revision$
# Changes: in most of the cases you should not modify this
# file, but provide customizations in fail2ban.local file, e.g.:
#
# [Definition]
# loglevel = 4
#
[Definition]

View File

@ -0,0 +1,39 @@
# Fail2Ban configuration file
#
# Author: Xavier Devlamynck
#
# $Revision$
#
[INCLUDES]
# Read common prefixes. If any customizations available -- read them from
# common.local
before = common.conf
[Definition]
# Option: failregex
# Notes.: regex to match the password failures messages in the logfile. The
# host must be matched by a group named "host". The tag "<HOST>" can
# be used for standard IP/hostname matching and is only an alias for
# (?:::f{4,6}:)?(?P<host>\S+)
# Values: TEXT
#
failregex = NOTICE%(__pid_re)s .*: Registration from '.*' failed for '<HOST>' - Wrong password$
NOTICE%(__pid_re)s .*: Registration from '.*' failed for '<HOST>' - No matching peer found$
NOTICE%(__pid_re)s .*: Registration from '.*' failed for '<HOST>' - Username/auth name mismatch$
NOTICE%(__pid_re)s .*: Registration from '.*' failed for '<HOST>' - Device does not match ACL$
NOTICE%(__pid_re)s .*: Registration from '.*' failed for '<HOST>' - Peer is not supposed to register$
NOTICE%(__pid_re)s .*: Registration from '.*' failed for '<HOST>' - ACL error (permit/deny)$
NOTICE%(__pid_re)s <HOST> failed to authenticate as '.*'$
NOTICE%(__pid_re)s .*: No registration for peer '.*' \(from <HOST>\)$
NOTICE%(__pid_re)s .*: Host <HOST> failed MD5 authentication for '.*' (.*)$
NOTICE%(__pid_re)s .*: Failed to authenticate user .*@<HOST>.*$
# Option: ignoreregex
# Notes.: regex to ignore. If this regex matches, the line is ignored.
# Values: TEXT
#
ignoreregex =

View File

@ -0,0 +1,19 @@
# Fail2Ban configuration file
#
# Author: Francois Boulogne <fboulogne@april.org>
#
[Definition]
# Option: failregex
# Notes.: regex to match wrong passwords as notified by lighttpd's auth Module
# Values: TEXT
#
failregex = .*http_auth.*password doesn\'t match.*IP: <HOST>\s*$
# Option: ignoreregex
# Notes.: regex to ignore. If this regex matches, the line is ignored.
# Values: TEXT
#
ignoreregex =

View File

@ -0,0 +1,38 @@
# Fail2Ban configuration file
#
# Author: Tom Hendrikx, modifications by Amir Caspi
#
# This filter monitors the fail2ban log file, and enables you to add long
# time bans for ip addresses that get banned by fail2ban multiple times.
# Reasons to use this: block very persistent attackers for a longer time,
# stop receiving email notifications about the same attacker over and
# over again.
#
# This jail is only useful if you set the 'findtime' and 'bantime' parameters
# in jail.conf to a higher value than the other jails. Also, this jail has its
# drawbacks, namely in that it works only with iptables, or if you use a
# different blocking mechanism for this jail versus others (e.g. hostsdeny
# for most jails, and shorewall for this one).
#
[Definition]
# The name of the jail that this filter is used for. In jail.conf, name the
# jail using this filter 'recidive', or change this line!
_jailname = recidive
# Option: failregex
# Notes.: regex to match the password failures messages in the logfile. The
# host must be matched by a group named "host". The tag "<HOST>" can
# be used for standard IP/hostname matching and is only an alias for
# (?:::f{4,6}:)?(?P<host>\S+)
# Values: TEXT
#
failregex = fail2ban.actions:\s+WARNING\s+\[(?:.*)\]\s+Ban\s+<HOST>
# Option: ignoreregex
# Notes.: regex to ignore. If this regex matches, the line is ignored.
# Values: TEXT
#
# Ignore our own bans, to keep our counts exact.
ignoreregex = fail2ban.actions:\s+WARNING\s+\[%(_jailname)s\]\s+Ban\s+<HOST>

View File

@ -25,10 +25,11 @@ _daemon = sshd
#
failregex = ^%(__prefix_line)s(?:error: PAM: )?Authentication failure for .* from <HOST>\s*$
^%(__prefix_line)s(?:error: PAM: )?User not known to the underlying authentication module for .* from <HOST>\s*$
^%(__prefix_line)sFailed (?:password|publickey) for .* from <HOST>(?: port \d*)?(?: ssh\d*)?$
^%(__prefix_line)sFailed (?:password|publickey) for .* from <HOST>(?: port \d*)?(?: ssh\d*)?\s*$
^%(__prefix_line)sROOT LOGIN REFUSED.* FROM <HOST>\s*$
^%(__prefix_line)s[iI](?:llegal|nvalid) user .* from <HOST>\s*$
^%(__prefix_line)sUser .+ from <HOST> not allowed because not listed in AllowUsers$
^%(__prefix_line)sUser .+ from <HOST> not allowed because not listed in AllowUsers\s*$
^%(__prefix_line)sUser .+ from <HOST> not allowed because listed in DenyUsers\s*$
^%(__prefix_line)sauthentication failure; logname=\S* uid=\S* euid=\S* tty=\S* ruser=\S* rhost=<HOST>(?:\s+user=.*)?\s*$
^%(__prefix_line)srefused connect from \S+ \(<HOST>\)\s*$
^%(__prefix_line)sAddress <HOST> .* POSSIBLE BREAK-IN ATTEMPT!*\s*$

View File

@ -1,8 +1,15 @@
# Fail2Ban configuration file
# Fail2Ban jail specifications file
#
# Author: Cyril Jaquier
# Comments: use '#' for comment lines and ';' for inline comments
#
# $Revision$
# Changes: in most of the cases you should not modify this
# file, but provide customizations in jail.local file, e.g.:
#
# [DEFAULT]
# bantime = 3600
#
# [ssh-iptables]
# enabled = true
#
# The DEFAULT allows a global definition of the options. They can be overridden
@ -25,16 +32,29 @@ findtime = 600
# "maxretry" is the number of failures before a host get banned.
maxretry = 3
# "backend" specifies the backend used to get files modification. Available
# options are "gamin", "polling" and "auto". This option can be overridden in
# each jail too (use "gamin" for a jail and "polling" for another).
# "backend" specifies the backend used to get files modification.
# Available options are "pyinotify", "gamin", "polling" and "auto".
# This option can be overridden in each jail as well.
#
# gamin: requires Gamin (a file alteration monitor) to be installed. If Gamin
# is not installed, Fail2ban will use polling.
# pyinotify: requires pyinotify (a file alteration monitor) to be installed.
# If pyinotify is not installed, Fail2ban will use auto.
# gamin: requires Gamin (a file alteration monitor) to be installed.
# If Gamin is not installed, Fail2ban will use auto.
# polling: uses a polling algorithm which does not require external libraries.
# auto: will choose Gamin if available and polling otherwise.
# auto: will try to use the following backends, in order:
# pyinotify, gamin, polling.
backend = auto
# "usedns" specifies if jails should trust hostnames in logs,
# warn when reverse DNS lookups are performed, or ignore all hostnames in logs
#
# yes: if a hostname is encountered, a reverse DNS lookup will be performed.
# warn: if a hostname is encountered, a reverse DNS lookup will be performed,
# but it will be logged as a warning.
# no: if a hostname is encountered, will not be used for banning,
# but it will be logged as info.
usedns = warn
# This jail corresponds to the standard configuration in Fail2ban 0.6.
# The mail-whois action send a notification e-mail with a whois request
@ -180,6 +200,18 @@ filter = lighttpd-fastcgi
logpath = /var/log/lighttpd/error.log
maxretry = 2
# Same as above for mod_auth
# It catches wrong authentifications
[lighttpd-auth]
enabled = false
port = http,https
filter = lighttpd-auth
# adapt the following two items as needed
logpath = /var/log/lighttpd/error.log
maxretry = 2
# This jail uses ipfw, the standard firewall on FreeBSD. The "ignoreip"
# option is overridden in this jail. Moreover, the action "mail-whois" defines
# the variable "name" which contains a comma using "". The characters '' are
@ -239,3 +271,38 @@ action = iptables-multiport[name=Named, port="domain,953", protocol=tcp]
logpath = /var/log/named/security.log
ignoreip = 168.192.0.1
# Multiple jails, 1 per protocol, are necessary ATM:
# see https://github.com/fail2ban/fail2ban/issues/37
[asterisk-tcp]
enabled = false
filter = asterisk
action = iptables-multiport[name=asterisk-tcp, port="5060,5061", protocol=tcp]
sendmail-whois[name=Asterisk, dest=you@example.com, sender=fail2ban@example.com]
logpath = /var/log/asterisk/messages
maxretry = 10
[asterisk-udp]
enabled = false
filter = asterisk
action = iptables-multiport[name=asterisk-udp, port="5060,5061", protocol=udp]
sendmail-whois[name=Asterisk, dest=you@example.com, sender=fail2ban@example.com]
logpath = /var/log/asterisk/messages
maxretry = 10
# Jail for more extended banning of persistent abusers
# !!! WARNING !!!
# Make sure that your loglevel specified in fail2ban.conf/.local
# is not at DEBUG level -- which might then cause fail2ban to fall into
# an infinite loop constantly feeding itself with non-informative lines
[recidive]
enabled = false
filter = recidive
logpath = /var/log/fail2ban.log
action = iptables-allports[name=recidive]
sendmail-whois-lines[name=recidive, logpath=/var/log/fail2ban.log]
bantime = 604800 # 1 week
findtime = 86400 # 1 day
maxretry = 5

View File

@ -16,7 +16,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -13,7 +13,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#
@ -29,7 +29,7 @@ import getopt, sys, time, logging, os
# Inserts our own modules path first in the list
# fix for bug #343821
sys.path.insert(1, "/usr/share/fail2ban")
#sys.path.insert(1, "/usr/share/fail2ban")
from client.configparserinc import SafeConfigParserWithIncludes
from ConfigParser import NoOptionError, NoSectionError, MissingSectionHeaderError
@ -72,6 +72,7 @@ class Fail2banRegex:
self.__filter = Filter(None)
self.__ignoreregex = list()
self.__failregex = list()
self.__verbose = False
# Setup logging
logging.getLogger("fail2ban").handlers = []
self.__hdlr = logging.StreamHandler(Fail2banRegex.test)
@ -79,6 +80,7 @@ class Fail2banRegex:
formatter = logging.Formatter("%(message)s")
# tell the handler to use this format
self.__hdlr.setFormatter(formatter)
self.__logging_level = self.__verbose and logging.DEBUG or logging.WARN
logging.getLogger("fail2ban").addHandler(self.__hdlr)
logging.getLogger("fail2ban").setLevel(logging.ERROR)
@ -106,6 +108,7 @@ class Fail2banRegex:
print "Options:"
print " -h, --help display this help message"
print " -V, --version print the version"
print " -v, --verbose verbose output"
print
print "Log:"
print " string a string representing a log line"
@ -132,6 +135,8 @@ class Fail2banRegex:
elif opt[0] in ["-V", "--version"]:
self.dispVersion()
sys.exit(0)
elif opt[0] in ["-v", "--verbose"]:
self.__verbose = True
#@staticmethod
def logIsFile(value):
@ -199,7 +204,7 @@ class Fail2banRegex:
def testIgnoreRegex(self, line):
found = False
for regex in self.__ignoreregex:
logging.getLogger("fail2ban").setLevel(logging.DEBUG)
logging.getLogger("fail2ban").setLevel(self.__logging_level)
try:
self.__filter.addIgnoreRegex(regex.getFailRegex())
try:
@ -211,7 +216,7 @@ class Fail2banRegex:
return False
finally:
self.__filter.delIgnoreRegex(0)
logging.getLogger("fail2ban").setLevel(logging.CRITICAL)
logging.getLogger("fail2ban").setLevel(self.__logging_level)
def testRegex(self, line):
found = False
@ -249,49 +254,26 @@ class Fail2banRegex:
print "======="
print
def print_failregexes(title, failregexes):
# Print title
cnt = 1
print "Failregex"
print "|- Regular expressions:"
for failregex in self.__failregex:
print "| [" + str(cnt) + "] " + failregex.getFailRegex()
cnt += 1
cnt = 1
print "|"
# Print stats
cnt = 1
total = 0
print "`- Number of matches:"
for failregex in self.__failregex:
total, out = 0, []
for cnt, failregex in enumerate(failregexes):
match = failregex.getStats()
total += match
print " [" + str(cnt) + "] " + str(match) + " match(es)"
cnt += 1
if (match or self.__verbose):
out.append("| %d) [%d] %s" % (cnt+1, match, failregex.getFailRegex()))
print "%s: %d total" % (title, total)
if len(out):
print "|- #) [# of hits] regular expression"
print '\n'.join(out)
print '`-'
print
return total
# Print title
cnt = 1
print "Ignoreregex"
print "|- Regular expressions:"
for failregex in self.__ignoreregex:
print "| [" + str(cnt) + "] " + failregex.getFailRegex()
cnt += 1
cnt = 1
total = print_failregexes("Failregex", self.__failregex)
_ = print_failregexes("Ignoreregex", self.__ignoreregex)
print "|"
# Print stats
cnt = 1
print "`- Number of matches:"
for failregex in self.__ignoreregex:
match = failregex.getStats()
print " [" + str(cnt) + "] " + str(match) + " match(es)"
cnt += 1
print
print "Summary"
print "======="
print
@ -304,26 +286,21 @@ class Fail2banRegex:
return False
else:
# Print stats
cnt = 1
print "Addresses found:"
for failregex in self.__failregex:
print "[" + str(cnt) + "]"
for cnt, failregex in enumerate(self.__failregex):
if self.__verbose or len(failregex.getIPList()):
print "[%d]" % (cnt+1)
for ip in failregex.getIPList():
timeTuple = time.localtime(ip[1])
timeString = time.strftime("%a %b %d %H:%M:%S %Y", timeTuple)
if ip[2]:
dup = " (already matched)"
else:
dup = ""
print " " + ip[0] + " (" + timeString + ")" + dup
cnt += 1
print " %s (%s)%s" % (
ip[0], timeString, ip[2] and " (already matched)" or "")
print
print "Date template hits:"
for template in self.__filter.dateDetector.getTemplates():
if self.__verbose or template.getHits():
print `template.getHits()` + " hit(s): " + template.getName()
print
print "Success, the total number of match is " + str(total)
@ -337,16 +314,17 @@ if __name__ == "__main__":
fail2banRegex = Fail2banRegex()
# Reads the command line options.
try:
cmdOpts = 'hV'
cmdLongOpts = ['help', 'version']
cmdOpts = 'hVcv'
cmdLongOpts = ['help', 'version', 'verbose']
optList, args = getopt.getopt(sys.argv[1:], cmdOpts, cmdLongOpts)
except getopt.GetoptError:
fail2banRegex.dispUsage()
sys.exit(-1)
# Process command line
fail2banRegex.getCmdLineOptions(optList)
# We need exactly 3 parameters
if not len(sys.argv) in (3, 4):
# We need 2 or 3 parameters
if not len(args) in (2, 3):
fail2banRegex.dispUsage()
sys.exit(-1)
else:
@ -355,17 +333,17 @@ if __name__ == "__main__":
print "============="
print
if len(sys.argv) == 4:
if fail2banRegex.readIgnoreRegex(sys.argv[3]) == False:
sys.exit(-1)
cmd_log, cmd_regex = args[:2]
if fail2banRegex.readRegex(sys.argv[2]) == False:
sys.exit(-1)
if len(args) == 3:
fail2banRegex.readIgnoreRegex(args[2]) or sys.exit(-1)
if fail2banRegex.logIsFile(sys.argv[1]):
fail2banRegex.readRegex(cmd_regex) or sys.exit(-1)
if fail2banRegex.logIsFile(cmd_log):
try:
hdlr = open(sys.argv[1])
print "Use log file : " + sys.argv[1]
hdlr = open(cmd_log)
print "Use log file : " + cmd_log
print
for line in hdlr:
fail2banRegex.testIgnoreRegex(line)
@ -376,15 +354,12 @@ if __name__ == "__main__":
sys.exit(-1)
else:
if len(sys.argv[1]) > 53:
stripLog = sys.argv[1][0:50] + "..."
stripLog = cmd_log[0:50] + "..."
else:
stripLog = sys.argv[1]
stripLog = cmd_log
print "Use single line: " + stripLog
print
fail2banRegex.testIgnoreRegex(sys.argv[1])
fail2banRegex.testRegex(sys.argv[1])
fail2banRegex.testIgnoreRegex(cmd_log)
fail2banRegex.testRegex(cmd_log)
if fail2banRegex.printStats():
sys.exit(0)
else:
sys.exit(-1)
fail2banRegex.printStats() or sys.exit(-1)

View File

@ -16,7 +16,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -16,7 +16,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -13,7 +13,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# This script can be used to collect data for Cacti. One parameter is needed,
# the jail name. It must be a currently running jail. The script returns two

View File

@ -13,13 +13,13 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# Author: Sireyessire, Cyril Jaquier
#
# $Revision$
opts="reload showlog"
extra_started_commands="reload showlog"
FAIL2BAN="/usr/bin/fail2ban-client ${FAIL2BAN_OPTIONS}"

View File

@ -45,9 +45,8 @@ check_processes_fail2ban()
}
######################################################################
# first check in the Background, PID will be killed when no response
# after 10 seconds, might be possible, otherwise the scipt will be
# pressent in your memory all the time
#
# after 10 seconds, might be possible, otherwise the script will be
# present in your memory all the time
######################################################################
check_processes_fail2ban &
@ -68,7 +67,7 @@ fi
done
######################################################################
# when the Server response (doesent mean the FAIL2BAN is working)
# when the Server response (does not mean the FAIL2BAN is working)
# in the first step, then it will run again and test the Service
# and provide the real status
######################################################################
@ -83,19 +82,19 @@ fi
######################################################################
# Mainmenu
# Main Menu
######################################################################
final_exit=$exit_fail2ban
if [ $final_exit -eq 0 ]; then
echo "SYSTEM OK - Fail2ban is working normaly"
echo "SYSTEM OK - Fail2ban is working normally"
exitstatus=$STATE_OK
elif [ $final_exit -ne "0" ]; then
echo "SYSTEM WARNING - Fail2Ban is not working"
######################################################################
# If don't have a Nagios Server for monitoring, remove the comment and
# add your Mail Addres. You can check it with a Cron Job once a hour.
# add your Mail Address. You can check it with a Cron Job once an hour.
# put a txt file on your server and describe how to fix the issue, this
# could be attached to the mail.
######################################################################

View File

@ -5,7 +5,7 @@ HELP:
1.) stop the Service
/etc/init.d/fail2ban stop
2.) delete the socket if avalible
2.) delete the socket if available
rm /tmp/fail2ban.sock
3.) start the Service

View File

@ -251,7 +251,7 @@ action <ACT> for <JAIL>
Written by Cyril Jaquier <cyril.jaquier@fail2ban.org>.
Many contributions by Yaroslav O. Halchenko <debian@onerussian.com>.
.SH "REPORTING BUGS"
Report bugs to <cyril.jaquier@fail2ban.org>
Report bugs on https://github.com/fail2ban/fail2ban/issues
.SH COPYRIGHT
Copyright \(co 2004-2008 Cyril Jaquier
.br

View File

@ -42,7 +42,7 @@ path to a filter file (filter.d/sshd.conf)
Written by Cyril Jaquier <cyril.jaquier@fail2ban.org>.
Many contributions by Yaroslav O. Halchenko <debian@onerussian.com>.
.SH "REPORTING BUGS"
Report bugs to <cyril.jaquier@fail2ban.org>
Report bugs on https://github.com/fail2ban/fail2ban/issues
.SH COPYRIGHT
Copyright \(co 2004-2008 Cyril Jaquier
.br

View File

@ -35,7 +35,7 @@ print the version
Written by Cyril Jaquier <cyril.jaquier@fail2ban.org>.
Many contributions by Yaroslav O. Halchenko <debian@onerussian.com>.
.SH "REPORTING BUGS"
Report bugs to <cyril.jaquier@fail2ban.org>
Report bugs on https://github.com/fail2ban/fail2ban/issues
.SH COPYRIGHT
Copyright \(co 2004-2008 Cyril Jaquier
.br

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#
@ -163,13 +163,13 @@ class Actions(JailThread):
aInfo["time"] = bTicket.getTime()
aInfo["matches"] = "".join(bTicket.getMatches())
if self.__banManager.addBanTicket(bTicket):
logSys.warn("[%s] Ban %s" % (self.jail.getName(), aInfo["ip"]))
logSys.warn("[%s] Ban %s" % (self.jail.getName(), str(aInfo["ip"])))
for action in self.__actions:
action.execActionBan(aInfo)
return True
else:
logSys.warn("[%s] %s already banned" % (self.jail.getName(),
aInfo["ip"]))
str(aInfo["ip"])))
return False
##

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#
@ -117,6 +117,12 @@ class DateDetector:
template.setRegex("\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}")
template.setPattern("%d-%m-%Y %H:%M:%S")
self.__templates.append(template)
# 01-27-2012 16:22:44.252
template = DateStrptime()
template.setName("Month-Day-Year Hour:Minute:Second[.Millisecond]")
template.setRegex("\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}")
template.setPattern("%m-%d-%Y %H:%M:%S")
self.__templates.append(template)
# TAI64N
template = DateTai64n()
template.setName("TAI64N")

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#
@ -140,12 +140,22 @@ class DateStrptime(DateTemplate):
conv = self.convertLocale(dateMatch.group())
try:
date = list(time.strptime(conv, self.getPattern()))
except ValueError, e:
except (ValueError, re.error), e:
# Try to add the current year to the pattern. Should fix
# the "Feb 29" issue.
opattern = self.getPattern()
# makes sense only if %Y is not in already:
if not '%Y' in opattern:
pattern = "%s %%Y" % opattern
conv += " %s" % MyTime.gmtime()[0]
pattern = "%s %%Y" % self.getPattern()
date = list(time.strptime(conv, pattern))
else:
# we are helpless here
raise ValueError(
"Given pattern %r does not match. Original "
"exception was %r and Feb 29 workaround could not "
"be tested due to already present year mark in the "
"pattern" % (opattern, e))
if date[0] < 2000:
# There is probably no year field in the logs
date[0] = MyTime.gmtime()[0]

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#
@ -64,6 +64,8 @@ class Filter(JailThread):
self.__failRegex = list()
## The regular expression list with expressions to ignore.
self.__ignoreRegex = list()
## Use DNS setting
self.__useDns = "warn"
## The amount of time to look back.
self.__findTime = 6000
## The ignore IP list.
@ -71,9 +73,12 @@ class Filter(JailThread):
self.dateDetector = DateDetector()
self.dateDetector.addDefaultTemplate()
logSys.debug("Created Filter")
logSys.debug("Created %s" % self)
def __repr__(self):
return "%s(%r)" % (self.__class__.__name__, self.jail)
##
# Add a regular expression which matches the failure.
#
@ -139,6 +144,21 @@ class Filter(JailThread):
ignoreRegex.append(regex.getRegex())
return ignoreRegex
##
# Set the Use DNS mode
# @param value the usedns mode
def setUseDns(self, value):
logSys.debug("Setting usedns = %s for %s" % (value, self))
self.__useDns = value
##
# Get the usedns mode
# @return the usedns mode
def getUseDns(self):
return self.__useDns
##
# Set the time needed to find a failure.
#
@ -194,7 +214,9 @@ class Filter(JailThread):
def addBannedIP(self, ip):
unixTime = time.time()
for i in xrange(self.failManager.getMaxRetry()):
self.failManager.addFailure(FailTicket(ip, unixTime))
return ip
##
@ -325,7 +347,7 @@ class Filter(JailThread):
else:
try:
host = failRegex.getHost()
ipMatch = DNSUtils.textToIp(host)
ipMatch = DNSUtils.textToIp(host, self.__useDns)
if ipMatch:
for ip in ipMatch:
failList.append([ip, date])
@ -564,13 +586,16 @@ class DNSUtils:
isValidIP = staticmethod(isValidIP)
#@staticmethod
def textToIp(text):
def textToIp(text, useDns):
""" Return the IP of DNS found in a given text.
"""
if useDns == "no":
return None
else:
ipList = list()
# Search for plain IP
plainIP = DNSUtils.searchIP(text)
if not plainIP == None:
if not plainIP is None:
plainIPStr = plainIP.group(0)
if DNSUtils.isValidIP(plainIPStr):
ipList.append(plainIPStr)
@ -579,6 +604,9 @@ class DNSUtils:
ip = DNSUtils.dnsToIp(text)
for e in ip:
ipList.append(e)
if useDns == "warn":
logSys.warning("Determined IP using DNS Reverse Lookup: %s = %s",
text, ipList)
return ipList
textToIp = staticmethod(textToIp)

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

155
server/filterpyinotify.py Normal file
View File

@ -0,0 +1,155 @@
# 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.
# Original author: Cyril Jaquier
__author__ = "Cyril Jaquier, Lee Clemens, Yaroslav Halchenko"
__copyright__ = "Copyright (c) 2004 Cyril Jaquier, 2011-2012 Lee Clemens, 2012 Yaroslav Halchenko"
__license__ = "GPL"
from failmanager import FailManagerEmpty
from filter import FileFilter
from mytime import MyTime
import time, logging, pyinotify
# Gets the instance of the logger.
logSys = logging.getLogger("fail2ban.filter")
##
# Log reader class.
#
# This class reads a log file and detects login failures or anything else
# that matches a given regular expression. This class is instantiated by
# a Jail object.
class FilterPyinotify(FileFilter):
##
# Constructor.
#
# Initialize the filter object with default values.
# @param jail the jail object
def __init__(self, jail):
FileFilter.__init__(self, jail)
self.__modified = False
# Pyinotify watch manager
self.__monitor = pyinotify.WatchManager()
self.__watches = dict()
logSys.debug("Created FilterPyinotify")
def callback(self, path):
self.getFailures(path)
try:
while True:
ticket = self.failManager.toBan()
self.jail.putFailTicket(ticket)
except FailManagerEmpty:
self.failManager.cleanup(MyTime.time())
self.dateDetector.sortTemplate()
self.__modified = False
##
# Add a log file path
#
# @param path log file path
def addLogPath(self, path, tail=False):
if self.containsLogPath(path):
logSys.error(path + " already exists")
else:
wd = self.__monitor.add_watch(path, pyinotify.IN_MODIFY)
self.__watches.update(wd)
FileFilter.addLogPath(self, path, tail)
logSys.info("Added logfile = %s" % path)
##
# Delete a log path
#
# @param path the log file to delete
def delLogPath(self, path):
if not self.containsLogPath(path):
logSys.error(path + " is not monitored")
else:
wdInt = self.__watches[path]
wd = self.__monitor.rm_watch(wdInt)
if wd[wdInt]:
del self.__watches[path]
FileFilter.delLogPath(self, path)
logSys.info("Removed logfile = %s" % path)
else:
logSys.error("Failed to remove watch on path: %s", path)
##
# Main loop.
#
# This function is the main loop of the thread. It checks if the
# file has been modified and looks for failures.
# @return True when the thread exits nicely
def run(self):
self.setActive(True)
self.__notifier = pyinotify.ThreadedNotifier(self.__monitor,
ProcessPyinotify(self))
self.__notifier.start()
while self._isActive():
if not self.getIdle():
self.__notifier.process_events()
if self.__notifier.check_events():
self.__notifier.read_events()
else:
time.sleep(self.getSleepTime())
# Cleanup pyinotify
self.__cleanup()
logSys.debug(self.jail.getName() + ": filter terminated")
return True
##
# Call super.stop() and then stop the 'Notifier'
def stop(self):
# Call super to set __isRunning
super(FilterPyinotify, self).stop()
# Now stop the Notifier, otherwise we're deadlocked
self.__notifier.stop()
##
# Deallocates the resources used by pyinotify.
def __cleanup(self):
del self.__notifier
del self.__monitor
class ProcessPyinotify(pyinotify.ProcessEvent):
def __init__(self, FileFilter, **kargs):
#super(ProcessPyinotify, self).__init__(**kargs)
# for some reason root class _ProcessEvent is old-style (is
# not derived from object), so to play safe let's avoid super
# for now, and call superclass directly
pyinotify.ProcessEvent.__init__(self, **kargs)
self.__FileFilter = FileFilter
pass
# just need default, since using mask on watch to limit events
def process_default(self, event):
logSys.debug("Callback for Event: %s" % event)
self.__FileFilter.callback(event.pathname)

View File

@ -15,16 +15,12 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#
# $Revision$
__author__ = "Cyril Jaquier"
__version__ = "$Revision$"
__date__ = "$Date$"
__copyright__ = "Copyright (c) 2004 Cyril Jaquier"
__author__ = "Cyril Jaquier, Lee Clemens, Yaroslav Halchenko"
__copyright__ = "Copyright (c) 2004 Cyril Jaquier, 2011-2012 Lee Clemens, 2012 Yaroslav Halchenko"
__license__ = "GPL"
import Queue, logging
@ -36,32 +32,73 @@ logSys = logging.getLogger("fail2ban.jail")
class Jail:
#Known backends. Each backend should have corresponding __initBackend method
_BACKENDS = ('pyinotify', 'gamin', 'polling')
def __init__(self, name, backend = "auto"):
self.__name = name
self.__queue = Queue.Queue()
self.__filter = None
logSys.info("Creating new jail '%s'" % self.__name)
if backend == "polling":
self.__initPoller()
else:
try:
self.__initGamin()
except ImportError:
self.__initPoller()
self.__action = Actions(self)
self._setBackend(backend)
def __initPoller(self):
def __repr__(self):
return "%s(%r)" % (self.__class__.__name__, self.__name)
def _setBackend(self, backend):
backend = backend.lower() # to assure consistent matching
backends = self._BACKENDS
if backend != 'auto':
# we have got strict specification of the backend to use
if not (backend in self._BACKENDS):
logSys.error("Unknown backend %s. Must be among %s or 'auto'"
% (backend, backends))
raise ValueError("Unknown backend %s. Must be among %s or 'auto'"
% (backend, backends))
# so explore starting from it till the 'end'
backends = backends[backends.index(backend):]
for b in backends:
initmethod = getattr(self, '_init%s' % b.capitalize())
try:
initmethod()
if backend != 'auto' and b != backend:
logSys.warning("Could only initiated %r backend whenever "
"%r was requested" % (b, backend))
else:
logSys.info("Initiated %r backend" % b)
self.__action = Actions(self)
return # we are done
except ImportError, e:
logSys.debug(
"Backend %r failed to initialize due to %s" % (b, e))
# log error since runtime error message isn't printed, INVALID COMMAND
logSys.error(
"Failed to initialize any backend for Jail %r" % self.__name)
raise RuntimeError(
"Failed to initialize any backend for Jail %r" % self.__name)
def _initPolling(self):
logSys.info("Jail '%s' uses poller" % self.__name)
from filterpoll import FilterPoll
self.__filter = FilterPoll(self)
def __initGamin(self):
def _initGamin(self):
# Try to import gamin
import gamin
logSys.info("Jail '%s' uses Gamin" % self.__name)
from filtergamin import FilterGamin
self.__filter = FilterGamin(self)
def _initPyinotify(self):
# Try to import pyinotify
import pyinotify
logSys.info("Jail '%s' uses pyinotify" % self.__name)
from filterpyinotify import FilterPyinotify
self.__filter = FilterPyinotify(self)
def setName(self, name):
self.__name = name

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#
@ -204,6 +204,12 @@ class Server:
def getIgnoreRegex(self, name):
return self.__jails.getFilter(name).getIgnoreRegex()
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)

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#
@ -154,6 +154,10 @@ class Transmitter:
value = int(command[2])
self.__server.delIgnoreRegex(name, value)
return self.__server.getIgnoreRegex(name)
elif command[1] == "usedns":
value = command[2]
self.__server.setUseDns(name, value)
return self.__server.getUseDns(name)
elif command[1] == "findtime":
value = command[2]
self.__server.setFindTime(name, int(value))
@ -231,6 +235,8 @@ class Transmitter:
return self.__server.getFailRegex(name)
elif command[1] == "ignoreregex":
return self.__server.getIgnoreRegex(name)
elif command[1] == "usedns":
return self.__server.getUseDns(name)
elif command[1] == "findtime":
return self.__server.getFindTime(name)
elif command[1] == "maxretry":

View File

@ -16,7 +16,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#
@ -67,6 +67,7 @@ class DateDetectorTest(unittest.TestCase):
"Jan 23 21:59:59",
"2005.01.23 21:59:59",
"23/01/2005 21:59:59",
"01-23-2005 21:59:59.252", # reported on f2b, causes Feb29 fix to break
):
log = sdate + "[sshd] error: PAM: Authentication failure"
# exclude

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#

View File

@ -0,0 +1,11 @@
# Sample log files for asterisk
[2012-02-13 17:21:54] NOTICE[1638] chan_sip.c: Registration from '<sip:301@asclepios.eyepea.be>' failed for '1.2.3.4' - Wrong password
[2012-02-13 17:18:22] NOTICE[1638] chan_sip.c: Registration from '<sip:301@asclepios.eyepea.be>' failed for '1.2.3.4' - No matching peer found
[2012-02-13 17:21:21] NOTICE[1638] chan_sip.c: Registration from '<sip:301@asclepios.eyepea.be>' failed for '1.2.3.4' - Username/auth name mismatch
[2012-02-13 17:32:01] NOTICE[1638] chan_sip.c: Registration from '<sip:301@asclepios.eyepea.be>' failed for '1.2.3.4' - Device does not match ACL
[2012-02-13 17:34:10] NOTICE[1638] chan_sip.c: Registration from '<sip:301@asclepios.eyepea.be>' failed for '1.2.3.4' - Peer is not supposed to register
[2012-02-13 17:36:23] NOTICE[1638] chan_sip.c: Registration from '<sip:301@asclepios.eyepea.be>' failed for '1.2.3.4' - ACL error (permit/deny)
[2012-02-13 17:53:59] NOTICE[1638] chan_iax2.c: Host 1.2.3.4 failed to authenticate as 'Fail2ban'
[2012-02-13 17:39:20] NOTICE[1638] chan_iax2.c: No registration for peer 'Fail2ban' (from 1.2.3.4)
[2012-02-13 17:44:26] NOTICE[1638] chan_iax2.c: Host 1.2.3.4 failed MD5 authentication for 'Fail2ban' (e7df7cd2ca07f4f1ab415d457a6e1c13 != 53ac4bc41ee4ec77888ed4aa50677247)
[2012-02-13 17:37:07] NOTICE[1638] chan_sip.c: Failed to authenticate user "Fail2ban" <sip:301@1.2.3.4>;tag=1r698745234

View File

@ -0,0 +1,2 @@
#authentification failure (mod_auth)
2011-12-25 17:09:20: (http_auth.c.875) password doesn't match for /gitweb/ username: francois, IP: 4.4.4.4

View File

@ -24,3 +24,6 @@ Nov 11 23:33:27 Server sshd[5174]: refused connect from _U2FsdGVkX19P3BCJmFBHhjL
#7 added exclamation mark to BREAK-IN
Oct 15 19:51:35 server sshd[7592]: Address 1.2.3.4 maps to 1234.bbbbbb.com, but this does not map back to the address - POSSIBLE BREAK-IN ATTEMPT
Oct 15 19:51:35 server sshd[7592]: Address 1.2.3.4 maps to 1234.bbbbbb.com, but this does not map back to the address - POSSIBLE BREAK-IN ATTEMPT!
#8 DenyUsers https://github.com/fail2ban/fail2ban/issues/47
Apr 16 22:01:15 al-ribat sshd[5154]: User root from 46.45.128.3 not allowed because listed in DenyUsers

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#
@ -222,12 +222,24 @@ class GetFailures(unittest.TestCase):
class DNSUtilsTests(unittest.TestCase):
def testUseDns(self):
res = DNSUtils.textToIp('www.example.com', 'no')
self.assertEqual(res, None)
res = DNSUtils.textToIp('www.example.com', 'warn')
self.assertEqual(res, ['192.0.43.10'])
res = DNSUtils.textToIp('www.example.com', 'yes')
self.assertEqual(res, ['192.0.43.10'])
def testTextToIp(self):
bogus = [
'doh1.2.3.4.buga.xxxxx.yyy',
'1.2.3.4.buga.xxxxx.yyy',
# Test hostnames
hostnames = [
'www.example.com',
'doh1.2.3.4.buga.xxxxx.yyy.invalid',
'1.2.3.4.buga.xxxxx.yyy.invalid',
]
"""Really bogus addresses which should have no matches"""
for s in bogus:
res = DNSUtils.textToIp(s)
for s in hostnames:
res = DNSUtils.textToIp(s, 'yes')
if s == 'www.example.com':
self.assertEqual(res, ['192.0.43.10'])
else:
self.assertEqual(res, [])

View File

@ -15,7 +15,7 @@
#
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Author: Cyril Jaquier
#