Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
49a44c6a82 | ||
|
|
d14d68d56c | ||
|
|
6830497241 | ||
|
|
5da1104701 | ||
|
|
38ab997cb3 | ||
|
|
587e626710 |
@@ -1,3 +1,4 @@
|
||||
.pc/*
|
||||
*~
|
||||
build
|
||||
dist
|
||||
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
#!/usr/bin/perl
|
||||
##########################################################################
|
||||
# $Id: fail2ban 150 2013-06-18 22:19:38Z mtremaine $
|
||||
##########################################################################
|
||||
# $Log: fail2ban,v $
|
||||
# Revision 1.5 2008/08/18 16:07:46 mike
|
||||
# Patches from Paul Gear <paul at libertysys.com> -mgt
|
||||
#
|
||||
# Revision 1.4 2008/06/30 23:07:51 kirk
|
||||
# fixed copyright holders for files where I know who they should be
|
||||
#
|
||||
# Revision 1.3 2008/03/24 23:31:26 kirk
|
||||
# added copyright/license notice to each script
|
||||
#
|
||||
# Revision 1.2 2006/12/15 04:53:59 bjorn
|
||||
# Additional filtering, by Willi Mann.
|
||||
#
|
||||
# Revision 1.1 2006/05/30 19:04:26 bjorn
|
||||
# Added fail2ban service, written by Yaroslav Halchenko.
|
||||
#
|
||||
# Written by Yaroslav Halchenko <debian@onerussian.com> for fail2ban
|
||||
#
|
||||
##########################################################################
|
||||
|
||||
########################################################
|
||||
## Copyright (c) 2008 Yaroslav Halchenko
|
||||
## Covered under the included MIT/X-Consortium License:
|
||||
## http://www.opensource.org/licenses/mit-license.php
|
||||
## All modifications and contributions by other persons to
|
||||
## this script are assumed to have been donated to the
|
||||
## Logwatch project and thus assume the above copyright
|
||||
## and licensing terms. If you want to make contributions
|
||||
## under your own copyright or a different license this
|
||||
## must be explicitly stated in the contribution an the
|
||||
## Logwatch project reserves the right to not accept such
|
||||
## contributions. If you have made significant
|
||||
## contributions to this script and want to claim
|
||||
## copyright please contact logwatch-devel@lists.sourceforge.net.
|
||||
#########################################################
|
||||
|
||||
use strict;
|
||||
use Logwatch ':all';
|
||||
|
||||
my $Debug = $ENV{'LOGWATCH_DEBUG'} || 0;
|
||||
my $Detail = $ENV{'LOGWATCH_DETAIL_LEVEL'} || 0;
|
||||
my $IgnoreHost = $ENV{'sshd_ignore_host'} || "";
|
||||
my $DebugCounter = 0;
|
||||
my $ReInitializations = 0;
|
||||
my @IptablesErrors = ();
|
||||
my @ActionErrors = ();
|
||||
my $NotValidIP = 0; # reported invalid IPs number
|
||||
my @OtherList = ();
|
||||
|
||||
my %ServicesBans = ();
|
||||
|
||||
if ( $Debug >= 5 ) {
|
||||
print STDERR "\n\nDEBUG: Inside Fail2Ban Filter \n\n";
|
||||
$DebugCounter = 1;
|
||||
}
|
||||
|
||||
while (defined(my $ThisLine = <STDIN>)) {
|
||||
if ( $Debug >= 5 ) {
|
||||
print STDERR "DEBUG($DebugCounter): $ThisLine";
|
||||
$DebugCounter++;
|
||||
}
|
||||
chomp($ThisLine);
|
||||
if ( ($ThisLine =~ /..,... DEBUG: /) or
|
||||
($ThisLine =~ /..,... \S*\s*: DEBUG /) or # syntax of 0.7.? fail2ban
|
||||
($ThisLine =~ /..,... INFO: (Fail2Ban v.* is running|Exiting|Enabled sections:)/) or
|
||||
($ThisLine =~ /INFO\s+Log rotation detected for/) or
|
||||
($ThisLine =~ /INFO\s+Jail.+(?:stopped|started|uses poller)/) or
|
||||
($ThisLine =~ /INFO\s+Changed logging target to/) or
|
||||
($ThisLine =~ /INFO\s+Creating new jail/) or
|
||||
($ThisLine =~ /..,... \S+\s*: INFO\s+(Set |Socket|Exiting|Gamin|Created|Added|Using)/) or # syntax of 0.7.? fail2ban
|
||||
($ThisLine =~ /..,... WARNING: Verbose level is /) or
|
||||
($ThisLine =~ /..,... WARNING: Restoring firewall rules/)
|
||||
)
|
||||
{
|
||||
if ( $Debug >= 6 ) {
|
||||
print STDERR "DEBUG($DebugCounter): line ignored\n";
|
||||
}
|
||||
} elsif ( my ($Service,$Action,$Host) = ($ThisLine =~ m/WARNING:?\s\[?(.*?)[]:]?\s(Ban|Unban)[^\.]* (\S+)/)) {
|
||||
if ( $Debug >= 6 ) {
|
||||
print STDERR "DEBUG($DebugCounter): Found $Action for $Service from $Host\n";
|
||||
}
|
||||
$ServicesBans{$Service}{$Host}{$Action}++;
|
||||
$ServicesBans{$Service}{"(all)"}{$Action}++;
|
||||
} elsif ( my ($Service,$Host,$NumFailures) = ($ThisLine =~ m/INFO: (\S+): (.+) has (\d+) login failure\(s\). Banned./)) {
|
||||
if ($Debug >= 4) {
|
||||
print STDERR "DEBUG: Found host $Host trying to access $Service - failed $NumFailures times\n";
|
||||
}
|
||||
push @{$ServicesBans{$Service}{$Host}{'Failures'}}, $NumFailures;
|
||||
} elsif ( my ($Service,$Host) = ($ThisLine =~ m/ ERROR:\s(.*):\s(\S+)\salready in ban list/)) {
|
||||
$ServicesBans{$Service}{$Host}{'AlreadyInTheList'}++;
|
||||
} elsif ( my ($Service,$Host) = ($ThisLine =~ m/WARNING\s*\[(.*)\]\s*(\S+)\s*already banned/)) {
|
||||
$ServicesBans{$Service}{$Host}{'AlreadyInTheList'}++;
|
||||
} elsif ( my ($Service,$Host) = ($ThisLine =~ m/ WARNING:\s(.*):\sReBan (\S+)/)) {
|
||||
$ServicesBans{$Service}{$Host}{'ReBan'}++;
|
||||
} elsif ($ThisLine =~ / ERROR:?\s*(Execution of command )?\'?iptables/) {
|
||||
push @IptablesErrors, "$ThisLine\n";
|
||||
} elsif ($ThisLine =~ /ERROR.*returned \d+$/) {
|
||||
push @ActionErrors, "$ThisLine\n";
|
||||
} elsif (($ThisLine =~ /..,... WARNING: \#\S+ reinitialization of firewalls/) or
|
||||
($ThisLine =~ / ERROR\s*Invariant check failed. Trying to restore a sane environment/)) {
|
||||
$ReInitializations++;
|
||||
} elsif ($ThisLine =~ /..,... WARNING: is not a valid IP address/) {
|
||||
# just ignore - this will be fixed within fail2ban and is harmless warning
|
||||
}
|
||||
else
|
||||
{
|
||||
# Report any unmatched entries...
|
||||
push @OtherList, "$ThisLine\n";
|
||||
}
|
||||
}
|
||||
|
||||
###########################################################
|
||||
|
||||
|
||||
if (keys %ServicesBans) {
|
||||
printf("\nBanned services with Fail2Ban: Bans:Unbans\n");
|
||||
foreach my $service (sort {$a cmp $b} keys %ServicesBans) {
|
||||
printf(" %-55s [%3d:%-3d]\n", "$service:",
|
||||
$ServicesBans{$service}{'(all)'}{'Ban'},
|
||||
$ServicesBans{$service}{'(all)'}{'Unban'});
|
||||
delete $ServicesBans{$service}{'(all)'};
|
||||
my $totalSort = TotalCountOrder(%{$ServicesBans{$service}}, \&SortIP);
|
||||
if ($Detail >= 5) {
|
||||
foreach my $ip (sort $totalSort keys %{$ServicesBans{$service}}) {
|
||||
my $name = LookupIP($ip);
|
||||
printf(" %-53s %3d:%-3d\n",
|
||||
$name,
|
||||
$ServicesBans{$service}{$ip}{'Ban'},
|
||||
$ServicesBans{$service}{$ip}{'Unban'});
|
||||
if (($Detail >= 10) and ($ServicesBans{$service}{$ip}{'Failures'}>0)) {
|
||||
print " Failed ";
|
||||
foreach my $fails (@{$ServicesBans{$service}{$ip}{'Failures'}}) {
|
||||
print " $fails";
|
||||
}
|
||||
print " times";
|
||||
printf("\n %d Duplicate Ban attempts", $ServicesBans{$service}{$ip}{'AlreadyInTheList'}) ;
|
||||
printf("\n %d ReBans due to rules reinitilizations", $ServicesBans{$service}{$ip}{'ReBan'}) ;
|
||||
print "\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if ($Detail>0) {
|
||||
if ($#IptablesErrors > 0) {
|
||||
printf("\n%d faulty iptables invocation(s)", $#IptablesErrors);
|
||||
if ($Detail > 5) {
|
||||
print ":\n";
|
||||
print @IptablesErrors ;
|
||||
}
|
||||
}
|
||||
if ($#ActionErrors > 0) {
|
||||
printf("\n%d error(s) returned from actions", $#ActionErrors);
|
||||
if ($Detail > 5) {
|
||||
print ":\n";
|
||||
print @ActionErrors ;
|
||||
}
|
||||
}
|
||||
if ($ReInitializations > 0) {
|
||||
printf("\n%d fail2ban rules reinitialization(s)", $ReInitializations);
|
||||
}
|
||||
if ($#OtherList >= 0) {
|
||||
print "\n**Unmatched Entries**\n";
|
||||
print @OtherList;
|
||||
}
|
||||
}
|
||||
|
||||
exit(0);
|
||||
|
||||
# vi: shiftwidth=3 tabstop=3 syntax=perl et
|
||||
# Local Variables:
|
||||
# mode: perl
|
||||
# perl-indent-level: 3
|
||||
# indent-tabs-mode: nil
|
||||
# End:
|
||||
@@ -48,16 +48,12 @@ ver. 0.9.1 (2014/xx/xx) - better, faster, stronger
|
||||
* cyrus-imap -- also catch also failed logins via secured (imaps/pop3s).
|
||||
Regression was introduced while strengthening failregex in 0.8.11 (bd175f)
|
||||
Debian bug #755173
|
||||
* postfix-sasl - added journalmatch. Thanks Luc Maisonobe
|
||||
* postfix* - match with a new daemon string (postfix/submission/smtpd).
|
||||
Closes gh-804 . Thanks Paul Traina
|
||||
* apache - added filter for AH01630 client denied by server configuration.
|
||||
* postfix-sasl -- added journalmatch. Thanks Luc Maisonobe
|
||||
|
||||
- New features:
|
||||
- New filters:
|
||||
- monit Thanks Jason H Martin
|
||||
- directadmin Thanks niorg
|
||||
- apache-shellshock Thanks Eugene Hopkinson (SlowRiot)
|
||||
- New actions:
|
||||
- symbiosis-blacklist-allports for Bytemark symbiosis firewall
|
||||
- fail2ban-client can fetch the running server version
|
||||
|
||||
@@ -34,7 +34,6 @@ David Nutter
|
||||
Derek Atkins
|
||||
Eric Gerbier
|
||||
Enrico Labedzki
|
||||
Eugene Hopkinson (SlowRiot)
|
||||
ftoppi
|
||||
François Boulogne
|
||||
Frédéric
|
||||
@@ -82,7 +81,6 @@ Mika (mkl)
|
||||
Nick Munger
|
||||
onorua
|
||||
Paul Marrapese
|
||||
Paul Traina
|
||||
Noel Butler
|
||||
Patrick Börjesson
|
||||
Pressy
|
||||
|
||||
Vendored
+5
@@ -1,5 +1,10 @@
|
||||
Vagrant.configure("2") do |config|
|
||||
|
||||
config.vm.define "builder" do |builder|
|
||||
builder.vm.box = "vm144"
|
||||
builder.vm.provision "shell", path: "provision.sh"
|
||||
end
|
||||
|
||||
config.vm.define "secure" do |secure|
|
||||
secure.vm.box = "ubuntu/trusty64"
|
||||
secure.vm.hostname = "secure.dev.fail2ban.org"
|
||||
|
||||
+44
-44
@@ -59,53 +59,53 @@ class Fail2banClient:
|
||||
self.__conf["pidfile"] = None
|
||||
|
||||
def dispVersion(self):
|
||||
print "Fail2Ban v" + version
|
||||
print
|
||||
print "Copyright (c) 2004-2008 Cyril Jaquier, 2008- Fail2Ban Contributors"
|
||||
print "Copyright of modifications held by their respective authors."
|
||||
print "Licensed under the GNU General Public License v2 (GPL)."
|
||||
print
|
||||
print "Written by Cyril Jaquier <cyril.jaquier@fail2ban.org>."
|
||||
print "Many contributions by Yaroslav O. Halchenko <debian@onerussian.com>."
|
||||
print("Fail2Ban v" + version)
|
||||
print()
|
||||
print("Copyright (c) 2004-2008 Cyril Jaquier, 2008- Fail2Ban Contributors")
|
||||
print("Copyright of modifications held by their respective authors.")
|
||||
print("Licensed under the GNU General Public License v2 (GPL).")
|
||||
print()
|
||||
print("Written by Cyril Jaquier <cyril.jaquier@fail2ban.org>.")
|
||||
print("Many contributions by Yaroslav O. Halchenko <debian@onerussian.com>.")
|
||||
|
||||
def dispUsage(self):
|
||||
""" Prints Fail2Ban command line options and exits
|
||||
"""
|
||||
print "Usage: "+self.__argv[0]+" [OPTIONS] <COMMAND>"
|
||||
print
|
||||
print "Fail2Ban v" + version + " reads log file that contains password failure report"
|
||||
print "and bans the corresponding IP addresses using firewall rules."
|
||||
print
|
||||
print "Options:"
|
||||
print " -c <DIR> configuration directory"
|
||||
print " -s <FILE> socket path"
|
||||
print " -p <FILE> pidfile path"
|
||||
print " -d dump configuration. For debugging"
|
||||
print " -i interactive mode"
|
||||
print " -v increase verbosity"
|
||||
print " -q decrease verbosity"
|
||||
print " -x force execution of the server (remove socket file)"
|
||||
print " -b start server in background (default)"
|
||||
print " -f start server in foreground (note that the client forks once itself)"
|
||||
print " -h, --help display this help message"
|
||||
print " -V, --version print the version"
|
||||
print
|
||||
print "Command:"
|
||||
print("Usage: "+self.__argv[0]+" [OPTIONS] <COMMAND>")
|
||||
print()
|
||||
print("Fail2Ban v" + version + " reads log file that contains password failure report")
|
||||
print("and bans the corresponding IP addresses using firewall rules.")
|
||||
print()
|
||||
print("Options:")
|
||||
print(" -c <DIR> configuration directory")
|
||||
print(" -s <FILE> socket path")
|
||||
print(" -p <FILE> pidfile path")
|
||||
print(" -d dump configuration. For debugging")
|
||||
print(" -i interactive mode")
|
||||
print(" -v increase verbosity")
|
||||
print(" -q decrease verbosity")
|
||||
print(" -x force execution of the server (remove socket file)")
|
||||
print(" -b start server in background (default)")
|
||||
print(" -f start server in foreground (note that the client forks once itself)")
|
||||
print(" -h, --help display this help message")
|
||||
print(" -V, --version print the version")
|
||||
print()
|
||||
print("Command:")
|
||||
|
||||
# Prints the protocol
|
||||
printFormatted()
|
||||
|
||||
print
|
||||
print "Report bugs to https://github.com/fail2ban/fail2ban/issues"
|
||||
print()
|
||||
print("Report bugs to https://github.com/fail2ban/fail2ban/issues")
|
||||
|
||||
def dispInteractive(self):
|
||||
print "Fail2Ban v" + version + " reads log file that contains password failure report"
|
||||
print "and bans the corresponding IP addresses using firewall rules."
|
||||
print
|
||||
print("Fail2Ban v" + version + " reads log file that contains password failure report")
|
||||
print("and bans the corresponding IP addresses using firewall rules.")
|
||||
print()
|
||||
|
||||
def __sigTERMhandler(self, signum, frame):
|
||||
# Print a new line because we probably come from wait
|
||||
print
|
||||
print()
|
||||
logSys.warning("Caught signal %d. Exiting" % signum)
|
||||
sys.exit(-1)
|
||||
|
||||
@@ -152,19 +152,19 @@ class Fail2banClient:
|
||||
client = CSocket(self.__conf["socket"])
|
||||
ret = client.send(c)
|
||||
if ret[0] == 0:
|
||||
logSys.debug("OK : " + `ret[1]`)
|
||||
logSys.debug("OK : " + repr(ret[1]))
|
||||
if showRet:
|
||||
print beautifier.beautify(ret[1])
|
||||
print(beautifier.beautify(ret[1]))
|
||||
else:
|
||||
logSys.error("NOK: " + `ret[1].args`)
|
||||
logSys.error("NOK: " + repr(ret[1].args))
|
||||
if showRet:
|
||||
print beautifier.beautifyError(ret[1])
|
||||
print(beautifier.beautifyError(ret[1]))
|
||||
streamRet = False
|
||||
except socket.error:
|
||||
if showRet:
|
||||
logSys.error("Unable to contact server. Is it running?")
|
||||
return False
|
||||
except Exception, e:
|
||||
except Exception as e:
|
||||
if showRet:
|
||||
logSys.error(e)
|
||||
return False
|
||||
@@ -383,7 +383,7 @@ class Fail2banClient:
|
||||
readline.parse_and_bind("tab: complete")
|
||||
self.dispInteractive()
|
||||
while True:
|
||||
cmd = raw_input(self.PROMPT)
|
||||
cmd = input(self.PROMPT)
|
||||
if cmd == "exit" or cmd == "quit":
|
||||
# Exit
|
||||
return True
|
||||
@@ -392,10 +392,10 @@ class Fail2banClient:
|
||||
elif not cmd == "":
|
||||
try:
|
||||
self.__processCommand(shlex.split(cmd))
|
||||
except Exception, e:
|
||||
except Exception as e:
|
||||
logSys.error(e)
|
||||
except (EOFError, KeyboardInterrupt):
|
||||
print
|
||||
print()
|
||||
return True
|
||||
# Single command mode
|
||||
else:
|
||||
@@ -413,7 +413,7 @@ class Fail2banClient:
|
||||
ret = self.__configurator.getOptions(jail)
|
||||
self.__configurator.convertToProtocol()
|
||||
self.__stream = self.__configurator.getConfigStream()
|
||||
except Exception, e:
|
||||
except Exception as e:
|
||||
logSys.error("Failed during configuration: %s" % e)
|
||||
ret = False
|
||||
return ret
|
||||
@@ -421,7 +421,7 @@ class Fail2banClient:
|
||||
#@staticmethod
|
||||
def dumpConfig(cmd):
|
||||
for c in cmd:
|
||||
print c
|
||||
print(c)
|
||||
return True
|
||||
dumpConfig = staticmethod(dumpConfig)
|
||||
|
||||
|
||||
+44
-46
@@ -29,10 +29,10 @@ __author__ = "Fail2Ban Developers"
|
||||
__copyright__ = "Copyright (c) 2004-2008 Cyril Jaquier, 2012-2014 Yaroslav Halchenko"
|
||||
__license__ = "GPL"
|
||||
|
||||
import getopt, sys, time, logging, os, locale, shlex, time, urllib
|
||||
import getopt, sys, time, logging, os, locale, shlex, time, urllib.request, urllib.parse, urllib.error
|
||||
from optparse import OptionParser, Option
|
||||
|
||||
from ConfigParser import NoOptionError, NoSectionError, MissingSectionHeaderError
|
||||
from configparser import NoOptionError, NoSectionError, MissingSectionHeaderError
|
||||
|
||||
try:
|
||||
from systemd import journal
|
||||
@@ -50,7 +50,7 @@ from fail2ban.helpers import FormatterWithTraceBack, getLogger
|
||||
logSys = getLogger("fail2ban")
|
||||
|
||||
def debuggexURL(sample, regex):
|
||||
q = urllib.urlencode({ 're': regex.replace('<HOST>', '(?&.ipv4)'),
|
||||
q = urllib.parse.urlencode({ 're': regex.replace('<HOST>', '(?&.ipv4)'),
|
||||
'str': sample,
|
||||
'flavor': 'python' })
|
||||
return 'http://www.debuggex.com/?' + q
|
||||
@@ -69,7 +69,7 @@ def pprint_list(l, header=None):
|
||||
s = "|- %s\n" % header
|
||||
else:
|
||||
s = ''
|
||||
print s + "| " + "\n| ".join(l) + '\n`-'
|
||||
print(s + "| " + "\n| ".join(l) + '\n`-')
|
||||
|
||||
def file_lines_gen(hdlr):
|
||||
for line in hdlr:
|
||||
@@ -244,14 +244,14 @@ class Fail2banRegex(object):
|
||||
self._filter.setDatePattern(pattern)
|
||||
self._datepattern_set = True
|
||||
if pattern is not None:
|
||||
print "Use datepattern : %s" % (
|
||||
self._filter.getDatePattern()[1], )
|
||||
print("Use datepattern : %s" % (
|
||||
self._filter.getDatePattern()[1], ))
|
||||
|
||||
def setMaxLines(self, v):
|
||||
if not self._maxlines_set:
|
||||
self._filter.setMaxLines(int(v))
|
||||
self._maxlines_set = True
|
||||
print "Use maxlines : %d" % self._filter.getMaxLines()
|
||||
print("Use maxlines : %d" % self._filter.getMaxLines())
|
||||
|
||||
def setJournalMatch(self, v):
|
||||
if self._journalmatch is None:
|
||||
@@ -261,7 +261,7 @@ class Fail2banRegex(object):
|
||||
assert(regextype in ('fail', 'ignore'))
|
||||
regex = regextype + 'regex'
|
||||
if os.path.isfile(value):
|
||||
print "Use %11s file : %s" % (regex, value)
|
||||
print("Use %11s file : %s" % (regex, value))
|
||||
reader = FilterReader(value, 'fail2ban-regex-jail', {})
|
||||
reader.setBaseDir(None)
|
||||
|
||||
@@ -270,9 +270,7 @@ class Fail2banRegex(object):
|
||||
readercommands = reader.convert()
|
||||
regex_values = [
|
||||
RegexStat(m[3])
|
||||
for m in filter(
|
||||
lambda x: x[0] == 'set' and x[2] == "add%sregex" % regextype,
|
||||
readercommands)]
|
||||
for m in [x for x in readercommands if x[0] == 'set' and x[2] == "add%sregex" % regextype]]
|
||||
# Read out and set possible value of maxlines
|
||||
for command in readercommands:
|
||||
if command[2] == "maxlines":
|
||||
@@ -280,8 +278,8 @@ class Fail2banRegex(object):
|
||||
try:
|
||||
self.setMaxLines(maxlines)
|
||||
except ValueError:
|
||||
print "ERROR: Invalid value for maxlines (%(maxlines)r) " \
|
||||
"read from %(value)s" % locals()
|
||||
print("ERROR: Invalid value for maxlines (%(maxlines)r) " \
|
||||
"read from %(value)s" % locals())
|
||||
return False
|
||||
elif command[2] == 'addjournalmatch':
|
||||
journalmatch = command[3]
|
||||
@@ -290,10 +288,10 @@ class Fail2banRegex(object):
|
||||
datepattern = command[3]
|
||||
self.setDatePattern(datepattern)
|
||||
else:
|
||||
print "ERROR: failed to read %s" % value
|
||||
print("ERROR: failed to read %s" % value)
|
||||
return False
|
||||
else:
|
||||
print "Use %11s line : %s" % (regex, shortstr(value))
|
||||
print("Use %11s line : %s" % (regex, shortstr(value)))
|
||||
regex_values = [RegexStat(value)]
|
||||
|
||||
setattr(self, "_" + regex, regex_values)
|
||||
@@ -310,8 +308,8 @@ class Fail2banRegex(object):
|
||||
if ret is not None:
|
||||
found = True
|
||||
regex = self._ignoreregex[ret].inc()
|
||||
except RegexException, e:
|
||||
print e
|
||||
except RegexException as e:
|
||||
print(e)
|
||||
return False
|
||||
return found
|
||||
|
||||
@@ -327,11 +325,11 @@ class Fail2banRegex(object):
|
||||
regex = self._failregex[match[0]]
|
||||
regex.inc()
|
||||
regex.appendIP(match)
|
||||
except RegexException, e:
|
||||
print e
|
||||
except RegexException as e:
|
||||
print(e)
|
||||
return False
|
||||
except IndexError:
|
||||
print "Sorry, but no <HOST> found in regex"
|
||||
print("Sorry, but no <HOST> found in regex")
|
||||
return False
|
||||
for bufLine in orgLineBuffer[int(fullBuffer):]:
|
||||
if bufLine not in self._filter._Filter__lineBuffer:
|
||||
@@ -405,21 +403,21 @@ class Fail2banRegex(object):
|
||||
ans = [[]]
|
||||
for arg in [l, regexlist]:
|
||||
ans = [ x + [y] for x in ans for y in arg ]
|
||||
b = map(lambda a: a[0] + ' | ' + a[1].getFailRegex() + ' | ' + debuggexURL(a[0], a[1].getFailRegex()), ans)
|
||||
b = [a[0] + ' | ' + a[1].getFailRegex() + ' | ' + debuggexURL(a[0], a[1].getFailRegex()) for a in ans]
|
||||
pprint_list([x.rstrip() for x in b], header)
|
||||
else:
|
||||
print "%s too many to print. Use --print-all-%s " \
|
||||
"to print all %d lines" % (header, ltype, lines)
|
||||
print("%s too many to print. Use --print-all-%s " \
|
||||
"to print all %d lines" % (header, ltype, lines))
|
||||
elif lines < self._maxlines or getattr(self, '_print_all_' + ltype):
|
||||
pprint_list([x.rstrip() for x in l], header)
|
||||
else:
|
||||
print "%s too many to print. Use --print-all-%s " \
|
||||
"to print all %d lines" % (header, ltype, lines)
|
||||
print("%s too many to print. Use --print-all-%s " \
|
||||
"to print all %d lines" % (header, ltype, lines))
|
||||
|
||||
def printStats(self):
|
||||
print
|
||||
print "Results"
|
||||
print "======="
|
||||
print()
|
||||
print("Results")
|
||||
print("=======")
|
||||
|
||||
def print_failregexes(title, failregexes):
|
||||
# Print title
|
||||
@@ -440,7 +438,7 @@ class Fail2banRegex(object):
|
||||
timeString,
|
||||
ip[-1] and " (multiple regex matched)" or ""))
|
||||
|
||||
print "\n%s: %d total" % (title, total)
|
||||
print("\n%s: %d total" % (title, total))
|
||||
pprint_list(out, " #) [# of hits] regular expression")
|
||||
return total
|
||||
|
||||
@@ -450,7 +448,7 @@ class Fail2banRegex(object):
|
||||
|
||||
|
||||
if self._filter.dateDetector is not None:
|
||||
print "\nDate template hits:"
|
||||
print("\nDate template hits:")
|
||||
out = []
|
||||
for template in self._filter.dateDetector.templates:
|
||||
if self._verbose or template.hits:
|
||||
@@ -458,10 +456,10 @@ class Fail2banRegex(object):
|
||||
template.hits, template.name))
|
||||
pprint_list(out, "[# of hits] date format")
|
||||
|
||||
print "\nLines: %s" % self._line_stats,
|
||||
print("\nLines: %s" % self._line_stats, end=' ')
|
||||
if self._time_elapsed is not None:
|
||||
print "[processed in %.2f sec]" % self._time_elapsed,
|
||||
print
|
||||
print("[processed in %.2f sec]" % self._time_elapsed, end=' ')
|
||||
print()
|
||||
|
||||
if self._print_all_matched:
|
||||
self.printLines('matched')
|
||||
@@ -486,10 +484,10 @@ if __name__ == "__main__":
|
||||
parser.print_help()
|
||||
sys.exit(-1)
|
||||
|
||||
print
|
||||
print "Running tests"
|
||||
print "============="
|
||||
print
|
||||
print()
|
||||
print("Running tests")
|
||||
print("=============")
|
||||
print()
|
||||
|
||||
fail2banRegex = Fail2banRegex(opts)
|
||||
|
||||
@@ -538,15 +536,15 @@ if __name__ == "__main__":
|
||||
if os.path.isfile(cmd_log):
|
||||
try:
|
||||
hdlr = open(cmd_log, 'rb')
|
||||
print "Use log file : %s" % cmd_log
|
||||
print "Use encoding : %s" % fail2banRegex.encoding
|
||||
print("Use log file : %s" % cmd_log)
|
||||
print("Use encoding : %s" % fail2banRegex.encoding)
|
||||
test_lines = file_lines_gen(hdlr)
|
||||
except IOError, e:
|
||||
print e
|
||||
except IOError as e:
|
||||
print(e)
|
||||
sys.exit(-1)
|
||||
elif cmd_log == "systemd-journal":
|
||||
if not journal:
|
||||
print "Error: systemd library not found. Exiting..."
|
||||
print("Error: systemd library not found. Exiting...")
|
||||
sys.exit(-1)
|
||||
myjournal = journal.Reader(converters={'__CURSOR': lambda x: x})
|
||||
journalmatch = fail2banRegex._journalmatch
|
||||
@@ -559,14 +557,14 @@ if __name__ == "__main__":
|
||||
else:
|
||||
myjournal.add_match(element)
|
||||
except ValueError:
|
||||
print "Error: Invalid journalmatch: %s" % shortstr(" ".join(journalmatch))
|
||||
print("Error: Invalid journalmatch: %s" % shortstr(" ".join(journalmatch)))
|
||||
sys.exit(-1)
|
||||
print "Use journal match : %s" % " ".join(journalmatch)
|
||||
print("Use journal match : %s" % " ".join(journalmatch))
|
||||
test_lines = journal_lines_gen(myjournal)
|
||||
else:
|
||||
print "Use single line : %s" % shortstr(cmd_log)
|
||||
print("Use single line : %s" % shortstr(cmd_log))
|
||||
test_lines = [ cmd_log ]
|
||||
print
|
||||
print()
|
||||
|
||||
fail2banRegex.process(test_lines)
|
||||
|
||||
|
||||
+28
-28
@@ -51,37 +51,37 @@ class Fail2banServer:
|
||||
self.__conf["pidfile"] = "/var/run/fail2ban/fail2ban.pid"
|
||||
|
||||
def dispVersion(self):
|
||||
print "Fail2Ban v" + version
|
||||
print
|
||||
print "Copyright (c) 2004-2008 Cyril Jaquier, 2008- Fail2Ban Contributors"
|
||||
print "Copyright of modifications held by their respective authors."
|
||||
print "Licensed under the GNU General Public License v2 (GPL)."
|
||||
print
|
||||
print "Written by Cyril Jaquier <cyril.jaquier@fail2ban.org>."
|
||||
print "Many contributions by Yaroslav O. Halchenko <debian@onerussian.com>."
|
||||
print("Fail2Ban v" + version)
|
||||
print()
|
||||
print("Copyright (c) 2004-2008 Cyril Jaquier, 2008- Fail2Ban Contributors")
|
||||
print("Copyright of modifications held by their respective authors.")
|
||||
print("Licensed under the GNU General Public License v2 (GPL).")
|
||||
print()
|
||||
print("Written by Cyril Jaquier <cyril.jaquier@fail2ban.org>.")
|
||||
print("Many contributions by Yaroslav O. Halchenko <debian@onerussian.com>.")
|
||||
|
||||
def dispUsage(self):
|
||||
""" Prints Fail2Ban command line options and exits
|
||||
"""
|
||||
print "Usage: "+self.__argv[0]+" [OPTIONS]"
|
||||
print
|
||||
print "Fail2Ban v" + version + " reads log file that contains password failure report"
|
||||
print "and bans the corresponding IP addresses using firewall rules."
|
||||
print
|
||||
print "Only use this command for debugging purpose. Start the server with"
|
||||
print "fail2ban-client instead. The default behaviour is to start the server"
|
||||
print "in background."
|
||||
print
|
||||
print "Options:"
|
||||
print " -b start in background"
|
||||
print " -f start in foreground"
|
||||
print " -s <FILE> socket path"
|
||||
print " -p <FILE> pidfile path"
|
||||
print " -x force execution of the server (remove socket file)"
|
||||
print " -h, --help display this help message"
|
||||
print " -V, --version print the version"
|
||||
print
|
||||
print "Report bugs to https://github.com/fail2ban/fail2ban/issues"
|
||||
print("Usage: "+self.__argv[0]+" [OPTIONS]")
|
||||
print()
|
||||
print("Fail2Ban v" + version + " reads log file that contains password failure report")
|
||||
print("and bans the corresponding IP addresses using firewall rules.")
|
||||
print()
|
||||
print("Only use this command for debugging purpose. Start the server with")
|
||||
print("fail2ban-client instead. The default behaviour is to start the server")
|
||||
print("in background.")
|
||||
print()
|
||||
print("Options:")
|
||||
print(" -b start in background")
|
||||
print(" -f start in foreground")
|
||||
print(" -s <FILE> socket path")
|
||||
print(" -p <FILE> pidfile path")
|
||||
print(" -x force execution of the server (remove socket file)")
|
||||
print(" -h, --help display this help message")
|
||||
print(" -V, --version print the version")
|
||||
print()
|
||||
print("Report bugs to https://github.com/fail2ban/fail2ban/issues")
|
||||
|
||||
def __getCmdLineOptions(self, optList):
|
||||
""" Gets the command line options
|
||||
@@ -125,7 +125,7 @@ class Fail2banServer:
|
||||
self.__conf["pidfile"],
|
||||
self.__conf["force"])
|
||||
return True
|
||||
except Exception, e:
|
||||
except Exception as e:
|
||||
logSys.exception(e)
|
||||
self.__server.quit()
|
||||
return False
|
||||
|
||||
@@ -114,8 +114,8 @@ logSys.addHandler(stdout)
|
||||
# Let know the version
|
||||
#
|
||||
if not opts.log_level or opts.log_level != 'critical': # pragma: no cover
|
||||
print("Fail2ban %s test suite. Python %s. Please wait..." \
|
||||
% (version, str(sys.version).replace('\n', '')))
|
||||
print(("Fail2ban %s test suite. Python %s. Please wait..." \
|
||||
% (version, str(sys.version).replace('\n', ''))))
|
||||
|
||||
tests = gatherTests(regexps, opts.no_network)
|
||||
#
|
||||
|
||||
@@ -10,7 +10,7 @@ before = apache-common.conf
|
||||
[Definition]
|
||||
|
||||
|
||||
failregex = ^%(_apache_error_client)s (AH(01797|01630): )?client denied by server configuration: (uri )?\S*(, referer: \S+)?\s*$
|
||||
failregex = ^%(_apache_error_client)s (AH01797: )?client denied by server configuration: (uri )?\S*(, referer: \S+)?\s*$
|
||||
^%(_apache_error_client)s (AH01617: )?user .*? authentication failure for "\S*": Password Mismatch(, referer: \S+)?$
|
||||
^%(_apache_error_client)s (AH01618: )?user .*? not found(: )?\S*(, referer: \S+)?\s*$
|
||||
^%(_apache_error_client)s (AH01614: )?client used wrong authentication scheme: \S*(, referer: \S+)?\s*$
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
# Fail2Ban filter to block web requests containing custom headers attempting to exploit the shellshock bug
|
||||
#
|
||||
#
|
||||
|
||||
[INCLUDES]
|
||||
|
||||
# overwrite with apache-common.local if _apache_error_client is incorrect.
|
||||
before = apache-common.conf
|
||||
|
||||
[Definition]
|
||||
|
||||
failregex = ^%(_apache_error_client)s (AH01215: )?/bin/(ba)?sh: warning: HTTP_.*?: ignoring function definition attempt(, referer: \S+)?\s*$
|
||||
^%(_apache_error_client)s (AH01215: )?/bin/(ba)?sh: error importing function definition for `HTTP_.*?'(, referer: \S+)?\s*$
|
||||
|
||||
ignoreregex =
|
||||
|
||||
|
||||
# DEV Notes:
|
||||
#
|
||||
# https://wiki.apache.org/httpd/ListOfErrors for apache error IDs
|
||||
#
|
||||
# example log lines:
|
||||
# [Thu Sep 25 09:27:18.813902 2014] [cgi:error] [pid 16860] [client 89.207.132.76:59635] AH01215: /bin/bash: warning: HTTP_TEST: ignoring function definition attempt
|
||||
# [Thu Sep 25 09:29:56.141832 2014] [cgi:error] [pid 16864] [client 162.247.73.206:41273] AH01215: /bin/bash: error importing function definition for `HTTP_TEST'
|
||||
#
|
||||
# Author: Eugene Hopkinson (riot@riot.so)
|
||||
@@ -7,12 +7,10 @@ before = common.conf
|
||||
|
||||
[Definition]
|
||||
|
||||
_daemon = postfix/(submission/)?smtp(d|s)
|
||||
_daemon = postfix/smtpd
|
||||
|
||||
failregex = ^%(__prefix_line)swarning: [-._\w]+\[<HOST>\]: SASL (?:LOGIN|PLAIN|(?:CRAM|DIGEST)-MD5) authentication failed(: [ A-Za-z0-9+/]*={0,2})?\s*$
|
||||
|
||||
ignoreregex =
|
||||
|
||||
[Init]
|
||||
|
||||
journalmatch = _SYSTEMD_UNIT=postfix.service
|
||||
|
||||
@@ -10,7 +10,7 @@ before = common.conf
|
||||
|
||||
[Definition]
|
||||
|
||||
_daemon = postfix/(submission/)?smtp(d|s)
|
||||
_daemon = postfix/smtpd
|
||||
|
||||
failregex = ^%(__prefix_line)sNOQUEUE: reject: RCPT from \S+\[<HOST>\]: 554 5\.7\.1 .*$
|
||||
^%(__prefix_line)sNOQUEUE: reject: RCPT from \S+\[<HOST>\]: 450 4\.7\.1 : Helo command rejected: Host not found; from=<> to=<> proto=ESMTP helo= *$
|
||||
|
||||
@@ -283,11 +283,6 @@ port = http,https
|
||||
logpath = %(apache_error_log)s
|
||||
maxretry = 2
|
||||
|
||||
[apache-shellshock]
|
||||
|
||||
port = http,https
|
||||
logpath = $(apache_error_log)s
|
||||
maxretry = 1
|
||||
|
||||
[nginx-http-auth]
|
||||
|
||||
|
||||
Vendored
+6
-8
@@ -1,14 +1,12 @@
|
||||
fail2ban (0.9.0+git252-g47441d1-1) experimental; urgency=medium
|
||||
fail2ban (0.9.X-python3) UNRELEASED; urgency=medium
|
||||
|
||||
[ Yaroslav Halchenko ]
|
||||
* New upstream snapshot from 0.9.0a2-814-g98dc084.
|
||||
[ Vid Luther ]
|
||||
* python3 for everything? .. I hope.
|
||||
|
||||
[ Daniel Schaal ]
|
||||
* debian/{control,rules}
|
||||
- switching to python3 as the interpreter for Fail2Ban so we could use
|
||||
python3-systemd which is N/A for Python2 any longer
|
||||
[ vagrant ]
|
||||
* warning?
|
||||
|
||||
-- Yaroslav Halchenko <debian@onerussian.com> Sun, 12 Oct 2014 16:45:36 -0400
|
||||
-- vagrant <vagrant@vagrant.vm> Sat, 13 Sep 2014 03:52:55 +0000
|
||||
|
||||
fail2ban (0.9.0+git48-gabcab00-1) experimental; urgency=medium
|
||||
|
||||
|
||||
Vendored
+2
-3
@@ -2,7 +2,7 @@ Source: fail2ban
|
||||
Section: net
|
||||
Priority: optional
|
||||
Maintainer: Yaroslav Halchenko <debian@onerussian.com>
|
||||
Build-Depends: debhelper (>= 9), python3, python3-pyinotify, dh-systemd
|
||||
Build-Depends: debhelper (>= 9), python3 (>= 3.0~), python3-pyinotify, dh-systemd
|
||||
Homepage: http://www.fail2ban.org
|
||||
Vcs-Git: git://github.com/fail2ban/fail2ban.git
|
||||
Vcs-Browser: http://github.com/fail2ban/fail2ban
|
||||
@@ -13,7 +13,7 @@ Package: fail2ban
|
||||
Architecture: all
|
||||
Depends: ${python3:Depends}, ${misc:Depends}, lsb-base (>=2.0-7)
|
||||
Recommends: iptables, whois, python3-pyinotify
|
||||
Suggests: mailx, system-log-daemon, python3-systemd
|
||||
Suggests: python-gamin, mailx, system-log-daemon, python3-systemd
|
||||
Description: ban hosts that cause multiple authentication errors
|
||||
Fail2ban monitors log files (e.g. /var/log/auth.log,
|
||||
/var/log/apache/access.log) and temporarily or persistently bans
|
||||
@@ -27,4 +27,3 @@ Description: ban hosts that cause multiple authentication errors
|
||||
easily extended for monitoring any other text file. All filters and
|
||||
actions are given in the config files, thus fail2ban can be adopted
|
||||
to be used with a variety of files and firewalls.
|
||||
|
||||
|
||||
+1556
File diff suppressed because it is too large
Load Diff
Vendored
+1
@@ -1 +1,2 @@
|
||||
deb_manpages_reportbug
|
||||
convert-to-python3.patch
|
||||
|
||||
Vendored
+2
-4
@@ -9,13 +9,10 @@
|
||||
# Uncomment this to turn on verbose mode.
|
||||
#export DH_VERBOSE=1
|
||||
|
||||
export PYBUILD_DISABLE_python2=1
|
||||
|
||||
%:
|
||||
dh $@ --with python3,systemd --buildsystem pybuild
|
||||
|
||||
DESTDIR=$(CURDIR)/debian/fail2ban
|
||||
PYVERSION=$(shell py3versions -dv)
|
||||
|
||||
override_dh_clean:
|
||||
rm -rf fail2ban.egg-info
|
||||
@@ -42,7 +39,8 @@ override_dh_install:
|
||||
|
||||
override_dh_auto_test:
|
||||
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
|
||||
cd build && FAIL2BAN_CONFIG_DIR="$(CURDIR)/config" PYTHONPATH="$(CURDIR)/.pybuild/pythonX.Y_$(PYVERSION)/build/" scripts-*/fail2ban-testcases --no-network
|
||||
cd build && PYTHONPATH=../.pybuild/pythonX.Y_3.4/build/ scripts-*/fail2ban-testcases --no-network
|
||||
|
||||
endif
|
||||
|
||||
override_dh_installexamples:
|
||||
|
||||
@@ -45,7 +45,7 @@ class Beautifier:
|
||||
return self.__inputCmd
|
||||
|
||||
def beautify(self, response):
|
||||
logSys.debug("Beautify " + `response` + " with " + `self.__inputCmd`)
|
||||
logSys.debug("Beautify " + repr(response) + " with " + repr(self.__inputCmd))
|
||||
inC = self.__inputCmd
|
||||
msg = response
|
||||
try:
|
||||
@@ -99,7 +99,7 @@ class Beautifier:
|
||||
elif response == 4:
|
||||
msg = msg + "DEBUG"
|
||||
else:
|
||||
msg = msg + `response`
|
||||
msg = msg + repr(response)
|
||||
elif inC[1] == "dbfile":
|
||||
if response is None:
|
||||
msg = "Database currently disabled"
|
||||
@@ -180,13 +180,13 @@ class Beautifier:
|
||||
msg += ", ".join(response)
|
||||
except Exception:
|
||||
logSys.warning("Beautifier error. Please report the error")
|
||||
logSys.error("Beautify " + `response` + " with " + `self.__inputCmd` +
|
||||
logSys.error("Beautify " + repr(response) + " with " + repr(self.__inputCmd) +
|
||||
" failed")
|
||||
msg = msg + `response`
|
||||
msg = msg + repr(response)
|
||||
return msg
|
||||
|
||||
def beautifyError(self, response):
|
||||
logSys.debug("Beautify (error) " + `response` + " with " + `self.__inputCmd`)
|
||||
logSys.debug("Beautify (error) " + repr(response) + " with " + repr(self.__inputCmd))
|
||||
msg = response
|
||||
if isinstance(response, UnknownJailException):
|
||||
msg = "Sorry but the jail '" + response.args[0] + "' does not exist"
|
||||
|
||||
@@ -58,7 +58,7 @@ if sys.version_info >= (3,2): # pragma: no cover
|
||||
parser, option, accum, rest, section, map, depth)
|
||||
|
||||
else: # pragma: no cover
|
||||
from ConfigParser import SafeConfigParser
|
||||
from configparser import SafeConfigParser
|
||||
|
||||
# Gets the instance of the logger.
|
||||
logSys = getLogger(__name__)
|
||||
@@ -122,7 +122,7 @@ after = 1.conf
|
||||
parser.read(resource, encoding='utf-8')
|
||||
else:
|
||||
parser.read(resource)
|
||||
except UnicodeDecodeError, e:
|
||||
except UnicodeDecodeError as e:
|
||||
logSys.error("Error decoding config file '%s': %s" % (resource, e))
|
||||
return []
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ __copyright__ = "Copyright (c) 2004 Cyril Jaquier"
|
||||
__license__ = "GPL"
|
||||
|
||||
import glob, os
|
||||
from ConfigParser import NoOptionError, NoSectionError
|
||||
from configparser import NoOptionError, NoSectionError
|
||||
|
||||
from .configparserinc import SafeConfigParserWithIncludes
|
||||
from ..helpers import getLogger
|
||||
@@ -67,7 +67,7 @@ class ConfigReader(SafeConfigParserWithIncludes):
|
||||
config_files += sorted(glob.glob('%s/*.local' % config_dir))
|
||||
|
||||
# choose only existing ones
|
||||
config_files = filter(os.path.exists, config_files)
|
||||
config_files = list(filter(os.path.exists, config_files))
|
||||
|
||||
if len(config_files):
|
||||
# at least one config exists and accessible
|
||||
@@ -111,7 +111,7 @@ class ConfigReader(SafeConfigParserWithIncludes):
|
||||
if not pOptions is None and option[1] in pOptions:
|
||||
continue
|
||||
values[option[1]] = v
|
||||
except NoSectionError, e:
|
||||
except NoSectionError as e:
|
||||
# No "Definition" section or wrong basedir
|
||||
logSys.error(e)
|
||||
values[option[1]] = option[2]
|
||||
@@ -127,7 +127,7 @@ class ConfigReader(SafeConfigParserWithIncludes):
|
||||
option[1], sec)
|
||||
except ValueError:
|
||||
logSys.warning("Wrong value for '" + option[1] + "' in '" + sec +
|
||||
"'. Using default one: '" + `option[2]` + "'")
|
||||
"'. Using default one: '" + repr(option[2]) + "'")
|
||||
values[option[1]] = option[2]
|
||||
return values
|
||||
|
||||
@@ -174,7 +174,7 @@ class DefinitionInitConfigReader(ConfigReader):
|
||||
|
||||
if self.has_section("Init"):
|
||||
for opt in self.options("Init"):
|
||||
if not self._initOpts.has_key(opt):
|
||||
if opt not in self._initOpts:
|
||||
self._initOpts[opt] = self.get("Init", opt)
|
||||
|
||||
def convert(self):
|
||||
|
||||
@@ -63,7 +63,7 @@ class CSocket:
|
||||
while msg.rfind(CSocket.END_STRING) == -1:
|
||||
chunk = sock.recv(6)
|
||||
if chunk == '':
|
||||
raise RuntimeError, "socket connection broken"
|
||||
raise RuntimeError("socket connection broken")
|
||||
msg = msg + chunk
|
||||
return loads(msg)
|
||||
receive = staticmethod(receive)
|
||||
|
||||
@@ -49,7 +49,7 @@ class FilterReader(DefinitionInitConfigReader):
|
||||
opts = CommandAction.substituteRecursiveTags(combinedopts)
|
||||
if not opts:
|
||||
raise ValueError('recursive tag definitions unable to be resolved')
|
||||
for opt, value in opts.iteritems():
|
||||
for opt, value in opts.items():
|
||||
if opt == "failregex":
|
||||
for regex in value.split('\n'):
|
||||
# Do not send a command if the rule is empty.
|
||||
|
||||
@@ -148,7 +148,7 @@ class JailReader(ConfigReader):
|
||||
self.__actions.append(action)
|
||||
else:
|
||||
raise AttributeError("Unable to read action")
|
||||
except Exception, e:
|
||||
except Exception as e:
|
||||
logSys.error("Error in action definition " + act)
|
||||
logSys.debug("Caught exception: %s" % (e,))
|
||||
return False
|
||||
|
||||
+13
-13
@@ -128,7 +128,7 @@ def printFormatted():
|
||||
firstHeading = False
|
||||
for m in protocol:
|
||||
if m[0] == '' and firstHeading:
|
||||
print
|
||||
print()
|
||||
firstHeading = True
|
||||
first = True
|
||||
if len(m[0]) >= MARGIN:
|
||||
@@ -139,7 +139,7 @@ def printFormatted():
|
||||
first = False
|
||||
else:
|
||||
line = ' ' * (INDENT + MARGIN) + n.strip()
|
||||
print line
|
||||
print(line)
|
||||
|
||||
##
|
||||
# Prints the protocol in a "mediawiki" format.
|
||||
@@ -149,19 +149,19 @@ def printWiki():
|
||||
for m in protocol:
|
||||
if m[0] == '':
|
||||
if firstHeading:
|
||||
print "|}"
|
||||
print("|}")
|
||||
__printWikiHeader(m[1], m[2])
|
||||
firstHeading = True
|
||||
else:
|
||||
print "|-"
|
||||
print "| <span style=\"white-space:nowrap;\"><tt>" + m[0] + "</tt></span> || || " + m[1]
|
||||
print "|}"
|
||||
print("|-")
|
||||
print("| <span style=\"white-space:nowrap;\"><tt>" + m[0] + "</tt></span> || || " + m[1])
|
||||
print("|}")
|
||||
|
||||
def __printWikiHeader(section, desc):
|
||||
print
|
||||
print "=== " + section + " ==="
|
||||
print
|
||||
print desc
|
||||
print
|
||||
print "{|"
|
||||
print "| '''Command''' || || '''Description'''"
|
||||
print()
|
||||
print("=== " + section + " ===")
|
||||
print()
|
||||
print(desc)
|
||||
print()
|
||||
print("{|")
|
||||
print("| '''Command''' || || '''Description'''")
|
||||
|
||||
@@ -27,6 +27,7 @@ from abc import ABCMeta
|
||||
from collections import MutableMapping
|
||||
|
||||
from ..helpers import getLogger
|
||||
import collections
|
||||
|
||||
# Gets the instance of the logger.
|
||||
logSys = getLogger(__name__)
|
||||
@@ -47,7 +48,7 @@ _RETCODE_HINTS = {
|
||||
|
||||
# Dictionary to lookup signal name from number
|
||||
signame = dict((num, name)
|
||||
for name, num in signal.__dict__.iteritems() if name.startswith("SIG"))
|
||||
for name, num in signal.__dict__.items() if name.startswith("SIG"))
|
||||
|
||||
class CallingMap(MutableMapping):
|
||||
"""A Mapping type which returns the result of callable values.
|
||||
@@ -74,7 +75,7 @@ class CallingMap(MutableMapping):
|
||||
|
||||
def __getitem__(self, key):
|
||||
value = self.data[key]
|
||||
if callable(value):
|
||||
if isinstance(value, collections.Callable):
|
||||
return value()
|
||||
else:
|
||||
return value
|
||||
@@ -94,7 +95,7 @@ class CallingMap(MutableMapping):
|
||||
def copy(self):
|
||||
return self.__class__(self.data.copy())
|
||||
|
||||
class ActionBase(object):
|
||||
class ActionBase(object, metaclass=ABCMeta):
|
||||
"""An abstract base class for actions in Fail2Ban.
|
||||
|
||||
Action Base is a base definition of what methods need to be in
|
||||
@@ -124,7 +125,6 @@ class ActionBase(object):
|
||||
Any additional arguments specified in `jail.conf` or passed
|
||||
via `fail2ban-client` will be passed as keyword arguments.
|
||||
"""
|
||||
__metaclass__ = ABCMeta
|
||||
|
||||
@classmethod
|
||||
def __subclasshook__(cls, C):
|
||||
@@ -135,7 +135,7 @@ class ActionBase(object):
|
||||
"unban",
|
||||
)
|
||||
for method in required:
|
||||
if not callable(getattr(C, method, None)):
|
||||
if not isinstance(getattr(C, method, None), collections.Callable):
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -242,7 +242,7 @@ class CommandAction(ActionBase):
|
||||
return dict(
|
||||
(key, getattr(self, key))
|
||||
for key in dir(self)
|
||||
if not key.startswith("_") and not callable(getattr(self, key)))
|
||||
if not key.startswith("_") and not isinstance(getattr(self, key), collections.Callable))
|
||||
|
||||
@property
|
||||
def actionstart(self):
|
||||
@@ -379,7 +379,7 @@ class CommandAction(ActionBase):
|
||||
within the values recursively replaced.
|
||||
"""
|
||||
t = re.compile(r'<([^ >]+)>')
|
||||
for tag in tags.iterkeys():
|
||||
for tag in tags.keys():
|
||||
if tag in cls._escapedTags:
|
||||
# Escaped so won't match
|
||||
continue
|
||||
@@ -398,7 +398,7 @@ class CommandAction(ActionBase):
|
||||
# Escaped so won't match
|
||||
continue
|
||||
else:
|
||||
if tags.has_key(found_tag):
|
||||
if found_tag in tags:
|
||||
value = value.replace('<%s>' % found_tag , tags[found_tag])
|
||||
#logSys.log(5, 'value now: %s' % value)
|
||||
done.append(found_tag)
|
||||
@@ -563,7 +563,7 @@ class CommandAction(ActionBase):
|
||||
os.kill(popen.pid, signal.SIGKILL) # Kill the process
|
||||
time.sleep(0.1)
|
||||
retcode = popen.poll()
|
||||
except OSError, e:
|
||||
except OSError as e:
|
||||
logSys.error("%s -- failed with %s" % (realCmd, e))
|
||||
finally:
|
||||
_cmd_lock.release()
|
||||
|
||||
@@ -213,7 +213,7 @@ class Actions(JailThread, Mapping):
|
||||
bool
|
||||
True when the thread exits nicely.
|
||||
"""
|
||||
for name, action in self._actions.iteritems():
|
||||
for name, action in self._actions.items():
|
||||
try:
|
||||
action.start()
|
||||
except Exception as e:
|
||||
@@ -231,7 +231,7 @@ class Actions(JailThread, Mapping):
|
||||
time.sleep(self.sleeptime)
|
||||
self.__flushBan()
|
||||
|
||||
actions = self._actions.items()
|
||||
actions = list(self._actions.items())
|
||||
actions.reverse()
|
||||
for name, action in actions:
|
||||
try:
|
||||
@@ -274,7 +274,7 @@ class Actions(JailThread, Mapping):
|
||||
jail.database.getBansMerged(ip=ip, jail=jail).getAttempt()
|
||||
if self.__banManager.addBanTicket(bTicket):
|
||||
logSys.notice("[%s] Ban %s" % (self._jail.name, aInfo["ip"]))
|
||||
for name, action in self._actions.iteritems():
|
||||
for name, action in self._actions.items():
|
||||
try:
|
||||
action.ban(aInfo.copy())
|
||||
except Exception as e:
|
||||
@@ -323,7 +323,7 @@ class Actions(JailThread, Mapping):
|
||||
aInfo["time"] = ticket.getTime()
|
||||
aInfo["matches"] = "".join(ticket.getMatches())
|
||||
logSys.notice("[%s] Unban %s" % (self._jail.name, aInfo["ip"]))
|
||||
for name, action in self._actions.iteritems():
|
||||
for name, action in self._actions.items():
|
||||
try:
|
||||
action.unban(aInfo.copy())
|
||||
except Exception as e:
|
||||
|
||||
@@ -134,7 +134,7 @@ class Fail2BanDb(object):
|
||||
|
||||
logSys.info(
|
||||
"Connected to fail2ban persistent database '%s'", filename)
|
||||
except sqlite3.OperationalError, e:
|
||||
except sqlite3.OperationalError as e:
|
||||
logSys.error(
|
||||
"Error connecting to fail2ban persistent database '%s': %s",
|
||||
filename, e.args[0])
|
||||
|
||||
@@ -168,7 +168,7 @@ class DatePatternRegex(DateTemplate):
|
||||
regex
|
||||
pattern
|
||||
"""
|
||||
_patternRE = r"%%(%%|[%s])" % "".join(timeRE.keys())
|
||||
_patternRE = r"%%(%%|[%s])" % "".join(list(timeRE.keys()))
|
||||
_patternName = {
|
||||
'a': "DAY", 'A': "DAYNAME", 'b': "MON", 'B': "MONTH", 'd': "Day",
|
||||
'H': "24hour", 'I': "12hour", 'j': "Yearday", 'm': "Month",
|
||||
@@ -232,7 +232,7 @@ class DatePatternRegex(DateTemplate):
|
||||
if dateMatch:
|
||||
groupdict = dict(
|
||||
(key, value)
|
||||
for key, value in dateMatch.groupdict().iteritems()
|
||||
for key, value in dateMatch.groupdict().items()
|
||||
if value is not None)
|
||||
return reGroupDictStrptime(groupdict), dateMatch
|
||||
|
||||
|
||||
@@ -91,7 +91,7 @@ class FailManager:
|
||||
ip = ticket.getIP()
|
||||
unixTime = ticket.getTime()
|
||||
matches = ticket.getMatches()
|
||||
if self.__failList.has_key(ip):
|
||||
if ip in self.__failList:
|
||||
fData = self.__failList[ip]
|
||||
if fData.getLastReset() < unixTime - self.__maxTime:
|
||||
fData.setLastReset(unixTime)
|
||||
@@ -112,7 +112,7 @@ class FailManager:
|
||||
# in case of having many active failures, it should be ran only
|
||||
# if debug level is "low" enough
|
||||
failures_summary = ', '.join(['%s:%d' % (k, v.getRetry())
|
||||
for k,v in self.__failList.iteritems()])
|
||||
for k,v in self.__failList.items()])
|
||||
logSys.debug("Total # of detected failures: %d. Current failures from %d IPs (IP:count): %s"
|
||||
% (self.__failTotal, len(self.__failList), failures_summary))
|
||||
finally:
|
||||
@@ -136,7 +136,7 @@ class FailManager:
|
||||
self.__lock.release()
|
||||
|
||||
def __delFailure(self, ip):
|
||||
if self.__failList.has_key(ip):
|
||||
if ip in self.__failList:
|
||||
del self.__failList[ip]
|
||||
|
||||
def toBan(self):
|
||||
|
||||
+11
-11
@@ -100,7 +100,7 @@ class Filter(JailThread):
|
||||
logSys.warning(
|
||||
"Mutliline regex set for jail '%s' "
|
||||
"but maxlines not greater than 1")
|
||||
except RegexException, e:
|
||||
except RegexException as e:
|
||||
logSys.error(e)
|
||||
raise e
|
||||
|
||||
@@ -134,7 +134,7 @@ class Filter(JailThread):
|
||||
try:
|
||||
regex = Regex(value)
|
||||
self.__ignoreRegex.append(regex)
|
||||
except RegexException, e:
|
||||
except RegexException as e:
|
||||
logSys.error(e)
|
||||
raise e
|
||||
|
||||
@@ -310,7 +310,7 @@ class Filter(JailThread):
|
||||
logSys.warning('Requested to manually ban an ignored IP %s. User knows best. Proceeding to ban it.' % ip)
|
||||
|
||||
unixTime = MyTime.time()
|
||||
for i in xrange(self.failManager.getMaxRetry()):
|
||||
for i in range(self.failManager.getMaxRetry()):
|
||||
self.failManager.addFailure(FailTicket(ip, unixTime))
|
||||
|
||||
# Perform the banning of the IP now.
|
||||
@@ -361,7 +361,7 @@ class Filter(JailThread):
|
||||
elif "." in s[1]: # 255.255.255.0 style mask
|
||||
s[1] = len(re.search(
|
||||
"(?<=b)1+", bin(DNSUtils.addr2bin(s[1]))).group())
|
||||
s[1] = long(s[1])
|
||||
s[1] = int(s[1])
|
||||
try:
|
||||
a = DNSUtils.cidr(s[0], s[1])
|
||||
b = DNSUtils.cidr(ip, s[1])
|
||||
@@ -525,7 +525,7 @@ class Filter(JailThread):
|
||||
failRegex.getMatchedLines()])
|
||||
if not checkAllRegex:
|
||||
break
|
||||
except RegexException, e: # pragma: no cover - unsure if reachable
|
||||
except RegexException as e: # pragma: no cover - unsure if reachable
|
||||
logSys.error(e)
|
||||
return failList
|
||||
|
||||
@@ -656,15 +656,15 @@ class FileFilter(Filter):
|
||||
try:
|
||||
has_content = container.open()
|
||||
# see http://python.org/dev/peps/pep-3151/
|
||||
except IOError, e:
|
||||
except IOError as e:
|
||||
logSys.error("Unable to open %s" % filename)
|
||||
logSys.exception(e)
|
||||
return False
|
||||
except OSError, e: # pragma: no cover - requires race condition to tigger this
|
||||
except OSError as e: # pragma: no cover - requires race condition to tigger this
|
||||
logSys.error("Error opening %s" % filename)
|
||||
logSys.exception(e)
|
||||
return False
|
||||
except OSError, e: # pragma: no cover - Requires implemention error in FileContainer to generate
|
||||
except OSError as e: # pragma: no cover - Requires implemention error in FileContainer to generate
|
||||
logSys.error("Internal errror in FileContainer open method - please report as a bug to https://github.com/fail2ban/fail2ban/issues")
|
||||
logSys.exception(e)
|
||||
return False
|
||||
@@ -845,11 +845,11 @@ class DNSUtils:
|
||||
"""
|
||||
try:
|
||||
return set(socket.gethostbyname_ex(dns)[2])
|
||||
except socket.error, e:
|
||||
except socket.error as e:
|
||||
logSys.warning("Unable to find a corresponding IP address for %s: %s"
|
||||
% (dns, e))
|
||||
return list()
|
||||
except socket.error, e:
|
||||
except socket.error as e:
|
||||
logSys.warning("Socket error raised trying to resolve hostname %s: %s"
|
||||
% (dns, e))
|
||||
return list()
|
||||
@@ -909,7 +909,7 @@ class DNSUtils:
|
||||
integer.
|
||||
"""
|
||||
# 32-bit IPv4 address mask
|
||||
MASK = 0xFFFFFFFFL
|
||||
MASK = 0xFFFFFFFF
|
||||
return ~(MASK >> n) & MASK & DNSUtils.addr2bin(i)
|
||||
cidr = staticmethod(cidr)
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ class FilterGamin(FileFilter):
|
||||
|
||||
|
||||
def callback(self, path, event):
|
||||
logSys.debug("Got event: " + `event` + " for " + path)
|
||||
logSys.debug("Got event: " + repr(event) + " for " + path)
|
||||
if event in (gamin.GAMCreated, gamin.GAMChanged, gamin.GAMExists):
|
||||
logSys.debug("File changed: " + path)
|
||||
self.__modified = True
|
||||
|
||||
@@ -136,7 +136,7 @@ class FilterPoll(FileFilter):
|
||||
logSys.debug("%s has been modified", filename)
|
||||
self.__prevStats[filename] = stats
|
||||
return True
|
||||
except OSError, e:
|
||||
except OSError as e:
|
||||
logSys.error("Unable to get stat on %s because of: %s"
|
||||
% (filename, e))
|
||||
self.__file404Cnt[filename] += 1
|
||||
|
||||
@@ -44,7 +44,7 @@ if not hasattr(pyinotify, '__version__') \
|
||||
try:
|
||||
manager = pyinotify.WatchManager()
|
||||
del manager
|
||||
except Exception, e:
|
||||
except Exception as e:
|
||||
raise ImportError("Pyinotify is probably not functional on this system: %s"
|
||||
% str(e))
|
||||
|
||||
|
||||
@@ -188,7 +188,7 @@ class FilterSystemd(JournalFilter): # pragma: systemd no cover
|
||||
logelements.append(logentry.get('MESSAGE', ''))
|
||||
|
||||
try:
|
||||
logline = u" ".join(logelements)
|
||||
logline = " ".join(logelements)
|
||||
except UnicodeDecodeError:
|
||||
# Python 2, so treat as string
|
||||
logline = " ".join([str(logline) for logline in logelements])
|
||||
|
||||
@@ -23,7 +23,7 @@ __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
|
||||
import queue, logging
|
||||
|
||||
from .actions import Actions
|
||||
from ..helpers import getLogger
|
||||
@@ -71,7 +71,7 @@ class Jail:
|
||||
"might not function correctly. Please shorten"
|
||||
% name)
|
||||
self.__name = name
|
||||
self.__queue = Queue.Queue()
|
||||
self.__queue = queue.Queue()
|
||||
self.__filter = None
|
||||
logSys.info("Creating new jail '%s'" % self.name)
|
||||
self._setBackend(backend)
|
||||
@@ -104,7 +104,7 @@ class Jail:
|
||||
logSys.info("Initiated %r backend" % b)
|
||||
self.__actions = Actions(self)
|
||||
return # we are done
|
||||
except ImportError, e:
|
||||
except ImportError as e:
|
||||
# Log debug if auto, but error if specific
|
||||
logSys.log(
|
||||
logging.DEBUG if backend == "auto" else logging.ERROR,
|
||||
@@ -117,25 +117,25 @@ class Jail:
|
||||
|
||||
|
||||
def _initPolling(self):
|
||||
from filterpoll import FilterPoll
|
||||
from .filterpoll import FilterPoll
|
||||
logSys.info("Jail '%s' uses poller" % self.name)
|
||||
self.__filter = FilterPoll(self)
|
||||
|
||||
def _initGamin(self):
|
||||
# Try to import gamin
|
||||
from filtergamin import FilterGamin
|
||||
from .filtergamin import FilterGamin
|
||||
logSys.info("Jail '%s' uses Gamin" % self.name)
|
||||
self.__filter = FilterGamin(self)
|
||||
|
||||
def _initPyinotify(self):
|
||||
# Try to import pyinotify
|
||||
from filterpyinotify import FilterPyinotify
|
||||
from .filterpyinotify import FilterPyinotify
|
||||
logSys.info("Jail '%s' uses pyinotify" % self.name)
|
||||
self.__filter = FilterPyinotify(self)
|
||||
|
||||
def _initSystemd(self): # pragma: systemd no cover
|
||||
# Try to import systemd
|
||||
from filtersystemd import FilterSystemd
|
||||
from .filtersystemd import FilterSystemd
|
||||
logSys.info("Jail '%s' uses systemd" % self.name)
|
||||
self.__filter = FilterSystemd(self)
|
||||
|
||||
@@ -199,7 +199,7 @@ class Jail:
|
||||
"""
|
||||
try:
|
||||
return self.__queue.get(False)
|
||||
except Queue.Empty:
|
||||
except queue.Empty:
|
||||
return False
|
||||
|
||||
def start(self):
|
||||
|
||||
@@ -74,7 +74,7 @@ class Server:
|
||||
sys.excepthook = excepthook
|
||||
|
||||
# First set the mask to only allow access to owner
|
||||
os.umask(0077)
|
||||
os.umask(0o077)
|
||||
if self.__daemon: # pragma: no cover
|
||||
logSys.info("Starting in daemon mode")
|
||||
ret = self.__createDaemon()
|
||||
@@ -90,20 +90,20 @@ class Server:
|
||||
pidFile = open(pidfile, 'w')
|
||||
pidFile.write("%s\n" % os.getpid())
|
||||
pidFile.close()
|
||||
except IOError, e:
|
||||
except IOError as 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:
|
||||
except AsyncServerException as e:
|
||||
logSys.error("Could not start server: %s", e)
|
||||
# Removes the PID file.
|
||||
try:
|
||||
logSys.debug("Remove PID file %s" % pidfile)
|
||||
os.remove(pidfile)
|
||||
except OSError, e:
|
||||
except OSError as e:
|
||||
logSys.error("Unable to remove PID file: %s" % e)
|
||||
logSys.info("Exiting Fail2ban")
|
||||
|
||||
@@ -159,7 +159,7 @@ class Server:
|
||||
logSys.info("Stopping all jails")
|
||||
try:
|
||||
self.__lock.acquire()
|
||||
for jail in self.__jails.keys():
|
||||
for jail in list(self.__jails.keys()):
|
||||
self.stopJail(jail)
|
||||
finally:
|
||||
self.__lock.release()
|
||||
@@ -486,7 +486,7 @@ class Server:
|
||||
# the child gets a new PID, making it impossible for its PID to equal its
|
||||
# PGID.
|
||||
pid = os.fork()
|
||||
except OSError, e:
|
||||
except OSError as e:
|
||||
return((e.errno, e.strerror)) # ERROR (return a tuple)
|
||||
|
||||
if pid == 0: # The first child.
|
||||
@@ -507,7 +507,7 @@ class Server:
|
||||
# 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:
|
||||
except OSError as e:
|
||||
return((e.errno, e.strerror)) # ERROR (return a tuple)
|
||||
|
||||
if (pid == 0): # The second child.
|
||||
|
||||
@@ -57,7 +57,7 @@ def reGroupDictStrptime(found_dict):
|
||||
# weekday and julian defaulted to -1 so as to signal need to calculate
|
||||
# values
|
||||
weekday = julian = -1
|
||||
for group_key in found_dict.keys():
|
||||
for group_key in list(found_dict.keys()):
|
||||
# Directives not explicitly handled below:
|
||||
# c, x, X
|
||||
# handled by making out of other directives
|
||||
|
||||
@@ -62,7 +62,7 @@ class Ticket:
|
||||
return False
|
||||
|
||||
def setIP(self, value):
|
||||
if isinstance(value, basestring):
|
||||
if isinstance(value, str):
|
||||
# guarantee using regular str instead of unicode for the IP
|
||||
value = str(value)
|
||||
self.__ip = value
|
||||
|
||||
@@ -29,6 +29,7 @@ import json
|
||||
|
||||
from ..helpers import getLogger
|
||||
from .. import version
|
||||
import collections
|
||||
|
||||
# Gets the instance of the logger.
|
||||
logSys = getLogger(__name__)
|
||||
@@ -51,11 +52,11 @@ class Transmitter:
|
||||
|
||||
def proceed(self, command):
|
||||
# Deserialize object
|
||||
logSys.debug("Command: " + `command`)
|
||||
logSys.debug("Command: " + repr(command))
|
||||
try:
|
||||
ret = self.__commandHandler(command)
|
||||
ack = 0, ret
|
||||
except Exception, e:
|
||||
except Exception as e:
|
||||
logSys.warning("Command %r has failed. Received %r"
|
||||
% (command, e))
|
||||
ack = 1, e
|
||||
@@ -248,7 +249,7 @@ class Transmitter:
|
||||
actionname = command[2]
|
||||
actionkey = command[3]
|
||||
action = self.__server.getAction(name, actionname)
|
||||
if callable(getattr(action, actionkey, None)):
|
||||
if isinstance(getattr(action, actionkey, None), collections.Callable):
|
||||
actionvalue = json.loads(command[4]) if len(command)>4 else {}
|
||||
return getattr(action, actionkey)(**actionvalue)
|
||||
else:
|
||||
@@ -306,7 +307,7 @@ class Transmitter:
|
||||
elif command[1] == "bantime":
|
||||
return self.__server.getBanTime(name)
|
||||
elif command[1] == "actions":
|
||||
return self.__server.getActions(name).keys()
|
||||
return list(self.__server.getActions(name).keys())
|
||||
elif command[1] == "action":
|
||||
actionname = command[2]
|
||||
actionvalue = command[3]
|
||||
@@ -318,13 +319,13 @@ class Transmitter:
|
||||
return [
|
||||
key for key in dir(action)
|
||||
if not key.startswith("_") and
|
||||
not callable(getattr(action, key))]
|
||||
not isinstance(getattr(action, key), collections.Callable)]
|
||||
elif command[1] == "actionmethods":
|
||||
actionname = command[2]
|
||||
action = self.__server.getAction(name, actionname)
|
||||
return [
|
||||
key for key in dir(action)
|
||||
if not key.startswith("_") and callable(getattr(action, key))]
|
||||
if not key.startswith("_") and isinstance(getattr(action, key), collections.Callable)]
|
||||
raise Exception("Invalid command (no get action or not yet implemented)")
|
||||
|
||||
def status(self, command):
|
||||
|
||||
@@ -22,7 +22,11 @@ import unittest
|
||||
import sys
|
||||
|
||||
from ..dummyjail import DummyJail
|
||||
from ..utils import CONFIG_DIR
|
||||
|
||||
if os.path.exists('config/fail2ban.conf'):
|
||||
CONFIG_DIR = "config"
|
||||
else:
|
||||
CONFIG_DIR='/etc/fail2ban'
|
||||
|
||||
if sys.version_info >= (2,7):
|
||||
class BadIPsActionTest(unittest.TestCase):
|
||||
|
||||
@@ -30,7 +30,10 @@ else:
|
||||
|
||||
from ..dummyjail import DummyJail
|
||||
|
||||
from ..utils import CONFIG_DIR
|
||||
if os.path.exists('config/fail2ban.conf'):
|
||||
CONFIG_DIR = "config"
|
||||
else:
|
||||
CONFIG_DIR='/etc/fail2ban'
|
||||
|
||||
class TestSMTPServer(smtpd.SMTPServer):
|
||||
|
||||
|
||||
@@ -32,10 +32,8 @@ from ..client.configurator import Configurator
|
||||
from .utils import LogCaptureTestCase
|
||||
|
||||
TEST_FILES_DIR = os.path.join(os.path.dirname(__file__), "files")
|
||||
|
||||
from .utils import CONFIG_DIR
|
||||
|
||||
STOCK = os.path.exists(os.path.join('config','fail2ban.conf'))
|
||||
CONFIG_DIR='config' if STOCK else '/etc/fail2ban'
|
||||
|
||||
IMPERFECT_CONFIG = os.path.join(os.path.dirname(__file__), 'config')
|
||||
|
||||
|
||||
@@ -92,7 +92,7 @@ class DatabaseTest(unittest.TestCase):
|
||||
self.db = Fail2BanDb(self.dbFilename)
|
||||
self.assertEqual(self.db.getJailNames(), set(['DummyJail #29162448 with 0 tickets']))
|
||||
self.assertEqual(self.db.getLogPaths(), set(['/tmp/Fail2BanDb_pUlZJh.log']))
|
||||
ticket = FailTicket("127.0.0.1", 1388009242.26, [u"abc\n"])
|
||||
ticket = FailTicket("127.0.0.1", 1388009242.26, ["abc\n"])
|
||||
self.assertEqual(self.db.getBans()[0], ticket)
|
||||
|
||||
self.assertEqual(self.db.updateDb(Fail2BanDb.__version__), Fail2BanDb.__version__)
|
||||
|
||||
@@ -139,7 +139,7 @@ class DateDetectorTest(unittest.TestCase):
|
||||
self.assertEqual(logMatch.group(), '2012/10/11 02:37:17')
|
||||
self.__datedetector.sortTemplate()
|
||||
# confuse it with year being at the end
|
||||
for i in xrange(10):
|
||||
for i in range(10):
|
||||
( logTime, logMatch ) = self.__datedetector.getTime('11/10/2012 02:37:17 [error] 18434#0')
|
||||
self.assertEqual(logTime, mu)
|
||||
self.assertEqual(logMatch.group(), '11/10/2012 02:37:17')
|
||||
|
||||
@@ -33,11 +33,11 @@ class AddFailure(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
"""Call before every test case."""
|
||||
self.__items = [[u'193.168.0.128', 1167605999.0],
|
||||
[u'193.168.0.128', 1167605999.0],
|
||||
[u'193.168.0.128', 1167605999.0],
|
||||
[u'193.168.0.128', 1167605999.0],
|
||||
[u'193.168.0.128', 1167605999.0],
|
||||
self.__items = [['193.168.0.128', 1167605999.0],
|
||||
['193.168.0.128', 1167605999.0],
|
||||
['193.168.0.128', 1167605999.0],
|
||||
['193.168.0.128', 1167605999.0],
|
||||
['193.168.0.128', 1167605999.0],
|
||||
['87.142.124.10', 1167605999.0],
|
||||
['87.142.124.10', 1167605999.0],
|
||||
['87.142.124.10', 1167605999.0],
|
||||
|
||||
@@ -1,21 +1,14 @@
|
||||
#!/bin/env python
|
||||
import requests
|
||||
import md5
|
||||
|
||||
try:
|
||||
import hashlib
|
||||
md5sum = hashlib.md5
|
||||
except ImportError: # pragma: no cover
|
||||
# hashlib was introduced in Python 2.5. For compatibility with those
|
||||
# elderly Pythons, import from md5
|
||||
import md5
|
||||
md5sum = md5.new
|
||||
|
||||
def auth(v):
|
||||
|
||||
ha1 = md5sum(username + ':' + realm + ':' + password).hexdigest()
|
||||
ha2 = md5sum("GET:" + url).hexdigest()
|
||||
ha1 = md5.new(username + ':' + realm + ':' + password).hexdigest()
|
||||
ha2 = md5.new("GET:" + url).hexdigest()
|
||||
|
||||
#response = md5sum(ha1 + ':' + v['nonce'][1:-1] + ':' + v['nc'] + ':' + v['cnonce'][1:-1]
|
||||
#response = md5.new(ha1 + ':' + v['nonce'][1:-1] + ':' + v['nc'] + ':' + v['cnonce'][1:-1]
|
||||
# + ':' + v['qop'][1:-1] + ':' + ha2).hexdigest()
|
||||
|
||||
nonce = v['nonce'][1:-1]
|
||||
@@ -24,7 +17,7 @@ def auth(v):
|
||||
#opaque = v.get('opaque') or ''
|
||||
qop = v['qop'][1:-1]
|
||||
algorithm = v['algorithm']
|
||||
response = md5sum(ha1 + ':' + nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2).hexdigest()
|
||||
response = md5.new(ha1 + ':' + nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2).hexdigest()
|
||||
|
||||
p = requests.Request('GET', host + url).prepare()
|
||||
#p.headers['Authentication-Info'] = response
|
||||
|
||||
@@ -19,9 +19,6 @@
|
||||
# failJSON: { "time": "2013-07-20T21:34:49", "match": true , "host": "127.0.0.1" }
|
||||
[Sat Jul 20 21:34:49.453232 2013] [access_compat:error] [pid 17512:tid 140123104306944] [client 127.0.0.1:51380] AH01797: client denied by server configuration: /var/www/html/noentry/cant_get_me.html
|
||||
|
||||
# failJSON: { "time": "2014-09-14T21:44:43", "match": true , "host": "192.3.9.178" }
|
||||
[Sun Sep 14 21:44:43.008606 2014] [authz_core:error] [pid 10691] [client 192.3.9.178:44271] AH01630: client denied by server configuration: /var/www/html/noentry/cant_get_me.html
|
||||
|
||||
# wget --http-user='' --http-password='' http://localhost/basic/file/cant_get_me.html -O /dev/null
|
||||
# failJSON: { "time": "2013-07-17T23:14:37", "match": true , "host": "127.0.0.1" }
|
||||
[Wed Jul 17 23:14:37 2013] [error] [client 127.0.0.1] user not found: /basic/anon/cant_get_me.html
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
# failJSON: { "time": "2014-09-25T09:27:18", "match": true , "host": "89.207.132.76" }
|
||||
[Thu Sep 25 09:27:18.813902 2014] [cgi:error] [pid 16860] [client 89.207.132.76:59635] AH01215: /bin/bash: warning: HTTP_TEST: ignoring function definition attempt
|
||||
# failJSON: { "time": "2014-09-25T09:29:56", "match": true , "host": "162.247.73.206" }
|
||||
[Thu Sep 25 09:29:56.141832 2014] [cgi:error] [pid 16864] [client 162.247.73.206:41273] AH01215: /bin/bash: error importing function definition for `HTTP_TEST'
|
||||
@@ -5,6 +5,3 @@ Dec 2 22:24:22 hel postfix/smtpd[7676]: warning: 114-44-142-233.dynamic.hinet.n
|
||||
# failJSON: { "time": "2005-03-10T13:33:30", "match": true , "host": "1.1.1.1" }
|
||||
Mar 10 13:33:30 gandalf postfix/smtpd[3937]: warning: HOSTNAME[1.1.1.1]: SASL LOGIN authentication failed: authentication failure
|
||||
|
||||
#3 Example from postfix post-debian changes to rename to add "submission" to syslog name
|
||||
# failJSON: { "time": "2004-09-06T00:44:56", "match": true , "host": "82.221.106.233" }
|
||||
Sep 6 00:44:56 trianon postfix/submission/smtpd[11538]: warning: unknown[82.221.106.233]: SASL LOGIN authentication failed: UGFzc3dvcmQ6
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
__copyright__ = "Copyright (c) 2004 Cyril Jaquier; 2012 Yaroslav Halchenko"
|
||||
__license__ = "GPL"
|
||||
|
||||
from __builtin__ import open as fopen
|
||||
from builtins import open as fopen
|
||||
import unittest
|
||||
import getpass
|
||||
import os
|
||||
@@ -133,7 +133,7 @@ def _copy_lines_between_files(in_, fout, n=None, skip=0, mode='a', terminal_line
|
||||
else:
|
||||
fin = in_
|
||||
# Skip
|
||||
for i in xrange(skip):
|
||||
for i in range(skip):
|
||||
fin.readline()
|
||||
# Read
|
||||
i = 0
|
||||
@@ -170,7 +170,7 @@ def _copy_lines_to_journal(in_, fields={},n=None, skip=0, terminal_line=""): # p
|
||||
"PRIORITY": "7",
|
||||
})
|
||||
# Skip
|
||||
for i in xrange(skip):
|
||||
for i in range(skip):
|
||||
fin.readline()
|
||||
# Read/Write
|
||||
i = 0
|
||||
@@ -806,7 +806,7 @@ class GetFailures(unittest.TestCase):
|
||||
|
||||
# so that they could be reused by other tests
|
||||
FAILURES_01 = ('193.168.0.128', 3, 1124013599.0,
|
||||
[u'Aug 14 11:59:59 [sshd] error: PAM: Authentication failure for kevin from 193.168.0.128']*3)
|
||||
['Aug 14 11:59:59 [sshd] error: PAM: Authentication failure for kevin from 193.168.0.128']*3)
|
||||
|
||||
def setUp(self):
|
||||
"""Call before every test case."""
|
||||
@@ -856,8 +856,8 @@ class GetFailures(unittest.TestCase):
|
||||
|
||||
def testGetFailures02(self):
|
||||
output = ('141.3.81.106', 4, 1124013539.0,
|
||||
[u'Aug 14 11:%d:59 i60p295 sshd[12365]: Failed publickey for roehl from ::ffff:141.3.81.106 port 51332 ssh2'
|
||||
% m for m in 53, 54, 57, 58])
|
||||
['Aug 14 11:%d:59 i60p295 sshd[12365]: Failed publickey for roehl from ::ffff:141.3.81.106 port 51332 ssh2'
|
||||
% m for m in (53, 54, 57, 58)])
|
||||
|
||||
self.filter.addLogPath(GetFailures.FILENAME_02)
|
||||
self.filter.addFailRegex("Failed .* from <HOST>")
|
||||
@@ -889,11 +889,11 @@ class GetFailures(unittest.TestCase):
|
||||
def testGetFailuresUseDNS(self):
|
||||
# We should still catch failures with usedns = no ;-)
|
||||
output_yes = ('93.184.216.119', 2, 1124013539.0,
|
||||
[u'Aug 14 11:54:59 i60p295 sshd[12365]: Failed publickey for roehl from example.com port 51332 ssh2',
|
||||
u'Aug 14 11:58:59 i60p295 sshd[12365]: Failed publickey for roehl from ::ffff:93.184.216.119 port 51332 ssh2'])
|
||||
['Aug 14 11:54:59 i60p295 sshd[12365]: Failed publickey for roehl from example.com port 51332 ssh2',
|
||||
'Aug 14 11:58:59 i60p295 sshd[12365]: Failed publickey for roehl from ::ffff:93.184.216.119 port 51332 ssh2'])
|
||||
|
||||
output_no = ('93.184.216.119', 1, 1124013539.0,
|
||||
[u'Aug 14 11:58:59 i60p295 sshd[12365]: Failed publickey for roehl from ::ffff:93.184.216.119 port 51332 ssh2'])
|
||||
['Aug 14 11:58:59 i60p295 sshd[12365]: Failed publickey for roehl from ::ffff:93.184.216.119 port 51332 ssh2'])
|
||||
|
||||
# Actually no exception would be raised -- it will be just set to 'no'
|
||||
#self.assertRaises(ValueError,
|
||||
|
||||
@@ -30,7 +30,7 @@ import shutil
|
||||
import fnmatch
|
||||
import datetime
|
||||
from glob import glob
|
||||
from StringIO import StringIO
|
||||
from io import StringIO
|
||||
|
||||
from ..helpers import formatExceptionInfo, mbasename, TraceBack, FormatterWithTraceBack, getLogger
|
||||
from ..server.datetemplate import DatePatternRegex
|
||||
@@ -138,7 +138,7 @@ class TestsUtilsTest(unittest.TestCase):
|
||||
else: func_raise()
|
||||
|
||||
try:
|
||||
print deep_function(3)
|
||||
print(deep_function(3))
|
||||
except ValueError:
|
||||
s = tb()
|
||||
|
||||
|
||||
@@ -28,13 +28,17 @@ if sys.version_info >= (2, 6):
|
||||
import json
|
||||
else:
|
||||
import simplejson as json
|
||||
next = lambda x: x.next()
|
||||
next = lambda x: x.__next__()
|
||||
|
||||
from ..server.filter import Filter
|
||||
from ..client.filterreader import FilterReader
|
||||
from .utils import setUpMyTime, tearDownMyTime, CONFIG_DIR
|
||||
from .utils import setUpMyTime, tearDownMyTime
|
||||
|
||||
TEST_FILES_DIR = os.path.join(os.path.dirname(__file__), "files")
|
||||
if os.path.exists('config/fail2ban.conf'):
|
||||
CONFIG_DIR = "config"
|
||||
else:
|
||||
CONFIG_DIR='/etc/fail2ban'
|
||||
|
||||
class FilterSamplesRegex(unittest.TestCase):
|
||||
|
||||
@@ -90,7 +94,7 @@ def testSampleRegexsFactory(name):
|
||||
if jsonREMatch:
|
||||
try:
|
||||
faildata = json.loads(jsonREMatch.group(1))
|
||||
except ValueError, e:
|
||||
except ValueError as e:
|
||||
raise ValueError("%s: %s:%i" %
|
||||
(e, logFile.filename(), logFile.filelineno()))
|
||||
line = next(logFile)
|
||||
@@ -112,7 +116,7 @@ def testSampleRegexsFactory(name):
|
||||
"Line matched when shouldn't have: %s:%i %r" %
|
||||
(logFile.filename(), logFile.filelineno(), line))
|
||||
self.assertEqual(len(ret), 1, "Multiple regexs matched %r - %s:%i" %
|
||||
(map(lambda x: x[0], ret),logFile.filename(), logFile.filelineno()))
|
||||
([x[0] for x in ret],logFile.filename(), logFile.filelineno()))
|
||||
|
||||
# Verify timestamp and host as expected
|
||||
failregex, host, fail2banTime, lines = ret[0]
|
||||
@@ -145,7 +149,7 @@ def testSampleRegexsFactory(name):
|
||||
|
||||
return testFilter
|
||||
|
||||
for filter_ in filter(lambda x: not x.endswith('common.conf'), os.listdir(os.path.join(CONFIG_DIR, "filter.d"))):
|
||||
for filter_ in [x for x in os.listdir(os.path.join(CONFIG_DIR, "filter.d")) if not x.endswith('common.conf')]:
|
||||
filterName = filter_.rpartition(".")[0]
|
||||
if not filterName.startswith('.'):
|
||||
setattr(
|
||||
|
||||
@@ -685,7 +685,7 @@ class TransmitterLogging(TransmitterBase):
|
||||
|
||||
def testLogTarget(self):
|
||||
logTargets = []
|
||||
for _ in xrange(3):
|
||||
for _ in range(3):
|
||||
tmpFile = tempfile.mkstemp("fail2ban", "transmitter")
|
||||
logTargets.append(tmpFile[1])
|
||||
os.close(tmpFile[0])
|
||||
@@ -738,26 +738,26 @@ class TransmitterLogging(TransmitterBase):
|
||||
self.assertEqual(self.transm.proceed(["flushlogs"]), (0, "rolled over"))
|
||||
l.warning("After flushlogs")
|
||||
with open(fn2,'r') as f:
|
||||
line1 = f.next()
|
||||
line1 = next(f)
|
||||
if line1.find('Changed logging target to') >= 0:
|
||||
line1 = f.next()
|
||||
line1 = next(f)
|
||||
self.assertTrue(line1.endswith("Before file moved\n"))
|
||||
line2 = f.next()
|
||||
line2 = next(f)
|
||||
self.assertTrue(line2.endswith("After file moved\n"))
|
||||
try:
|
||||
n = f.next()
|
||||
n = next(f)
|
||||
if n.find("Command: ['flushlogs']") >=0:
|
||||
self.assertRaises(StopIteration, f.next)
|
||||
self.assertRaises(StopIteration, f.__next__)
|
||||
else:
|
||||
self.fail("Exception StopIteration or Command: ['flushlogs'] expected. Got: %s" % n)
|
||||
except StopIteration:
|
||||
pass # on higher debugging levels this is expected
|
||||
with open(fn,'r') as f:
|
||||
line1 = f.next()
|
||||
line1 = next(f)
|
||||
if line1.find('rollover performed on') >= 0:
|
||||
line1 = f.next()
|
||||
line1 = next(f)
|
||||
self.assertTrue(line1.endswith("After flushlogs\n"))
|
||||
self.assertRaises(StopIteration, f.next)
|
||||
self.assertRaises(StopIteration, f.__next__)
|
||||
f.close()
|
||||
finally:
|
||||
os.remove(fn2)
|
||||
|
||||
+5
-14
@@ -27,22 +27,13 @@ import os
|
||||
import re
|
||||
import time
|
||||
import unittest
|
||||
from StringIO import StringIO
|
||||
from io import StringIO
|
||||
|
||||
from ..server.mytime import MyTime
|
||||
from ..helpers import getLogger
|
||||
|
||||
logSys = getLogger(__name__)
|
||||
|
||||
CONFIG_DIR = os.environ.get('FAIL2BAN_CONFIG_DIR', None)
|
||||
|
||||
if not CONFIG_DIR:
|
||||
# Use heuristic to figure out where configuration files are
|
||||
if os.path.exists(os.path.join('config','fail2ban.conf')):
|
||||
CONFIG_DIR = 'config'
|
||||
else:
|
||||
CONFIG_DIR = '/etc/fail2ban'
|
||||
|
||||
def mtimesleep():
|
||||
# no sleep now should be necessary since polling tracks now not only
|
||||
# mtime but also ino and size
|
||||
@@ -165,13 +156,13 @@ def gatherTests(regexps=None, no_network=False):
|
||||
try:
|
||||
from ..server.filtergamin import FilterGamin
|
||||
filters.append(FilterGamin)
|
||||
except Exception, e: # pragma: no cover
|
||||
except Exception as e: # pragma: no cover
|
||||
logSys.warning("Skipping gamin backend testing. Got exception '%s'" % e)
|
||||
|
||||
try:
|
||||
from ..server.filterpyinotify import FilterPyinotify
|
||||
filters.append(FilterPyinotify)
|
||||
except Exception, e: # pragma: no cover
|
||||
except Exception as e: # pragma: no cover
|
||||
logSys.warning("I: Skipping pyinotify backend testing. Got exception '%s'" % e)
|
||||
|
||||
for Filter_ in filters:
|
||||
@@ -180,7 +171,7 @@ def gatherTests(regexps=None, no_network=False):
|
||||
try: # pragma: systemd no cover
|
||||
from ..server.filtersystemd import FilterSystemd
|
||||
tests.addTest(unittest.makeSuite(filtertestcase.get_monitor_failures_journal_testcase(FilterSystemd)))
|
||||
except Exception, e: # pragma: no cover
|
||||
except Exception as e: # pragma: no cover
|
||||
logSys.warning("I: Skipping systemd backend testing. Got exception '%s'" % e)
|
||||
|
||||
|
||||
@@ -217,4 +208,4 @@ class LogCaptureTestCase(unittest.TestCase):
|
||||
return s in self._log.getvalue()
|
||||
|
||||
def printLog(self):
|
||||
print(self._log.getvalue())
|
||||
print((self._log.getvalue()))
|
||||
|
||||
@@ -1,209 +0,0 @@
|
||||
#!/usr/bin/perl
|
||||
##########################################################################
|
||||
# $Id: fail2ban 150 2013-06-18 22:19:38Z mtremaine $
|
||||
##########################################################################
|
||||
# $Log: fail2ban,v $
|
||||
#
|
||||
# Revision 1.6 2014/08/11 16:07:46 yoh
|
||||
# Patches from Yaroslav Halchenko to match adjusted in 0.9.x lines.
|
||||
# Also reports now total number of hits (matches) along with Ban:Unban
|
||||
# and relaxed regular expressions for matching any log level
|
||||
#
|
||||
# Revision 1.5 2008/08/18 16:07:46 mike
|
||||
# Patches from Paul Gear <paul at libertysys.com> -mgt
|
||||
#
|
||||
# Revision 1.4 2008/06/30 23:07:51 kirk
|
||||
# fixed copyright holders for files where I know who they should be
|
||||
#
|
||||
# Revision 1.3 2008/03/24 23:31:26 kirk
|
||||
# added copyright/license notice to each script
|
||||
#
|
||||
# Revision 1.2 2006/12/15 04:53:59 bjorn
|
||||
# Additional filtering, by Willi Mann.
|
||||
#
|
||||
# Revision 1.1 2006/05/30 19:04:26 bjorn
|
||||
# Added fail2ban service, written by Yaroslav Halchenko.
|
||||
#
|
||||
# Written by Yaroslav Halchenko <debian@onerussian.com> for fail2ban
|
||||
#
|
||||
##########################################################################
|
||||
|
||||
########################################################
|
||||
## Copyright (c) 2008 Yaroslav Halchenko
|
||||
## Covered under the included MIT/X-Consortium License:
|
||||
## http://www.opensource.org/licenses/mit-license.php
|
||||
## All modifications and contributions by other persons to
|
||||
## this script are assumed to have been donated to the
|
||||
## Logwatch project and thus assume the above copyright
|
||||
## and licensing terms. If you want to make contributions
|
||||
## under your own copyright or a different license this
|
||||
## must be explicitly stated in the contribution an the
|
||||
## Logwatch project reserves the right to not accept such
|
||||
## contributions. If you have made significant
|
||||
## contributions to this script and want to claim
|
||||
## copyright please contact logwatch-devel@lists.sourceforge.net.
|
||||
#########################################################
|
||||
|
||||
use strict;
|
||||
use Logwatch ':all';
|
||||
|
||||
my $Debug = $ENV{'LOGWATCH_DEBUG'} || 0;
|
||||
my $Detail = $ENV{'LOGWATCH_DETAIL_LEVEL'} || 0;
|
||||
my $IgnoreHost = $ENV{'sshd_ignore_host'} || "";
|
||||
my $DebugCounter = 0;
|
||||
my $ReInitializations = 0;
|
||||
my @ActionsErrors = ();
|
||||
my @CommandsErrors = ();
|
||||
my $NotValidIP = 0; # reported invalid IPs number
|
||||
my @OtherList = ();
|
||||
|
||||
my %ServicesBans = ();
|
||||
|
||||
if ( $Debug >= 5 ) {
|
||||
print STDERR "\n\nDEBUG: Inside Fail2Ban Filter \n\n";
|
||||
$DebugCounter = 1;
|
||||
}
|
||||
|
||||
while (defined(my $ThisLine = <STDIN>)) {
|
||||
if ( $Debug >= 5 ) {
|
||||
print STDERR "DEBUG($DebugCounter): $ThisLine";
|
||||
$DebugCounter++;
|
||||
}
|
||||
chomp($ThisLine);
|
||||
if ( ($ThisLine =~ /..,... DEBUG: /) or
|
||||
($ThisLine =~ /..,... \S*\s*: DEBUG /) or # syntax of 0.7.? fail2ban
|
||||
($ThisLine =~ /..,... \S+: (Fail2Ban v.* is running|Exiting|Enabled sections:)/) or
|
||||
($ThisLine =~ /\S+\s+rollover performed on/) or
|
||||
($ThisLine =~ /\S+\s+Connected to .* persistent database/) or
|
||||
($ThisLine =~ /\S+\s+Jail '.*' uses .*/) or
|
||||
($ThisLine =~ /\S+\s+Initiated '.*' backend/) or
|
||||
($ThisLine =~ /\S+\s+Jail .* is not a JournalFilter instance/) or
|
||||
($ThisLine =~ /\S+\s+Log rotation detected for/) or
|
||||
($ThisLine =~ /\S+\s+Jail.+(?:stopped|started|uses poller)/) or
|
||||
($ThisLine =~ /\S+\s+Changed logging target to/) or
|
||||
($ThisLine =~ /\S+\s+Creating new jail/) or
|
||||
($ThisLine =~ /..,... \S+\s*: INFO\s+(Set |Socket|Exiting|Gamin|Created|Added|Using)/) or # syntax of 0.7.? fail2ban
|
||||
($ThisLine =~ /..,... \S+: Verbose level is /) or
|
||||
($ThisLine =~ /..,... \S+: Restoring firewall rules/)
|
||||
)
|
||||
{
|
||||
if ( $Debug >= 6 ) {
|
||||
print STDERR "DEBUG($DebugCounter): line ignored\n";
|
||||
}
|
||||
} elsif ( my ($LogLevel,$Service,$Action,$Host) = ($ThisLine =~ m/(WARNING|NOTICE):?\s+\[?(.*?)[]:]?\s(Ban|Unban)[^\.]* (\S+)/)) {
|
||||
if ( $Debug >= 6 ) {
|
||||
print STDERR "DEBUG($DebugCounter): Found $Action for $Service from $Host\n";
|
||||
}
|
||||
$ServicesBans{$Service}{$Host}{$Action}++;
|
||||
$ServicesBans{$Service}{"(all)"}{$Action}++;
|
||||
} elsif ( my ($LogLevel,$Service,$Host) = ($ThisLine =~ m/(INFO|WARNING|NOTICE):?\s+\[?(.*?)[]:]?\sFound[^\.]* (\S+)/)) {
|
||||
if ( $Debug >= 6 ) {
|
||||
print STDERR "DEBUG($DebugCounter): Found hit for $Service from $Host\n";
|
||||
}
|
||||
$ServicesBans{$Service}{$Host}{"Hit"}++;
|
||||
$ServicesBans{$Service}{"(all)"}{"Hit"}++;
|
||||
} elsif ( my ($Service,$Host,$NumFailures) = ($ThisLine =~ m/\S+:\s+(\S+): (.+) has (\d+) login failure\(s\). Banned./)) {
|
||||
if ($Debug >= 4) {
|
||||
print STDERR "DEBUG: Found host $Host trying to access $Service - failed $NumFailures times\n";
|
||||
}
|
||||
push @{$ServicesBans{$Service}{$Host}{'Failures'}}, $NumFailures;
|
||||
} elsif ( my ($Service,$Host) = ($ThisLine =~ m/ \S+:\s(.*):\s(\S+)\salready in ban list/)) {
|
||||
$ServicesBans{$Service}{$Host}{'AlreadyInTheList'}++;
|
||||
} elsif ( my ($Service,$Host) = ($ThisLine =~ m/\S+:?\s+\[?([^[]*?)[]:]?\s+(\S+)\salready banned/)) {
|
||||
if ( $Debug >= 6 ) {
|
||||
print STDERR "DEBUG($DebugCounter): Found hit for already banned $Host against $Service\n";
|
||||
}
|
||||
$ServicesBans{$Service}{$Host}{'AlreadyInTheList'}++;
|
||||
} elsif ( my ($Service,$Host) = ($ThisLine =~ m/ \S+:\s(.*):\sReBan (\S+)/)) {
|
||||
$ServicesBans{$Service}{$Host}{'ReBan'}++;
|
||||
} elsif ($ThisLine =~ / ERROR:?\s*(Execution of command )?\'?iptables/) {
|
||||
push @ActionsErrors, "$ThisLine\n";
|
||||
} elsif ($ThisLine =~ / ERROR\s*Failed to execute.*action/) {
|
||||
push @ActionsErrors, "$ThisLine\n";
|
||||
} elsif ($ThisLine =~ / WARNING Command \[.*\] has failed. Received/) {
|
||||
push @CommandsErrors, "$ThisLine\n";
|
||||
} elsif ($ThisLine =~ /ERROR.*returned \d+$/) {
|
||||
push @ActionsErrors, "$ThisLine\n";
|
||||
} elsif (($ThisLine =~ /..,... WARNING: \#\S+ reinitialization of firewalls/) or
|
||||
($ThisLine =~ / ERROR\s*Invariant check failed. Trying to restore a sane environment/)) {
|
||||
$ReInitializations++;
|
||||
} elsif ($ThisLine =~ /..,... WARNING: is not a valid IP address/) {
|
||||
# just ignore - this will be fixed within fail2ban and is harmless warning
|
||||
}
|
||||
else
|
||||
{
|
||||
# Report any unmatched entries...
|
||||
push @OtherList, "$ThisLine\n";
|
||||
}
|
||||
}
|
||||
|
||||
###########################################################
|
||||
|
||||
|
||||
if (keys %ServicesBans) {
|
||||
printf("\nBanned services with Fail2Ban: Bans:Unbans:Hits\n");
|
||||
foreach my $service (sort {$a cmp $b} keys %ServicesBans) {
|
||||
printf(" %-55s [%3d:%d:%-3d]\n", "$service:",
|
||||
$ServicesBans{$service}{'(all)'}{'Ban'},
|
||||
$ServicesBans{$service}{'(all)'}{'Unban'},
|
||||
$ServicesBans{$service}{'(all)'}{'Hit'});
|
||||
delete $ServicesBans{$service}{'(all)'};
|
||||
my $totalSort = TotalCountOrder(%{$ServicesBans{$service}}, \&SortIP);
|
||||
if ($Detail >= 5) {
|
||||
foreach my $ip (sort $totalSort keys %{$ServicesBans{$service}}) {
|
||||
my $name = LookupIP($ip);
|
||||
printf(" %-53s %3d:%d:%-3d\n",
|
||||
$name,
|
||||
$ServicesBans{$service}{$ip}{'Ban'},
|
||||
$ServicesBans{$service}{$ip}{'Unban'},
|
||||
$ServicesBans{$service}{$ip}{'Hit'});
|
||||
if (($Detail >= 10) and ($ServicesBans{$service}{$ip}{'Failures'}>0)) {
|
||||
print " Failed ";
|
||||
foreach my $fails (@{$ServicesBans{$service}{$ip}{'Failures'}}) {
|
||||
print " $fails";
|
||||
}
|
||||
print " times\n";
|
||||
}
|
||||
if ($ServicesBans{$service}{$ip}{'AlreadyInTheList'}>0) {
|
||||
printf(" %d Duplicate Ban attempt(s)\n", $ServicesBans{$service}{$ip}{'AlreadyInTheList'}) ;
|
||||
}
|
||||
if ($ServicesBans{$service}{$ip}{'ReBan'}>0) {
|
||||
printf(" %d ReBan(s) due to rules reinitilizations\n", $ServicesBans{$service}{$ip}{'ReBan'}) ;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($Detail>0) {
|
||||
if ($#ActionsErrors >= 0) {
|
||||
printf("\n%d faulty action invocation(s)", $#ActionsErrors+1);
|
||||
if ($Detail > 5) {
|
||||
print ":\n";
|
||||
print @ActionsErrors ;
|
||||
}
|
||||
}
|
||||
if ($#CommandsErrors >= 0) {
|
||||
printf("\n%d faulty command invocation(s) from client(s)", $#CommandsErrors+1);
|
||||
if ($Detail > 5) {
|
||||
print ":\n";
|
||||
print @CommandsErrors ;
|
||||
}
|
||||
}
|
||||
if ($ReInitializations > 0) {
|
||||
printf("\n%d fail2ban rules reinitialization(s)", $ReInitializations);
|
||||
}
|
||||
if ($#OtherList >= 0) {
|
||||
print "\n**Unmatched Entries**\n";
|
||||
print @OtherList;
|
||||
}
|
||||
}
|
||||
|
||||
exit(0);
|
||||
|
||||
# vi: shiftwidth=3 tabstop=3 syntax=perl et
|
||||
# Local Variables:
|
||||
# mode: perl
|
||||
# perl-indent-level: 3
|
||||
# indent-tabs-mode: nil
|
||||
# End:
|
||||
@@ -1,2 +0,0 @@
|
||||
2014-08-04 03:06:26,161 fail2ban.actions[4822]: WARNING [apache-badbots] Ban 37.152.91.34
|
||||
2014-08-05 03:06:26,448 fail2ban.actions[4822]: WARNING [apache-badbots] Unban 37.152.91.34
|
||||
@@ -1,52 +0,0 @@
|
||||
2014-08-08 14:59:35,013 fail2ban.server.server[31122]: INFO Exiting Fail2ban
|
||||
2014-08-08 14:59:36,041 fail2ban.server.server[21667]: INFO Changed logging target to /var/log/fail2ban.log for Fail2ban v0.9.0
|
||||
2014-08-08 14:59:36,043 fail2ban.server.database[21667]: INFO Connected to fail2ban persistent database '/var/lib/fail2ban/fail2ban.sqlite3'
|
||||
2014-08-08 14:59:36,072 fail2ban.server.jail[21667]: INFO Creating new jail 'exim'
|
||||
2014-08-08 14:59:36,137 fail2ban.server.jail[21667]: INFO Jail 'exim' uses pyinotify
|
||||
2014-08-08 14:59:36,172 fail2ban.server.filter[21667]: INFO Set jail log file encoding to UTF-8
|
||||
2014-08-08 14:59:36,172 fail2ban.server.jail[21667]: INFO Initiated 'pyinotify' backend
|
||||
2014-08-08 14:59:36,233 fail2ban.server.filter[21667]: INFO Added logfile = /var/log/exim4/mainlog
|
||||
2014-08-08 14:59:36,249 fail2ban.server.filter[21667]: INFO Set maxRetry = 5
|
||||
2014-08-08 14:59:36,251 fail2ban.server.filter[21667]: INFO Set jail log file encoding to UTF-8
|
||||
2014-08-08 14:59:36,252 fail2ban.server.actions[21667]: INFO Set banTime = 600
|
||||
2014-08-08 14:59:36,254 fail2ban.server.filter[21667]: INFO Set findtime = 600
|
||||
2014-08-08 14:59:36,284 fail2ban.server.jail[21667]: INFO Creating new jail 'sshd'
|
||||
2014-08-08 14:59:36,284 fail2ban.server.jail[21667]: INFO Jail 'sshd' uses pyinotify
|
||||
2014-08-08 14:59:36,286 fail2ban.server.filter[21667]: INFO Set jail log file encoding to UTF-8
|
||||
2014-08-08 14:59:36,286 fail2ban.server.jail[21667]: INFO Initiated 'pyinotify' backend
|
||||
2014-08-08 14:59:36,499 fail2ban.server.filter[21667]: INFO Added logfile = /var/log/auth.log
|
||||
2014-08-08 14:59:36,510 fail2ban.server.filter[21667]: INFO Set maxRetry = 5
|
||||
2014-08-08 14:59:36,512 fail2ban.server.filter[21667]: INFO Set jail log file encoding to UTF-8
|
||||
2014-08-08 14:59:36,513 fail2ban.server.actions[21667]: INFO Set banTime = 600
|
||||
2014-08-08 14:59:36,514 fail2ban.server.filter[21667]: INFO Set findtime = 600
|
||||
2014-08-08 14:59:36,515 fail2ban.server.filter[21667]: INFO Set maxlines = 10
|
||||
2014-08-08 14:59:36,788 fail2ban.server.server[21667]: INFO Jail sshd is not a JournalFilter instance
|
||||
2014-08-08 14:59:36,798 fail2ban.server.jail[21667]: INFO Jail 'exim' started
|
||||
2014-08-08 14:59:36,802 fail2ban.server.jail[21667]: INFO Jail 'sshd' started
|
||||
2014-08-08 15:01:30,120 fail2ban.server.transmitter[21667]: WARNING Command ['status', 'ssh'] has failed. Received UnknownJailException('ssh',)
|
||||
2014-08-08 15:09:36,978 fail2ban.server.actions[21667]: NOTICE [sshd] Unban 116.10.191.199
|
||||
2014-08-08 15:09:37,187 fail2ban.server.action[21667]: ERROR rm -f /etc/symbiosis/firewall/blacklist.d/116.10.191.199.auto
|
||||
iptables -D INPUT -s 116.10.191.199 -j DROP -- stdout: ''
|
||||
2014-08-08 15:09:37,188 fail2ban.server.action[21667]: ERROR rm -f /etc/symbiosis/firewall/blacklist.d/116.10.191.199.auto
|
||||
iptables -D INPUT -s 116.10.191.199 -j DROP -- stderr: 'iptables: Bad rule (does a matching rule exist in that chain?).\n'
|
||||
2014-08-08 15:09:37,188 fail2ban.server.action[21667]: ERROR rm -f /etc/symbiosis/firewall/blacklist.d/116.10.191.199.auto
|
||||
iptables -D INPUT -s 116.10.191.199 -j DROP -- returned 1
|
||||
2014-08-08 15:09:37,188 fail2ban.server.actions[21667]: ERROR Failed to execute unban jail 'sshd' action 'symbiosis-blacklist': Error unbanning 116.10.191.199
|
||||
2014-08-10 02:27:27,235 fail2ban.server.server[21667]: INFO rollover performed on /var/log/fail2ban.log
|
||||
2014-08-10 02:27:28,109 fail2ban.server.filter[21667]: INFO Log rotation detected for /var/log/exim4/mainlog
|
||||
2014-08-10 02:28:01,747 fail2ban.server.filter[21667]: INFO Log rotation detected for /var/log/auth.log
|
||||
2014-08-10 02:33:29,500 fail2ban.server.filter[21667]: INFO [sshd] Found 86.101.234.57
|
||||
2014-08-10 02:46:06,846 fail2ban.server.filter[21667]: INFO [sshd] Found 220.130.163.247
|
||||
2014-08-10 03:10:43,794 fail2ban.server.filter[21667]: INFO [sshd] Found 220.130.163.247
|
||||
2014-08-10 06:49:27,446 fail2ban.server.actions[21667]: NOTICE [sshd] Ban 116.10.191.181
|
||||
2014-08-10 06:59:28,375 fail2ban.server.actions[21667]: NOTICE [sshd] Unban 116.10.191.181
|
||||
2014-08-10 20:06:41,576 fail2ban.server.actions[21667]: NOTICE [sshd] Unban 50.30.34.7
|
||||
2014-08-13 17:55:50,401 fail2ban.server.actions[17436]: NOTICE [sshd] 144.0.0.25 already banned
|
||||
2014-08-10 20:06:41,785 fail2ban.server.action[21667]: ERROR rm -f /etc/symbiosis/firewall/blacklist.d/50.30.34.7.auto
|
||||
iptables -D INPUT -s 50.30.34.7 -j DROP -- stdout: ''
|
||||
2014-08-10 20:06:41,785 fail2ban.server.action[21667]: ERROR rm -f /etc/symbiosis/firewall/blacklist.d/50.30.34.7.auto
|
||||
iptables -D INPUT -s 50.30.34.7 -j DROP -- stderr: 'iptables: Bad rule (does a matching rule exist in that chain?).\n'
|
||||
2014-08-10 20:06:41,786 fail2ban.server.action[21667]: ERROR rm -f /etc/symbiosis/firewall/blacklist.d/50.30.34.7.auto
|
||||
iptables -D INPUT -s 50.30.34.7 -j DROP -- returned 1
|
||||
2014-08-10 20:06:41,786 fail2ban.server.actions[21667]: ERROR Failed to execute unban jail 'sshd' action 'symbiosis-blacklist': Error unbanning 50.30.34.7
|
||||
2014-08-11 02:27:35,433 fail2ban.server.filter[21667]: INFO Log rotation detected for /var/log/exim4/mainlog
|
||||
@@ -378,7 +378,7 @@ the 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 https://github.com/fail2ban/fail2ban/issues
|
||||
Report bugs via Debian bug tracking system \fIhttp://www.debian.org/Bugs/\fR .
|
||||
.SH COPYRIGHT
|
||||
Copyright \(co 2004\-2008 Cyril Jaquier, 2008\- Fail2Ban Contributors
|
||||
.br
|
||||
|
||||
@@ -38,7 +38,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 https://github.com/fail2ban/fail2ban/issues
|
||||
Report bugs via Debian bug tracking system \fIhttp://www.debian.org/Bugs/\fR .
|
||||
.SH COPYRIGHT
|
||||
Copyright \(co 2004\-2008 Cyril Jaquier, 2008\- Fail2Ban Contributors
|
||||
.br
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/bash
|
||||
|
||||
sudo apt-get -y update
|
||||
sudo apt-get -y install curl python-systemd dh-systemd python-pip python-inotifyx git build-essential autotools-dev libssl-dev devscripts debhelper git libpcre3-dev libssl-dev
|
||||
Reference in New Issue
Block a user