Fail2ban

Fail2ban - Asterisk jak Cię draznią akaki na your exchange to jest pakiecik wprost dla Ciebie

Original page contentHello all,I have fail2ban installed on CentOS 4.7 with Shoreline Firewall (Shorewall) and IpTables. This works well with SSH, Apache and Named bans. However, I am still trying to get it to ban failed SIP registration attempts in Asterisk.My jail.conf contains the following for Asterisk:[asterisk-iptables]enabled  = true
filter   = asterisk
action   = iptables-allports[name=ASTERISK, protocol=all]
              sendmail[name=ASTERISK, dest=you@yourmail.co.uk, sender=fail2ban@local.local]
logpath  = /var/log/messages
maxretry = 2
bantime = 259200Here is the filter.d/asterisk file:# Fail2Ban configuration file
#
#
# $Revision: 250 $
#[INCLUDES]# Read common prefixes. If any customizations available -- read them from
# common.local
#before = common.conf
[Definition]#_daemon = asterisk# Option:  failregex
# Notes.:  regex to match the password failures messages in the logfile. The
#          host must be matched by a group named "host". The tag "" can
#          be used for standard IP/hostname matching and is only an alias for
#          (?:::f{4,6}:)?(?P\S+)
# Values:  TEXT
#failregex = NOTICE.* .*: Registration from '.*' failed for '' - Wrong password
            NOTICE.* .*: Registration from '.*' failed for '' - No matching peer found
            NOTICE.* .*: Registration from '.*' failed for '' - Username/auth name mismatch
            NOTICE.*  failed to authenticate as '.*'$
            NOTICE.* .*: No registration for peer '.*' (from )
            NOTICE.* .*: Host  failed MD5 authentication for '.*' (.*)# Option:  ignoreregex
# Notes.:  regex to ignore. If this regex matches, the line is ignored.
# Values:  TEXT
#
ignoreregex =
Fail2BanFail2Ban is a limited intrusion detection/prevention system. It works by scanning log files and then taking action based on the entries in those logs.
We are implementing Fail2Ban with a configuration to be able to prevent SIP brute force attacks against our Asterisk PBXs.You can get Fail2Ban, as well as more documentation, at www.fail2ban.org. At the time this is being written, the current release is 0.8.4.Fail2Ban With AsteriskThe following describes how to setup Fail2Ban to protect an Asterisk PBX from SIP brute force attempts and scans utilizing the iptables firewall.Easy Install Script for Fail2ban version 0.8.4 / Red HatThis script was written by Cédric Brohée in order to simplify and accelerate the integration of the solution in a basic Asterisk configuration on Red Hat.
Do not hesitate to read the bash script and make changes to match your own configuration.Before running it, you will have to do chmod 755.Download script :
Fail2ban.sh.txt
Dan at VoicePlex fixed a small error in the script to download and unpack fail2ban ...
Fail2ban.sh.new.txtInstallingLog into the system and su - root, or sudo -i to get a root shell on Ubuntu.CentOS/Red Hat (this method may install an older version of fail2ban):Install rpmforge or optionally fetch the fail2ban rpm directly from rpmforge.
Install fail2ban using yum:yum install fail2banDebian/Ubuntu:apt-get install fail2banSource installation:
Change directories to /usr/src:cd /usr/srcDownload and extract Fail2Ban (check for newer releases):wget http://superb-east.dl.sourceforge.net/sourceforge/fail2ban/fail2ban-0.8.4.tar.bz2
tar jxf fail2ban-0.8.4.tar.bz2Enter the Fail2Ban directory you just extracted:cd fail2ban-0.8.4Make sure python and iptables are installed:CentOS/Red Hat:yum install python iptablesDebian/Ubuntu:apt-get install python iptablesInstall Fail2Ban:python setup.py installInstall the Fail2Ban init script (for source installations):Centos/Red Hat (if you installed via yum/rpm, the init script has already been installed):cp /usr/src/fail2ban-0.8.4/files/redhat-initd /etc/init.d/fail2ban
chmod 755 /etc/init.d/fail2banFor other distributions' init scripts, please refer to documentation specific to them.
Configure Fail2BanWe need to create a configuration for Fail2Ban so that it can understand attacks against Asterisk.Create a new filter configuration for Asterisk:touch /etc/fail2ban/filter.d/asterisk.confThe contents of /etc/fail2ban/filter.d/asterisk.conf should be the following:
# Fail2Ban configuration file
#
#
# $Revision: 250 $
#[INCLUDES]# Read common prefixes. If any customizations available -- read them from
# common.local
#before = common.conf
[Definition]#_daemon = asterisk# Option:  failregex
# Notes.:  regex to match the password failures messages in the logfile. The
#          host must be matched by a group named "host". The tag "" can
#          be used for standard IP/hostname matching and is only an alias for
#          (?:::f{4,6}:)?(?P\S+)
# Values:  TEXT
#failregex = NOTICE.* .*: Registration from '.*' failed for '' - Wrong password
            NOTICE.* .*: Registration from '.*' failed for '' - No matching peer found
            NOTICE.* .*: Registration from '.*' failed for '' - Username/auth name mismatch
            NOTICE.* .*: Registration from '.*' failed for '' - Device does not match ACL
            NOTICE.* .*: Registration from '.*' failed for '' - Peer is not supposed to register
            NOTICE.*  failed to authenticate as '.*'$
            NOTICE.* .*: No registration for peer '.*' \(from \)
            NOTICE.* .*: Host  failed MD5 authentication for '.*' (.*)
            NOTICE.* .*: Failed to authenticate user .*@.*# Option:  ignoreregex
