Compare commits

..
36 Commits
Author SHA1 Message Date
Cyril Jaquier 351614258d - Updated for 0.6.0
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@215 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-11-20 16:53:13 +00:00
Cyril Jaquier c6e1763d37 - Updated
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@214 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-11-01 08:32:04 +00:00
Cyril Jaquier 4559dbf09f - Added an option to report local time (including timezone) or GMT in mail notification. Thanks to Yaroslav Halchenko
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@213 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-11-01 08:31:27 +00:00
Cyril Jaquier e12db53bf7 - Added "fwcheck" option to verify consistency of the firewall
- Added section in email
- Added "-f" command line option
- Reordered code a bit
Many thanks to Yaroslav Halchenko


git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@211 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-10-26 21:57:03 +00:00
Cyril Jaquier 6151d11720 - Added a cleanup of firewall rules on emergency shutdown when unknown exception is catched. Thanks to Yaroslav Halchenko
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@210 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-10-26 21:53:43 +00:00
Cyril Jaquier 61aa9d917d - Updated for 0.5.5
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@209 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-10-26 21:52:43 +00:00
Cyril Jaquier 0366e98291 - Updated
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@208 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-10-26 21:52:22 +00:00
Cyril Jaquier 1d09db666d - Added "ExternalError" exception
- Raise "ExternalError" exception in "executeCmd()" if "system()" fails


git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@207 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-10-26 21:51:52 +00:00
Cyril Jaquier 5556c78350 - Handle "AttributeError" exception in remove()
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@206 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-10-26 21:50:18 +00:00
Cyril Jaquier 2c1a0785c5 - Better exception handling in isModified()
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@205 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-10-26 21:49:05 +00:00
Cyril Jaquier 2701d7500b - Added firewall check command. Thanks to Yaroslav Halchenko
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@204 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-10-26 21:47:46 +00:00
Cyril Jaquier 31abe6f37c - Added "fwcheck", "reinittime" and "maxreinits"
- Added "<section>" in email


git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@203 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-10-26 21:45:37 +00:00
Cyril Jaquier 1c3f233475 - Updated for 0.5.4
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@201 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-09-13 20:43:00 +00:00
Cyril Jaquier c07015129b - Formatting
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@200 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-09-13 20:42:33 +00:00
Cyril Jaquier 3ca5a75094 - Updated
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@199 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-09-12 14:44:07 +00:00
Cyril Jaquier cfa8d0a7fe - Updated to CVS version
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@198 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-09-12 14:43:51 +00:00
Cyril Jaquier 0d4302c912 - Fixed bug #1286222
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@197 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-09-12 14:42:08 +00:00
Cyril Jaquier 11d887c603 - Formatting
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@196 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-09-12 14:41:40 +00:00
Yaroslav Halchenko eb11caa621 Propagated patches introduced by Debian maintainer
* Fixed handling of SYSLOG logging target. Now it can log
    to any SYSLOG target and facility as directed by the
    config
  * Format of SYSLOG entries fixed to look closer to standard
  * Fixed errata in config/gentoo-confd
  * Introduced findtime configuration variable to control the
    lifetime of caught "failed" log entries


git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@195 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-09-11 15:42:32 +00:00
Cyril Jaquier 10c0307ad5 - Updated
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@193 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-09-08 18:21:04 +00:00
Cyril Jaquier d0c70e1535 - Updated for 0.5.3
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@191 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-09-08 18:20:51 +00:00
Cyril Jaquier 830ac2001e - Added more debug output if an error occurs when sending mail. Thanks to Stephen Gildea
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@190 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-09-08 18:05:59 +00:00
Cyril Jaquier c1a86f9e18 - Updated
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@189 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-09-05 21:12:32 +00:00
Cyril Jaquier c573432e74 - Fixed a bug when overriding "maxfailures" or "bantime". Thanks to Yaroslav Halchenko
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@188 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-09-05 21:12:08 +00:00
Cyril Jaquier 54f4a7d240 - Hopefully fixed bug #1256075
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@187 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-09-05 21:06:15 +00:00
Cyril Jaquier cdc7b4b048 - Renamed "maxretry" to "maxfailures" and changed default value to 5. Thanks to Stephen Gildea
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@186 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-09-05 21:05:00 +00:00
Cyril Jaquier 631f2ac352 - Updated
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@185 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-08-17 19:34:00 +00:00
Cyril Jaquier c5c90b182a - Fixed bug #1262345
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@184 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-08-17 19:26:49 +00:00
Cyril Jaquier daf35a3535 - Added a warning message if IP address is not valid in ignoreip
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@183 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-08-17 19:26:14 +00:00
Cyril Jaquier 8a1241533f - Removed warning when using "-V" or "-h" with no config file. Thanks to Yaroslav Halchenko
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@182 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-08-07 13:12:15 +00:00
Cyril Jaquier ed46bcdaf2 - Removed "It needs log4py" from description
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@181 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-08-07 13:10:39 +00:00
Cyril Jaquier 38f2c24be1 - Updated
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@180 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-08-07 13:10:00 +00:00
Cyril Jaquier dd27cafee3 - Added better handling of exception
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@179 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-08-07 13:08:18 +00:00
Cyril Jaquier b3a90d7492 - Changed mask to 16
- Removed "-i eth0". Match all interfaces


git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@178 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-08-07 13:06:56 +00:00
Cyril Jaquier d2f3d1c263 - Fixed a bug with "-k"
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@177 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-08-06 18:44:06 +00:00
Cyril Jaquier 9548edaff0 - Do not exit on exception. Continue and wait for an unhandled exception
git-svn-id: https://fail2ban.svn.sourceforge.net/svnroot/fail2ban/branches/FAIL2BAN-0_5@176 a942ae1a-1317-0410-a47c-b1dcaea8d605
2005-08-06 18:43:11 +00:00
17 changed files with 565 additions and 201 deletions
+58 -1
View File
@@ -4,9 +4,66 @@
|_| \__,_|_|_/___|_.__/\__,_|_||_|
=============================================================
Fail2Ban (version 0.5.2) 2005/08/06
Fail2Ban (version 0.6.0) 2005/11/20
=============================================================
ver. 0.6.0 (2005/11/20) - stable
----------
- Propagated patches introduced by Debian maintainer
(Yaroslav Halchenko):
* Added an option to report local time (including timezone)
or GMT in mail notification.
ver. 0.5.5 (2005/10/26) - beta
----------
- Propagated patches introduced by Debian maintainer
(Yaroslav Halchenko):
* Introduced fwcheck option to verify consistency of the
chains. Implemented automatic restart of fail2ban main
function in case check of fwban or fwunban command failed
(closes: #329163, #331695). (Introduced patch was further
adjusted by upstream author).
* Added -f command line parameter for [findtime].
* Added a cleanup of firewall rules on emergency shutdown
when unknown exception is catched.
* Fail2ban should not crash now if a wrong file name is
specified in config.
* reordered code a bit so that log targets are setup right
after background and then only loglevel (verbose, debug)
is processed, so the warning could be seen in the logs
* Added a keyword <section> in parsing of the subject and
the body of an email sent out by fail2ban (closes:
#330311)
ver. 0.5.4 (2005/09/13) - beta
----------
- Fixed bug #1286222.
- Propagated patches introduced by Debian maintainer
(Yaroslav Halchenko):
* Fixed handling of SYSLOG logging target. Now it can log
to any SYSLOG target and facility as directed by the
config
* Format of SYSLOG entries fixed to look closer to standard
* Fixed errata in config/gentoo-confd
* Introduced findtime configuration variable to control the
lifetime of caught "failed" log entries
ver. 0.5.3 (2005/09/08) - beta
----------
- Fixed a bug when overriding "maxfailures" or "bantime".
Thanks to Yaroslav Halchenko
- Added more debug output if an error occurs when sending
mail. Thanks to Stephen Gildea
- Renamed "maxretry" to "maxfailures" and changed default
value to 5. Thanks to Stephen Gildea
- Hopefully fixed bug #1256075
- Fixed bug #1262345
- Fixed exception handling in PIDLock
- Removed warning when using "-V" or "-h" with no config
file. Thanks to Yaroslav Halchenko
- Removed "-i eth0" from config file. Thanks to Yaroslav
Halchenko
ver. 0.5.2 (2005/08/06) - beta
----------
- Better PID lock file handling. Should close #1239562
+12 -9
View File
@@ -4,7 +4,7 @@
|_| \__,_|_|_/___|_.__/\__,_|_||_|
=============================================================
Fail2Ban (version 0.5.2) 2005/08/06
Fail2Ban (version 0.6.0) 2005/11/20
=============================================================
Fail2Ban scans log files like /var/log/pwdfail and bans IP
@@ -54,19 +54,20 @@ firewalls.
Installation:
-------------
Require: python-2.3 (http://www.python.org)
Require: python-2.4 (http://www.python.org)
To install, just do:
> tar xvfj fail2ban-0.5.2.tar.bz2
> cd fail2ban-0.5.2
> tar xvfj fail2ban-0.6.0.tar.bz2
> cd fail2ban-0.6.0
> python setup.py install
This will install Fail2Ban into /usr/lib/fail2ban. The fail2ban
executable is placed into /usr/bin.
Gentoo: an ebuild is available on the website.
Debian: a package is available on the website.
Gentoo: ebuilds are available on the website.
Debian: Fail2Ban is in Debian unstable.
RedHat: packages are available on the website.
Fail2Ban should now be correctly installed. Just type:
@@ -101,8 +102,9 @@ options:
-h display this help message
-i <IP(s)> IP(s) to ignore
-k kill a currently running instance
-r <VALUE> allow a max of VALUE password failure
-t <TIME> ban IP for TIME seconds
-r <VALUE> allow a max of VALUE password failure [maxfailures]
-t <TIME> ban IP for TIME seconds [bantime]
-f <TIME> lifetime in seconds of failed entry [findtime]
-v verbose. Use twice for greater effect
-V print software version
@@ -121,7 +123,8 @@ Thanks:
-------
Kévin Drapel, Marvin Rouge, Sireyessire, Robert Edeker,
Tom Pike, Iain Lea, Andrey G. Grozin, Yaroslav Halchenko
Tom Pike, Iain Lea, Andrey G. Grozin, Yaroslav Halchenko,
Jonathan Kamens, Stephen Gildea
License:
--------
+12 -1
View File
@@ -4,9 +4,20 @@
|_| \__,_|_|_/___|_.__/\__,_|_||_|
=============================================================
ToDo
ToDo $Revision$
=============================================================
See Feature Request Tracking System at SourceForge.net
- improve installation process (better prefix support)
- install Fail2ban into /usr/share
- better configuration files
- add a check to see if the time of the log messages is
correctly detected (valid regexp)
- split configuration files in /etc/fail2ban/services.d
Example: /etc/fail2ban/services.d/apache
- template for common services in /etc/fail2ban/scripts.d
Example: /etc/fail2ban/scripts.d/apache
- remove debug mode (root check)
- better return values in function
- use more email.Utils in mail.py
+47 -35
View File
@@ -1,13 +1,14 @@
#! /bin/sh
#
# skeleton example file to build /etc/init.d/ scripts.
# This file should be used to construct scripts for /etc/init.d.
# Fail2Ban init.d file - to be launched on boot
#
# Written by Miquel van Smoorenburg <miquels@cistron.nl>.
# Modified for Debian
# by Ian Murdock <imurdock@gnu.ai.mit.edu>.
# Modified for Debian
# by Ian Murdock <imurdock@gnu.ai.mit.edu>.
# Adjusted for Fail2Ban
# by Yaroslav Halchenko <debian@onerussian.com>.
#
# Version: @(#)skeleton 1.9 26-Feb-2001 miquels@cistron.nl
# Version: $Id$
#
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
@@ -26,36 +27,47 @@ DAEMON_OPTS=$FAIL2BAN_OPTS
set -e
case "$1" in
start)
echo -n "Starting $DESC: "
[ -f $PIDFILE ] && [ ! -d /proc/`cat $PIDFILE` ] && rm -f $PIDFILE
start-stop-daemon --start --quiet --pidfile /var/run/$NAME.pid \
-b --exec $DAEMON -- $DAEMON_OPTS
echo "$NAME."
;;
stop)
echo -n "Stopping $DESC: "
start-stop-daemon --stop --quiet --pidfile /var/run/$NAME.pid
rm -f $PIDFILE
echo "$NAME."
;;
restart|force-reload)
#
# If the "reload" option is implemented, move the "force-reload"
# option to the "reload" entry above. If not, "force-reload" is
# just the same as "restart".
#
echo -n "Restarting $DESC: "
( $0 stop )
sleep 1
$0 start
;;
*)
N=/etc/init.d/$NAME
# echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
echo "Usage: $N {start|stop|restart|force-reload}" >&2
exit 1
start)
echo -n "Starting $DESC: "
[ -f $PIDFILE ] && [ ! -d /proc/`cat $PIDFILE` ] && rm -f $PIDFILE
start-stop-daemon --start --quiet --pidfile $PIDFILE \
-b --exec $DAEMON -- $DAEMON_OPTS
echo "$NAME."
;;
stop)
echo -n "Stopping $DESC: "
start-stop-daemon --stop --quiet --pidfile $PIDFILE
echo "$NAME."
;;
restart|force-reload)
echo -n "Restarting $DESC: "
( $0 stop )
sleep 1
$0 start
;;
status)
echo -n "Status of $DESC: "
if [ ! -e "$PIDFILE" ]; then
echo "$NAME is not running."
exit 3
fi
if [ ! -r "$PIDFILE" ]; then
echo "$PIDFILE not readable, status of $NAME unknown."
exit 4
fi
if [ -d /proc/`cat "$PIDFILE"` ]; then
echo "$NAME is running."
exit 0
else
echo "$NAME is not running but $PIDFILE exists."
exit 1
fi
;;
*)
N=/etc/init.d/$NAME
echo "Usage: $N {start|stop|restart|force-reload|status}" >&2
exit 1
;;
esac
exit 0
exit 0
+84 -29
View File
@@ -23,17 +23,29 @@ debug = false
#
logtargets = /var/log/fail2ban.log
# Option: syslog-target
# Notes.: where to find syslog facility if logtarget SYSLOG.
# Values: SOCKET HOST HOST:PORT Default: /dev/log
#
syslog-target = /dev/log
# Option: syslog-facility
# Notes.: which syslog facility to use if logtarget SYSLOG.
# Values: NUM Default: 1
#
syslog-facility = 1
# Option: pidlock
# Notes.: path of the PID lock file (must be able to write to file).
# Values: FILE Default: /var/run/fail2ban.pid
#
pidlock = /var/run/fail2ban.pid
# Option: maxretry
# Notes.: number of retrys before IP gets banned.
# Values: NUM Default: 3
# Option: maxfailures
# Notes.: number of failures before IP gets banned.
# Values: NUM Default: 5
#
maxretry = 3
maxfailures = 5
# Option: bantime
# Notes.: number of seconds an IP will be banned.
@@ -41,13 +53,19 @@ maxretry = 3
#
bantime = 600
# Option: findtime
# Notes.: lifetime in seconds of a "failed" log entry.
# Values: NUM Default: 600
#
findtime = 600
# Option: ignoreip
# Notes.: space separated list of IP's to be ignored by fail2ban.
# You can use CIDR mask in order to specify a range.
# Example: ignoreip = 192.168.0.1/24 123.45.235.65
# Values: IP Default: 192.168.0.0/24
# Values: IP Default: 192.168.0.0/16
#
ignoreip = 192.168.0.0/24
ignoreip = 192.168.0.0/16
# Option: cmdstart
# Notes.: command executed once at the start of Fail2Ban
@@ -56,7 +74,7 @@ ignoreip = 192.168.0.0/24
cmdstart =
# Option: cmdend
# Notes.: command executed once at the end of Fail2Ban
# Notes.: command executed once at the end of Fail2Ban.
# Values: CMD Default:
#
cmdend =
@@ -67,6 +85,21 @@ cmdend =
#
polltime = 1
# Option: reinittime
# Notes.: minimal number of seconds between the re-initialization of
# firewalls due to external changes in their rules (see fwcheck)
# Values: NUM Default: 100
#
reinittime = 10
# Option: maxreinits
# Notes.: maximal number of re-initialization of firewalls due to external
# changes. -1 stays for infinite, so only reinittime is of importance
# Values: NUM Default: -1
#
maxreinits = -1
[MAIL]
# Option: enabled
# Notes.: enable mail notification when banning an IP address.
@@ -99,26 +132,34 @@ from = fail2ban
#
to = root
# Option: localtime
# Notes.: report local time (including timezone) or GMT
# Values: [true | false] Default: false
#
localtime = true
# Option: subject
# Notes.: subject of the e-mail.
# Tags: <ip> IP address
# Tags: <section> active section (eg ssh, apache, etc)
# <ip> IP address
# <failures> number of failures
# <failtime> unix timestamp of the last failure
# Values: TEXT Default: [Fail2Ban] Banned <ip>
# Values: TEXT Default: [Fail2Ban] <section>: Banned <ip>
#
subject = [Fail2Ban] Banned <ip>
subject = [Fail2Ban] <section>: Banned <ip>
# Option: message
# Notes.: message of the e-mail.
# Tags: <ip> IP address
# Tags: <section> active section (eg ssh, apache, etc)
# <ip> IP address
# <failures> number of failures
# <failtime> unix timestamp of the last failure
# <br> new line
# Values: TEXT Default:
# Values: TEXT Default:
#
message = Hi,<br>
The IP <ip> has just been banned by Fail2Ban after
<failures> attempts.<br>
<failures> attempts against <section>.<br>
Regards,<br>
Fail2Ban
@@ -127,6 +168,7 @@ message = Hi,<br>
# options: logfile, fwban, fwunban, timeregex, timepattern,
# failregex.
[Apache]
# Option: enabled
# Notes.: enable monitoring for this section.
@@ -145,17 +187,23 @@ logfile = /var/log/httpd/access_log
# Values: CMD Default:
#
fwstart = iptables -N fail2ban-http
iptables -I INPUT -i eth0 -p tcp --dport http -j fail2ban-http
iptables -I INPUT -p tcp --dport http -j fail2ban-http
iptables -A fail2ban-http -j RETURN
# Option: fwend
# Notes.: command executed once at the end of Fail2Ban
# Values: CMD Default:
#
fwend = iptables -D INPUT -i eth0 -p tcp --dport http -j fail2ban-http
iptables -D fail2ban-http -j RETURN
fwend = iptables -D INPUT -p tcp --dport http -j fail2ban-http
iptables -F fail2ban-http
iptables -X fail2ban-http
# Option: fwcheck
# Notes.: command executed once before each fwban command
# Values: CMD Default:
#
fwcheck = iptables -L INPUT | grep -q fail2ban-http
# Option: fwban
# Notes.: command executed when banning an IP. Take care that the
# command is executed with Fail2Ban user rights.
@@ -164,9 +212,9 @@ fwend = iptables -D INPUT -i eth0 -p tcp --dport http -j fail2ban-http
# <failtime> unix timestamp of the last failure
# <bantime> unix timestamp of the ban time
# Values: CMD
# Default: iptables -I INPUT 1 -i eth0 -s <ip> -j DROP
# Default: iptables -I INPUT 1 -s <ip> -j DROP
#
fwban = iptables -I fail2ban-http 1 -i eth0 -s <ip> -j DROP
fwban = iptables -I fail2ban-http 1 -s <ip> -j DROP
# Option: fwunban
# Notes.: command executed when unbanning an IP. Take care that the
@@ -175,13 +223,13 @@ fwban = iptables -I fail2ban-http 1 -i eth0 -s <ip> -j DROP
# <bantime> unix timestamp of the ban time
# <unbantime> unix timestamp of the unban time
# Values: CMD
# Default: iptables -D INPUT -i eth0 -s <ip> -j DROP
# Default: iptables -D INPUT -s <ip> -j DROP
#
fwunban = iptables -D fail2ban-http -i eth0 -s <ip> -j DROP
fwunban = iptables -D fail2ban-http -s <ip> -j DROP
# Option: timeregex
# Notes.: regex to match timestamp in Apache logfile.
# Values: [Wed Jan 05 15:08:01 2005]
# Values: [Wed Jan 05 15:08:01 2005]
# Default: \S{3} \S{3} \d{2} \d{2}:\d{2}:\d{2} \d{4}
#
timeregex = \S{3} \S{3} \d{2} \d{2}:\d{2}:\d{2} \d{4}
@@ -199,6 +247,7 @@ timepattern = %%a %%b %%d %%H:%%M:%%S %%Y
#
failregex = authentication failure|user .* not found
[SSH]
# Option: enabled
# Notes.: enable monitoring for this section.
@@ -217,17 +266,23 @@ logfile = /var/log/secure
# Values: CMD Default:
#
fwstart = iptables -N fail2ban-ssh
iptables -I INPUT -i eth0 -p tcp --dport ssh -j fail2ban-ssh
iptables -I INPUT -p tcp --dport ssh -j fail2ban-ssh
iptables -A fail2ban-ssh -j RETURN
# Option: fwend
# Notes.: command executed once at the end of Fail2Ban
# Values: CMD Default:
#
fwend = iptables -D INPUT -i eth0 -p tcp --dport ssh -j fail2ban-ssh
iptables -D fail2ban-ssh -j RETURN
fwend = iptables -D INPUT -p tcp --dport ssh -j fail2ban-ssh
iptables -F fail2ban-ssh
iptables -X fail2ban-ssh
# Option: fwcheck
# Notes.: command executed once before each fwban command
# Values: CMD Default:
#
fwcheck = iptables -L INPUT | grep -q fail2ban-ssh
# Option: fwbanrule
# Notes.: command executed when banning an IP. Take care that the
# command is executed with Fail2Ban user rights.
@@ -236,9 +291,9 @@ fwend = iptables -D INPUT -i eth0 -p tcp --dport ssh -j fail2ban-ssh
# <failtime> unix timestamp of the last failure
# <bantime> unix timestamp of the ban time
# Values: CMD
# Default: iptables -I INPUT 1 -i eth0 -s <ip> -j DROP
# Default: iptables -I INPUT 1 -s <ip> -j DROP
#
fwban = iptables -I fail2ban-ssh 1 -i eth0 -s <ip> -j DROP
fwban = iptables -I fail2ban-ssh 1 -s <ip> -j DROP
# Option: fwunbanrule
# Notes.: command executed when unbanning an IP. Take care that the
@@ -247,13 +302,13 @@ fwban = iptables -I fail2ban-ssh 1 -i eth0 -s <ip> -j DROP
# <bantime> unix timestamp of the ban time
# <unbantime> unix timestamp of the unban time
# Values: CMD
# Default: iptables -D INPUT -i eth0 -s <ip> -j DROP
# Default: iptables -D INPUT -s <ip> -j DROP
#
fwunban = iptables -D fail2ban-ssh -i eth0 -s <ip> -j DROP
fwunban = iptables -D fail2ban-ssh -s <ip> -j DROP
# Option: timeregex
# Notes.: regex to match timestamp in SSH logfile.
# Values: [Mar 7 17:53:28]
# Values: [Mar 7 17:53:28]
# Default: \S{3}\s{1,2}\d{1,2} \d{2}:\d{2}:\d{2}
#
timeregex = \S{3}\s{1,2}\d{1,2} \d{2}:\d{2}:\d{2}
+1 -1
View File
@@ -18,6 +18,6 @@
#
# $Revision$
# Command line options for Fail2Ban. Refer to "fail2ban.py -h" for
# Command line options for Fail2Ban. Refer to "fail2ban -h" for
# valid options.
FAIL2BAN_OPTS="-v"
+6
View File
@@ -55,6 +55,12 @@ except Exception, e:
logSys.error("Type: " + `type.__name__` + "\n" +
"Value: " + `e.args` + "\n" +
"TB: " + `tbStack`)
# Try to clean up after ourselves
# just for extreme caution - wrapping with try
try:
fail2ban.restoreFwRules()
except Exception:
pass
# Remove the PID lock file. Should close #1239562
pidLock.remove()
logging.shutdown()
+197 -87
View File
@@ -15,6 +15,7 @@
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Author: Cyril Jaquier
# Modified by: Yaroslav Halchenko (SYSLOG, findtime)
#
# $Revision$
@@ -24,7 +25,7 @@ __date__ = "$Date$"
__copyright__ = "Copyright (c) 2004 Cyril Jaquier"
__license__ = "GPL"
import time, sys, getopt, os, string, signal, logging, logging.handlers
import time, sys, getopt, os, string, signal, logging, logging.handlers, copy
from ConfigParser import *
from version import version
@@ -61,8 +62,9 @@ def dispUsage():
print " -h display this help message"
print " -i <IP(s)> IP(s) to ignore"
print " -k kill a currently running instance"
print " -r <VALUE> allow a max of VALUE password failure"
print " -t <TIME> ban IP for TIME seconds"
print " -r <VALUE> allow a max of VALUE password failure [maxfailures]"
print " -t <TIME> ban IP for TIME seconds [bantime]"
print " -f <TIME> lifetime in seconds of failed entry [findtime]"
print " -v verbose. Use twice for greater effect"
print " -V print software version"
print
@@ -91,19 +93,48 @@ def sigTERMhandler(signum, frame):
logSys.debug("Signal handler called with sig "+`signum`)
killApp()
def setFwMustCheck(value):
""" Set the mustCheck value of the firewalls (True/False)
"""
for element in logFwList:
element[2].setMustCheck(value)
def initializeFwRules():
""" Initializes firewalls by running cmdstart and then
fwstart for each section
"""
# Execute global start command
executeCmd(conf["cmdstart"], conf["debug"])
# Execute start command of each section
for element in logFwList:
element[2].initialize(conf["debug"])
def reBan():
""" For each section asks the Firewall to reban known IPs
"""
for element in logFwList:
element[2].reBan(conf["debug"])
def restoreFwRules():
""" Flush the ban list
"""
logSys.warn("Restoring firewall rules...")
try:
for element in logFwList:
# Execute end command of each section
element[2].restore(conf["debug"])
# Execute global end command
executeCmd(conf["cmdend"], conf["debug"])
except ExternalError:
# nothing bad really - we can survive :-)
pass
def killApp():
""" Flush the ban list, remove the PID lock file and exit
nicely.
"""
logSys.warn("Restoring firewall rules...")
for element in logFwList:
element[2].flushBanList(conf["debug"])
# Execute end command of each section
for element in logFwList:
l = element[4]
executeCmd(l["fwend"], conf["debug"])
# Execute global start command
executeCmd(conf["cmdend"], conf["debug"])
# Restore Fw rules
restoreFwRules()
# Remove the PID lock
pidLock.remove()
logSys.info("Exiting...")
@@ -114,10 +145,6 @@ def getCmdLineOptions(optList):
""" Gets the command line options
"""
for opt in optList:
if opt[0] in ["-h", "--help"]:
dispUsage()
if opt[0] in ["-V", "--version"]:
dispVersion()
if opt[0] == "-v":
conf["verbose"] = conf["verbose"] + 1
if opt[0] == "-b":
@@ -130,21 +157,20 @@ def getCmdLineOptions(optList):
except ValueError:
logSys.warn("banTime must be an integer")
logSys.warn("Using default value")
if opt[0] == "-f":
try:
conf["findtime"] = int(opt[1])
except ValueError:
logSys.warn("findTime must be an integer")
logSys.warn("Using default value")
if opt[0] == "-i":
conf["ignoreip"] = opt[1]
if opt[0] == "-r":
conf["maxretry"] = int(opt[1])
conf["maxfailures"] = int(opt[1])
if opt[0] == "-p":
conf["pidlock"] = opt[1]
if opt[0] == "-k":
pid = checkForPID(conf["pidlock"])
if pid:
killPID(int(pid))
logSys.warn("Killed Fail2Ban with PID "+pid)
sys.exit(0)
else:
logSys.error("No running Fail2Ban found")
sys.exit(-1)
conf["kill"] = True
def main():
""" Fail2Ban main function
@@ -155,9 +181,11 @@ def main():
logSys.addHandler(stdout)
# Default formatter
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
formatterstring='%(levelname)s: %(message)s'
formatter = logging.Formatter('%(asctime)s ' + formatterstring)
stdout.setFormatter(formatter)
conf["kill"] = False
conf["verbose"] = 0
conf["conffile"] = "/etc/fail2ban.conf"
@@ -173,6 +201,10 @@ def main():
for opt in optList:
if opt[0] == "-c":
conf["conffile"] = opt[1]
if opt[0] in ["-h", "--help"]:
dispUsage()
if opt[0] in ["-V", "--version"]:
dispVersion()
# Reads the config file and create a LogReader instance for
# each log file to check.
@@ -182,20 +214,39 @@ def main():
# Options
optionValues = (["bool", "background", False],
["str", "logtargets", "/var/log/fail2ban.log"],
["str", "syslog-target", "/dev/log"],
["int", "syslog-facility", 1],
["bool", "debug", False],
["str", "pidlock", "/var/run/fail2ban.pid"],
["int", "maxretry", 3],
["int", "maxfailures", 5],
["int", "bantime", 600],
["int", "findtime", 600],
["str", "ignoreip", ""],
["int", "polltime", 1],
["str", "cmdstart", ""],
["str", "cmdend", ""])
["str", "cmdend", ""],
["int", "reinittime", 100],
["int", "maxreinits", 100])
# Gets global configuration options
conf.update(confReader.getLogOptions("DEFAULT", optionValues))
# Gets command line options
getCmdLineOptions(optList)
# PID lock
pidLock.setPath(conf["pidlock"])
# Now we can kill properly a running instance if needed
if conf["kill"]:
pid = pidLock.exists()
if pid:
killPID(int(pid))
logSys.warn("Killed Fail2Ban with PID "+pid)
sys.exit(0)
else:
logSys.error("No running Fail2Ban found")
sys.exit(-1)
# Start Fail2Ban in daemon mode
if conf["background"]:
@@ -205,6 +256,58 @@ def main():
logSys.error("Unable to start daemon")
sys.exit(-1)
# Process some options
# First setup Log targets
# Bug fix for #1234699
os.umask(0077)
for target in conf["logtargets"].split():
# target formatter
# By default global formatter is taken. Is different for SYSLOG
tformatter = formatter
if target == "STDERR":
hdlr = logging.StreamHandler(sys.stderr)
elif target == "SYSLOG":
# SYSLOG target can be either
# a socket (file, so it starts with /)
# or hostname
# or hostname:port
syslogtargets = re.findall("(/[\w/]*)|([^/ ][^: ]*)(:(\d+)){,1}",
conf["syslog-target"])
# we are waiting for a single match
syslogtargets = syslogtargets[0]
# assign facility if it was defined
if conf["syslog-facility"] < 0:
facility = handlers.SysLogHandler.LOG_USER
else:
facility = conf["syslog-facility"]
if len(syslogtargets) == 0: # everything default
hdlr = logging.handlers.SysLogHandler()
else:
if not ( syslogtargets[0] == "" ): # got socket
syslogtarget = syslogtargets[0]
else: # got hostname and maybe a port
if syslogtargets[3] == "": # no port specified
port = 514
else:
port = int(syslogtargets[3])
syslogtarget = (syslogtargets[1], port)
hdlr = logging.handlers.SysLogHandler(syslogtarget, facility)
tformatter = logging.Formatter("fail2ban[%(process)d]: " +
formatterstring);
else:
# Target should be a file
try:
open(target, "a")
hdlr = logging.FileHandler(target)
except IOError:
logSys.error("Unable to log to " + target)
continue
# Set formatter and add handler to logger
hdlr.setFormatter(tformatter)
logSys.addHandler(hdlr)
# Verbose level
if conf["verbose"]:
logSys.warn("Verbose level is "+`conf["verbose"]`)
@@ -216,46 +319,16 @@ def main():
# Set debug log level
if conf["debug"]:
logSys.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s %(levelname)s " +
"[%(filename)s (%(lineno)d)] " +
"%(message)s")
formatterstring = ('%(levelname)s: [%(filename)s (%(lineno)d)] ' +
'%(message)s')
formatter = logging.Formatter("%(asctime)s " + formatterstring)
stdout.setFormatter(formatter)
logSys.warn("DEBUG MODE: FIREWALL COMMANDS ARE _NOT_ EXECUTED BUT " +
"ONLY DISPLAYED IN THE LOG MESSAGES")
# Process some options
# Log targets
# Bug fix for #1234699
os.umask(0077)
for target in conf["logtargets"].split():
if target == "STDERR":
hdlr = logging.StreamHandler(sys.stderr)
elif target == "SYSLOG":
hdlr = logging.handlers.SysLogHandler()
else:
# Target should be a file
try:
open(target, "a")
hdlr = logging.FileHandler(target)
except IOError:
logSys.error("Unable to log to " + target)
continue
# Set formatter and add handler to logger
hdlr.setFormatter(formatter)
logSys.addHandler(hdlr)
# PID lock
pidLock.setPath(conf["pidlock"])
# Ignores IP list
ignoreIPList = conf["ignoreip"].split(' ')
# maxretry option
maxRetry = conf["maxretry"]
# bantime option
banTime = conf["bantime"]
# Checks for root user. This is necessary because log files
# are owned by root and firewall needs root access.
if not checkForRoot():
@@ -269,11 +342,15 @@ def main():
logSys.error("Fail2Ban already running with PID "+pid)
sys.exit(-1)
else:
pidLock.create()
ret = pidLock.create()
if not ret:
# Unable to create PID lock. Exit
sys.exit(-1)
logSys.debug("ConfFile is " + conf["conffile"])
logSys.debug("BanTime is " + `conf["bantime"]`)
logSys.debug("retryAllowed is " + `conf["maxretry"]`)
logSys.debug("FindTime is " + `conf["findtime"]`)
logSys.debug("MaxFailure is " + `conf["maxfailures"]`)
# Options
optionValues = (["bool", "enabled", False],
@@ -281,6 +358,7 @@ def main():
["int", "port", "25"],
["str", "from", "root"],
["str", "to", "root"],
["bool", "localtime", False],
["str", "subject", "[Fail2Ban] Banned <ip>"],
["str", "message", "Fail2Ban notification"])
@@ -293,38 +371,38 @@ def main():
mail = Mail(mailConf["host"], mailConf["port"])
mail.setFromAddr(mailConf["from"])
mail.setToAddr(mailConf["to"])
mail.setLocalTimeFlag(mailConf["localtime"])
logSys.debug("to: " + mailConf["to"] + " from: " + mailConf["from"])
# Options
optionValues = (["bool", "enabled", False],
["str", "logfile", "/dev/null"],
["int", "maxretry", None],
["int", "bantime", None],
["int", "maxfailures", conf["maxfailures"]],
["int", "bantime", conf["bantime"]],
["int", "findtime", conf["findtime"]],
["str", "timeregex", ""],
["str", "timepattern", ""],
["str", "failregex", ""],
["str", "fwstart", ""],
["str", "fwend", ""],
["str", "fwban", ""],
["str", "fwunban", ""])
["str", "fwunban", ""],
["str", "fwcheck", ""])
logSys.info("Fail2Ban v" + version + " is running")
# Gets the options of each sections
for t in confReader.getSections():
l = confReader.getLogOptions(t, optionValues)
if l["enabled"]:
# Override maxretry option
if not l["maxretry"] == None:
maxRetry = l["maxretry"]
# Override bantime option
if not l["bantime"] == None:
banTime = l["bantime"]
# Creates a logreader object
lObj = LogReader(l["logfile"], l["timeregex"], l["timepattern"],
l["failregex"], maxRetry, banTime)
l["failregex"], l["maxfailures"], l["findtime"])
# Creates a firewall object
fObj = Firewall(l["fwban"], l["fwunban"], banTime)
fObj = Firewall(l["fwstart"], l["fwend"], l["fwban"], l["fwunban"],
l["fwcheck"], l["bantime"])
# "Name" the firewall
fObj.setSection(t)
# Links them into a list. I'm not really happy
# with this :/
logFwList.append([t, lObj, fObj, dict(), l])
@@ -339,14 +417,13 @@ def main():
if isValidIP(ip):
for element in logFwList:
element[1].addIgnoreIP(ip)
else:
logSys.warn(ip + " is not a valid IP address")
logSys.info("Fail2Ban v" + version + " is running")
# Execute global start command
executeCmd(conf["cmdstart"], conf["debug"])
# Execute start command of each section
for element in logFwList:
l = element[4]
executeCmd(l["fwstart"], conf["debug"])
initializeFwRules()
# try to reinit once if it fails immediately
lastReinitTime = time.time() - conf["reinittime"] - 1
reinits = 0
# Main loop
while True:
try:
@@ -393,7 +470,8 @@ def main():
if failTime < unixTime - findTime:
del element[3][attempt]
elif fails[attempt][0] >= element[1].getMaxRetry():
aInfo = {"ip": attempt,
aInfo = {"section": element[0],
"ip": attempt,
"failures": element[3][attempt][0],
"failtime": failTime}
logSys.info(element[0] + ": " + aInfo["ip"] +
@@ -405,7 +483,39 @@ def main():
mail.sendmail(mailConf["subject"],
mailConf["message"], aInfo)
del element[3][attempt]
except ExternalError, e:
# Something wrong while dealing with Iptables.
# May be chain got removed?
reinits += 1
logSys.error(e)
if ((unixTime - lastReinitTime > conf["reinittime"]) and
((conf["maxreinits"] < 0) or (reinits < conf["maxreinits"]))):
logSys.warn("#%d reinitialization of firewalls"%reinits)
lastReinitTime = unixTime
else:
logSys.error("Exiting: reinits follow too often, or too many " +
"reinit attempts")
killApp()
# We already failed runCheck so disable it until
# restoring a safe state
setFwMustCheck(False)
# save firewalls to keep a list of IPs for rebanning
logFwListCopy = copy.deepcopy(logFwList)
try:
# restore as much as possible
restoreFwRules()
# reinitialize all the chains
initializeFwRules()
# restore the lists of baned IPs
logFwList.__init__(logFwListCopy)
# reBan known IPs
reBan()
# Now we can enable the runCheck test again
setFwMustCheck(True)
except ExternalError:
raise ExternalError("Big Oops happened: situation is out of " +
"control. Something is wrong with your " +
"setup. Please check your settings")
except KeyboardInterrupt:
# When the user press <ctrl>+<c> we exit nicely.
killApp()
+78 -8
View File
@@ -28,6 +28,10 @@ import time, os, logging, re
from utils.process import executeCmd
from utils.strings import replaceTag
# unfortunately but I have to bring ExternalError in especially for
# flushBanList: if one of IPs got flushed manually outside or something, we
# might endup with not "full" flush unless we handle exception within the loop
from utils.process import ExternalError
# Gets the instance of the logger.
logSys = logging.getLogger("fail2ban")
@@ -37,41 +41,102 @@ class Firewall:
the IP.
"""
def __init__(self, banRule, unBanRule, banTime):
def __init__(self, startRule, endRule, banRule, unBanRule, checkRule,
banTime):
self.banRule = banRule
self.unBanRule = unBanRule
self.checkRule = checkRule
self.startRule = startRule
self.endRule = endRule
self.banTime = banTime
self.banList = dict()
self.section = ""
self.mustCheck = True
def setSection(self, section):
""" Set optional section name for clarify of logging
"""
self.section = section
def getMustCheck(self):
""" Return true if the runCheck test is executed
"""
return self.mustCheck
def setMustCheck(self, value):
""" Enable or disable the execution of runCheck test
"""
self.mustCheck = value
def initialize(self, debug):
logSys.debug("%s: Initialize firewall rules"%self.section)
executeCmd(self.startRule, debug)
def restore(self, debug):
logSys.debug("%s: Restore firewall rules"%self.section)
try:
self.flushBanList(debug)
executeCmd(self.endRule, debug)
except ExternalError:
pass
def addBanIP(self, aInfo, debug):
""" Bans an IP.
"""
ip = aInfo["ip"]
if not self.inBanList(ip):
crtTime = time.time()
logSys.warn("Ban " + ip)
logSys.warn("%s: Ban "%self.section + ip)
self.banList[ip] = crtTime
aInfo["bantime"] = crtTime
executeCmd(self.banIP(aInfo), debug)
self.runCheck(debug)
cmd = self.banIP(aInfo)
if executeCmd(cmd, debug):
raise ExternalError("Firewall: execution of fwban command " +
"'%s' failed"%cmd)
else:
logSys.error(ip+" already in ban list")
self.runCheck(debug)
logSys.error("%s: "%self.section+ip+" already in ban list")
def delBanIP(self, aInfo, debug):
""" Unban an IP.
"""
ip = aInfo["ip"]
if self.inBanList(ip):
logSys.warn("Unban "+ip)
logSys.warn("%s: Unban "%self.section + ip)
del self.banList[ip]
self.runCheck(debug)
executeCmd(self.unBanIP(aInfo), debug)
else:
logSys.error(ip+" not in ban list")
logSys.error("%s: "%self.section+ip+" not in ban list")
def reBan(self, debug):
""" Re-Bans known IPs.
TODO: implement "failures" and "failtime"
"""
for ip in self.banList:
aInfo = {"ip": ip,
"bantime":self.banList[ip]}
logSys.warn("%s: ReBan "%self.section + ip)
# next piece is similar to the on in addBanIp
# so might be one more function will not hurt
self.runCheck(debug)
executeCmd(self.banIP(aInfo), debug)
def inBanList(self, ip):
""" Checks if IP is in ban list.
"""
return self.banList.has_key(ip)
def runCheck(self, debug):
""" Runs fwcheck command and throws an exception if it returns non-0
result
"""
if self.mustCheck:
executeCmd(self.checkRule, debug)
else:
return None
def checkForUnBan(self, debug):
""" Check for IP to remove from ban list.
"""
@@ -93,7 +158,12 @@ class Firewall:
aInfo = {"ip": element[0],
"bantime": element[1],
"unbantime": time.time()}
self.delBanIP(aInfo, debug)
try:
self.delBanIP(aInfo, debug)
except ExternalError:
# we must let it fail here in the loop, or we don't
# flush properly
pass
def banIP(self, aInfo):
""" Returns query to ban IP.
+23 -12
View File
@@ -89,7 +89,7 @@ class LogReader:
fileHandler = open(self.logPath)
except OSError:
logSys.error("Unable to open "+self.logPath)
sys.exit(-1)
return fileHandler
def isModified(self):
@@ -97,16 +97,15 @@ class LogReader:
"""
try:
self.logStats = os.stat(self.logPath)
if self.lastModTime == self.logStats.st_mtime:
return False
else:
logSys.debug(self.logPath+" has been modified")
self.lastModTime = self.logStats.st_mtime
return True
except OSError:
logSys.error("Unable to get stat on "+self.logPath)
sys.exit(-1)
if self.lastModTime == self.logStats.st_mtime:
return False
else:
logSys.debug(self.logPath+" has been modified")
self.lastModTime = self.logStats.st_mtime
return True
def setFilePos(self, file):
""" Sets the file position. We must take care of log file rotation
@@ -135,11 +134,13 @@ class LogReader:
logSys.debug(self.logPath)
logFile = self.openLogFile()
self.setFilePos(logFile)
lastLine = ''
lastLine = None
for line in logFile:
if not self.hasTime(line):
# There is no valid time in this line
continue
lastLine = line
failList = self.findFailure(line)
for element in failList:
for element in self.findFailure(line):
ip = element[0]
unixTime = element[1]
if unixTime < time.time()-self.findTime:
@@ -153,7 +154,8 @@ class LogReader:
else:
ipList[ip] = (1, unixTime)
self.lastPos = logFile.tell()
self.lastDate = self.getTime(lastLine)
if lastLine:
self.lastDate = self.getTime(lastLine)
logFile.close()
return ipList
@@ -176,6 +178,15 @@ class LogReader:
failList.append([ip, date])
return failList
def hasTime(self, line):
""" Return true if the line contains a date
"""
timeMatch = re.search(self.timeregex, line)
if timeMatch:
return True
else:
return False
def getTime(self, line):
""" Gets the time of a log message.
"""
+5 -2
View File
@@ -33,10 +33,13 @@ display this help message
kill a currently running Fail2Ban instance
.TP
\fB\-r\fR \fIVALUE\fR
allow a max of \fIVALUE\fR password failure
allow a max of \fIVALUE\fR password failure [maxfailures]
.TP
\fB\-t\fR \fITIME\fR
ban IP for \fITIME\fR seconds
ban IP for \fITIME\fR seconds [bantime]
.TP
\fB\-f\fR \fITIME\fR
lifetime in seconds of failed entry [findtime]
.TP
\fB\-v\fR
verbose. Use twice for greater effect
+1 -1
View File
@@ -36,7 +36,7 @@ Fail2Ban scans log files like /var/log/pwdfail or
/var/log/apache/error_log and bans IP that makes
too many password failures. It updates firewall rules
to reject the IP address or executes user defined
commands. It needs log4py.'''
commands.'''
setup(
name = "fail2ban",
+2 -1
View File
@@ -58,8 +58,9 @@ def searchIP(text):
def isValidIP(str):
""" Return true if str is a valid IP
"""
s = str.split('/', 1)
try:
socket.inet_aton(str)
socket.inet_aton(s[0])
return True
except socket.error:
return False
+14 -6
View File
@@ -24,7 +24,7 @@ __date__ = "$Date$"
__copyright__ = "Copyright (c) 2004 Cyril Jaquier"
__license__ = "GPL"
import logging, smtplib
import logging, smtplib, email.Utils
from utils.strings import replaceTag
@@ -38,6 +38,7 @@ class Mail:
def __init__(self, host, port = 25):
self.host = host
self.port = port
self.localTimeFlag = False
def setFromAddr(self, fromAddr):
""" Set from: address
@@ -49,14 +50,21 @@ class Mail:
"""
self.toAddr = toAddr.split()
def setLocalTimeFlag(self, localTimeFlag):
""" Set to: address
"""
self.localTimeFlag = localTimeFlag
def sendmail(self, subject, message, aInfo):
""" Send an email using smtplib
"""
subj = replaceTag(subject, aInfo)
msg = replaceTag(message, aInfo)
mail = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" %
(self.fromAddr, ", ".join(self.toAddr), subj)) + msg
mail = ("From: %s\r\nTo: %s\r\nDate: %s\r\nSubject: %s\r\n\r\n" %
(self.fromAddr, ", ".join(self.toAddr),
email.Utils.formatdate(localtime = self.localTimeFlag),
subj)) + msg
try:
server = smtplib.SMTP(self.host, self.port)
@@ -64,8 +72,8 @@ class Mail:
server.sendmail(self.fromAddr, self.toAddr, mail)
logSys.debug("Email sent to " + `self.toAddr`)
server.quit()
except Exception:
except Exception, e:
logSys.error("Unable to send mail to " + self.host + ":" +
`self.port` + " from " + self.fromAddr + " to " +
`self.toAddr`)
`self.toAddr` + ": " + `e` + ": " + `e.args`)
+18 -7
View File
@@ -51,17 +51,28 @@ class PIDLock:
def create(self):
""" Create PID lock.
"""
fileHandler = open(self.path, mode='w')
pid = os.getpid()
fileHandler.write(`pid` + '\n')
fileHandler.close()
logSys.debug("Created PID lock (" + `pid` + ") in " + self.path)
try:
fileHandler = open(self.path, mode='w')
pid = os.getpid()
fileHandler.write(`pid` + '\n')
fileHandler.close()
logSys.debug("Created PID lock (" + `pid` + ") in " + self.path)
return True
except:
logSys.error("Unable to create PID lock " + self.path)
return False
def remove(self):
""" Remove PID lock.
"""
os.remove(self.path)
logSys.debug("Removed PID lock " + self.path)
try:
os.remove(self.path)
logSys.debug("Removed PID lock " + self.path)
except OSError:
logSys.error("Unable to remove PID lock " + self.path)
except AttributeError:
# AttributeError if self.path wasn't specified yet
logSys.debug("PID lock not removed because not defined yet")
def exists(self):
""" Returns the current PID if Fail2Ban is running or False
+6
View File
@@ -29,6 +29,11 @@ import os, logging, signal
# Gets the instance of the logger.
logSys = logging.getLogger("fail2ban")
class ExternalError(UserWarning):
""" Exception to warn about failed fwcheck or fwban command
"""
pass
def createDaemon():
""" Detach a process from the controlling terminal and run it in the
background as a daemon.
@@ -126,6 +131,7 @@ def executeCmd(cmd, debug):
retval = os.system(cmd)
if not retval == 0:
logSys.error("'" + cmd + "' returned " + `retval`)
raise ExternalError("Execution of command '%s' failed" % cmd)
return retval
else:
return None
+1 -1
View File
@@ -24,4 +24,4 @@ __date__ = "$Date$"
__copyright__ = "Copyright (c) 2004 Cyril Jaquier"
__license__ = "GPL"
version = "0.5.2"
version = "0.6.0"