# Notes.:  regex to ignore. If this regex matches, the line is ignored.
# Values:  TEXT
#
ignoreregex =Next edit /etc/fail2ban/jail.conf to include the following section so that it uses the new filter. This does a 3-day ban on the IP that performed the attack. It is recommend to set the bantime in the [DEFAULT] section so if affects all attacks. It is also recommend to turn on an iptables ban for ssh, httpd/apache, and ftp if they are running on the system. Be sure to edit the sendmail-whois action to send notifications to an appropriate address:
[asterisk-iptables]enabled  = true
filter   = asterisk
action   = iptables-allports[name=ASTERISK, protocol=all]
           sendmail-whois[name=ASTERISK, dest=root, sender=fail2ban@example.org]
logpath  = /var/log/asterisk/messages
maxretry = 5
bantime = 259200note: logpath = /var/log/asterisk/messages is for vanilla asterisk, use logpath = /var/log/asterisk/full for freepbx. You can check the name of the log file in logger.conf.note: if fail2ban still failed to identify login attempts, try the syslog logging way.Don't Ban YourselfWe don't want to ban ourselves by accident. Edit /etc/fail2ban/jail.conf and edit the ignoreip option under the [DEFAULT] section to include your IP addresses or network, as well as any other hosts or networks you do not wish to ban. Note that the addresses must be separated by a SPACE character!Asterisk LoggingWe must change how Asterisk does its time stamp for logging. The default format does not work with Fail2Ban because the pattern Fail2Ban uses that would match this format has a beginning of line character (^), and Asterisk puts its date/time inside of []. The other formats that Fail2Ban supports, however, do not have this character and can be used with Asterisk.To change this format, open /etc/asterisk/logger.conf and add the following line under [general] section (You may have to create this before the [logfiles] section). This causes the date and time to be formatted as Year-Month-Day Hour:Minute:Second, [2008-10-01 13:40:04] is an example.
 [general]
 dateformat=%F %TThen reload the logger module for Asterisk. At the command line, run the following command:asterisk -rx "logger reload"If for some reason you do not want to change the date/time format for your normal asterisk logs (maybe you already have scripts that use it or something and do not want to edit them), you can do the following instead:In /etc/asterisk/logger.conf, add the following line under the [logfiles] section for Asterisk to log NOTICE level events to the syslog (/var/log/messages) as well as its normal log file. These entries in syslog will have a Date/Time stamp that is usable by Fail2Ban.syslog.local0 => noticeBe sure to reload the logger module for Asterisk — check above for the command to do so. If you chose this option, you will also have to change the /etc/fail2ban/jail.conf setting under the [asterisk-iptables] section for the logpath option to the following:logpath  = /var/log/messagesTurning it OnNow it is time to put fail2ban to work. There are a couple steps we need to do first.Turn IPTABLES onBy default, iptables allows all traffic. So if we turn it on, it will not block any traffic until Fail2Ban creates deny rules for attackers. You should create your own firewall rules and setup for iptables, but that is beyond the scope of this guide. Just know that Fail2Ban, by default, inserts rules at the top of the chain, so they will override any rules you have configured in iptables. This is good because you may allow all sip traffic in and then the Fail2Ban will block individual hosts, after they have done an attack, before they are allowed by this rule again.To start iptables, run the following as root:/etc/init.d/iptables startDepending on your install, you may or may not have the iptables init script installed. Please refer to an iptables install/setup guide for your distribution for more information.Turn on Fail2BanTo start Fail2Ban, run the following as root:/etc/init.d/fail2ban startCheck ItIf both started properly, issue the following command to view your iptables rules:iptables -L -vYou should see something like the following for the INPUT chain (you will see more if you have other Fail2Ban filters enabled):Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination         
2104K  414M fail2ban-ASTERISK  all  —  any    any     anywhere             anywhereIf you do not see something similar to that, then you have some troubleshooting to do; check out /var/log/fail2ban.log.If you do not see all your rules, or if you see a different subset of rules after stopping and restarting fail2ban, you may be experiencing the issue described on this page on the Fail2ban talk:Community Portal and may wish to use the suggested fix:fail2ban.action.action ERROR on startup/restartI had multiple fail2ban.action.action ERROR on startup/restart. It seems there was a "race" condition with iptables. I solved the problem completely on my system by editing /usr/bin/fail2ban-client and adding a time.sleep(0.1)
def __processCmd(self, cmd, showRet = True):
    beautifier = Beautifier()
    for c in cmd:
        time.sleep(0.1)
        beautifier.setInputCmd(c)Turn it on for goodIf all is well up to this point, let's make sure that fail2ban and iptables restart with the server by issuing the following commands.Centos/Red Hat:chkconfig iptables on
chkconfig fail2ban onDebian/Ubuntu:update-rc.d iptables defaults
update-rc.d fail2ban defaultsYou should now be somewhat protected against SIP scans and brute force attacks!Try a rebootOnce you have fail2ban working ok, make sure that it continues that way after rebooting the server. On some distributions (including Ubuntu daper) fail2ban won't start after the system reboots because the /var/run/fail2ban directory gets deleted and needs to be re-created. This can be frustrating as there is also nothing that shows up in the logs to indicate what the problem is. If this happens, please see the link below for instructions on modifying the startup script so that it checks for and creates the /var/run/fail2ban directory if needed: