Fail2ban on asterisk

im traying to configure fail2ban on my asterisk
/etc/fail2ban/jail.conf
[asterisk-iptables]
enabled = true
filter = asterisk
action = iptables-allports[name=ASTERISK, protocol=all]
logpath = /var/log/asterisk/messages
maxretry = 2
bantime = 3600


/etc/fail2ban/filter.d/asterisk.conf

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

Asterisk 1.4 use the following failregex

failregex = NOTICE.* .: Registration from '.’ failed for ‘’ - Wrong password
NOTICE.* .: Registration from '.’ failed for ‘:.’ - No matching peer found
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.* .: Registration from '.’ failed for ‘’ - ACL error (permit/deny)
NOTICE.* .: Registration from '.’ failed for ‘’ - Device does not match ACL
NOTICE.* failed to authenticate as ‘.’$
NOTICE.
.: No registration for peer '.’ (from )
NOTICE.* .: Host failed MD5 authentication for '.’ (.)
NOTICE.
.: Failed to authenticate user .@.*
NOTICE.* .: Sending fake auth rejection for device .<sip:.@>;tag=.

In Asterisk 1.8 use the same as above, but after add :.* before the single quote. This is because in Asterisk 1.8, the log file includes a port number which 1.4 did not.

Option: ignoreregex

Notes.: regex to ignore. If this regex matches, the line is ignored.

Values: TEXT


and i restart fail2ban for the new configuration file to load:

fail2ban-client reload


fail2ban-client status

Status
|- Number of jail: 2
`- Jail list: asterisk-iptables, sshd


and i try to check the work:

fail2ban-client status asterisk-iptables

Status for the jail: asterisk-iptables
|- Filter
| |- Currently failed: 0
| |- Total failed: 0
| - File list: /var/log/asterisk/messages - Actions
|- Currently banned: 0
|- Total banned: 0
`- Banned IP list:


iptables -L

i should see something like the following for the INPUT chain:

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 anywhere
but the problem i do not see something similar to that i see this: Chain INPUT (policy ACCEPT)
target prot opt source destination

Chain FORWARD (policy ACCEPT)
target prot opt source destination

Chain OUTPUT (policy ACCEPT)
target prot opt source destination

and i dont undrestand where the problem and to fix it ???

I’m using asterisk 13.38, on OrangePI with Armbian:

Linux orangepipc 5.3.13-sunxi #19.11.3 SMP Fri Dec 6 14:09:51 CET 2019 armv7l GNU/Linux
Distributor ID: Debian
Description: Debian GNU/Linux 10 (buster)
Release: 10
Codename: buster

cat /etc/debian_version:
10.2

Fail2Ban version is:

fail2ban/stable,now 0.10.2-2.1 all [installed]

Here is my config:
jail.conf:

[asterisk]

port = 5060,5061
action = %(banaction)s[name=%(name)s-tcp, port="%(port)s", protocol=“tcp”, chain="%(chain)s", actname=%(banaction)s-tcp]
%(banaction)s[name=%(name)s-udp, port="%(port)s", protocol=“udp”, chain="%(chain)s", actname=%(banaction)s-udp]
%(mta)s-whois[name=%(name)s, dest="%(destemail)s"]
logpath = /var/log/asterisk/messages
maxretry = 10

jail.local

[asterisk]
enabled = true
port = xxxxxx
filter = asterisk
logpath = /var/log/asterisk/messages
maxretry = 3
findtime = 12h
bantime = 72h

This config work very nicely! :slight_smile:

1 Like

Please mark up your configurations as preformatted text, using the </> button.

Although I haven’t personally used fail2ban, the example match patterns appear to predate the Asterisk security log channel, which you should be using on any version of Asterisk that still has any level of support.

You should be following the guidance for Asterisk 10.x and above, in Asterisk - Fail2ban

I think the filter file you should have is fail2ban/asterisk.conf at master · fail2ban/fail2ban · GitHub However, you should aim to understand what they are actually doing.

what about your filter.d that you’r used !

I personally don’t use fail2ban, I watch manager security events and react to them, so I cannot provide any files related to fail2ban ; I hope someone can send you his files as an example.

il trying to configure fail2ban-iptables to secure my server asterisk 16.6.1
this is my jail.local


[DEFAULT]
ignoreip = 127.0.0.1/8
bantime = 600
findtime = 600
maxretry = 3
backend = auto
usedns = warn
destemail = rouroubella345@gmail.com
sendername = Fail2Ban
banaction = iptables-multiport
mta = sendmail
protocol = all
chain = INPUT
# action_ = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]

# action_mw = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]
          %(mta)s-whois[name=%(__name__)s, dest="%(destemail)s", protocol="%(protocol)s", chain="%(chain)s", sendername="%(sendername)s"]
          
          
# action_mwl = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]
           %(mta)s-whois-lines[name=%(__name__)s, dest="%(destemail)s", logpath=%(logpath)s, chain="%(chain)s", sendername="%(sendername)s"]
          
action = iptables-allports[name=ASTERISK, protocol=all]

[asterisk-iptables]
enabled     = true
port        = 5060, 5061
filter      = asterisk
logpath     = /var/log/asterisk/messages
maxretry    = 3

for filters i used /etc/fail2ban/filter.d/asterisk.conf

# Fail2Ban filter for asterisk authentication failures
#

[INCLUDES]

# Read common prefixes. If any customizations available -- read them from
# common.local
before = common.conf

[Definition]

_daemon = asterisk

__pid_re = (?:\s*\[\d+\])

iso8601 = \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+[+-]\d{4}

# All Asterisk log messages begin like this:
log_prefix= (?:NOTICE|SECURITY|WARNING)%(__pid_re)s:?(?:\[C-[\da-f]*\])?:? [^:]+:\d*(?:(?: in)? [^:]+:)?

prefregex = ^%(__prefix_line)s%(log_prefix)s <F-CONTENT>.+</F-CONTENT>$

failregex = ^Registration from '[^']*' failed for '<HOST>(:\d+)?' - (?:Wrong password|Username/auth name mismatch|No matching peer found|Not a local domain|Device does not match ACL|Peer is not supposed to register|ACL error \(permit/deny\)|Not a local domain)$
            ^Call from '[^']*' \(<HOST>:\d+\) to extension '[^']*' rejected because extension not found in context
            ^(?:Host )?<HOST> (?:failed (?:to authenticate\b|MD5 authentication\b)|tried to authenticate with nonexistent user\b)
            ^No registration for peer '[^']*' \(from <HOST>\)$
            ^hacking attempt detected '<HOST>'$
            ^SecurityEvent="(?:FailedACL|InvalidAccountID|ChallengeResponseFailed|InvalidPassword)"(?:(?:,(?!RemoteAddress=)\w+="[^"]*")*|.*?),RemoteAddress="IPV[46]/[^/"]+/<HOST>/\d+"(?:,(?!RemoteAddress=)\w+="[^"]*")*$
            ^"Rejecting unknown SIP connection from <HOST>(?::\d+)?"$
            ^Request (?:'[^']*' )?from '(?:[^']*|.*?)' failed for '<HOST>(?::\d+)?'\s\(callid: [^\)]*\) - (?:No matching endpoint found|Not match Endpoint(?: Contact)? ACL|(?:Failed|Error) to authenticate)\s*$

# FreePBX (todo: make optional in v.0.10):
#            ^(%(__prefix_line)s|\[\]\s*WARNING%(__pid_re)s:?(?:\[C-[\da-f]*\])? )[^:]+: Friendly Scanner from <HOST>$

ignoreregex =

datepattern = {^LN-BEG}

# Author: Xavier Devlamynck / Daniel Black
#
# General log format - main/logger.c:ast_log
# Address format - ast_sockaddr_stringify
#
# First regex: channels/chan_sip.c
#
# main/logger.c:ast_log_vsyslog - "in {functionname}:" only occurs in syslog

journalmatch = _SYSTEMD_UNIT=asterisk.service


[lt_journal]

# asterisk can log timestamp if logs into systemd-journal (optional part matching this timestamp, gh-2383):
__extra_timestamp = (?:\[[^\]]+\]\s+)?
__prefix_line = %(known/__prefix_line)s%(__extra_timestamp)s

the action that my asterisk service invokes is called iptables-multiport this is the associated file :

# Fail2Ban configuration file
#
# Author: Cyril Jaquier
# Modified by Yaroslav Halchenko for multiport banning
#

[INCLUDES]

before = iptables-common.conf

[Definition]

# Option:  actionstart
# Notes.:  command executed on demand at the first ban (or at the start of Fail2Ban if actionstart_on_demand is set to false).
# Values:  CMD
#
actionstart = <iptables> -N f2b-<name>
              <iptables> -A f2b-<name> -j <returntype>
              <iptables> -I <chain> -p <protocol> -m multiport --dports <port> -j f2b-<name>

# Option:  actionstop
# Notes.:  command executed at the stop of jail (or at the end of Fail2Ban)
# Values:  CMD
#
actionstop = <iptables> -D <chain> -p <protocol> -m multiport --dports <port> -j f2b-<name>
             <actionflush>
             <iptables> -X f2b-<name>

# Option:  actioncheck
# Notes.:  command executed once before each actionban command
# Values:  CMD
#
actioncheck = <iptables> -n -L <chain> | grep -q 'f2b-<name>[ \t]'

# Option:  actionban
# Notes.:  command executed when banning an IP. Take care that the
#          command is executed with Fail2Ban user rights.
# Tags:    See jail.conf(5) man page
# Values:  CMD
#
actionban = <iptables> -I f2b-<name> 1 -s <ip> -j <blocktype>

# Option:  actionunban
# Notes.:  command executed when unbanning an IP. Take care that the
#          command is executed with Fail2Ban user rights.
# Tags:    See jail.conf(5) man page
# Values:  CMD
#
actionunban = <iptables> -D f2b-<name> -s <ip> -j <blocktype>

[Init]
name = default
port = 5060, 5061
protocol = all
chain = INPUT

After making changes restart Fail2Ban to take effect.

[For SysVinit Systems]
# service fail2ban restart

[For systemd Systems]
# systemctl restart fail2ban.service

sudo fail2ban-client status

Status
|- Number of jail:	2
`- Jail list:	asterisk-iptables, sshd

fail2ban-client status asterisk-iptables

Status for the jail: asterisk-iptables
|- Filter
|  |- Currently failed:	0
|  |- Total failed:	0
|  `- File list:	/var/log/asterisk/messages
`- Actions
   |- Currently banned:	0
   |- Total banned:	0
   `- Banned IP list:

the problem is :
when i want to confirm whether Fail2Ban iptables rules are added into firewall using below command # iptables -L :

Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination  

thst’ mean fail2ban iptables rules does not added into firewall
when i want also to display the contents of the iptables table with the command #iptables -nL fail2ban-ASTERISK

# iptables -nL fail2ban-ASTERISK
iptables: No chain/target/match by that name.

that mean fail2ban iptables not added
any one helps me plizzzz ???

Continuation of Fail2ban on asterisk (and moderator has now combined it with that).

no i change some configuration files

probably yes
have you any idea about fail2ban configuration ??

This is my f2b filters for asterisk. Working great. You should be more dependent on asterisk security log and make sure you are enabling f2b compatible logging in asterisk and enable security logs as well.

Fail2Ban configuration file

Revision: 251

[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

Asterisk 1.8 uses Host:Port format which is reflected here

failregex = NOTICE.* .: Registration from '.’ failed for ‘:.’ - Wrong password
NOTICE.
.: Registration from '.’ failed for ‘:.’ - No matching peer found
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.
.: Registration from '.’ failed for ‘:.’ - ACL error (permit/deny)
NOTICE.
.: Registration from '.’ failed for ‘:.’ - Device does not match ACL
NOTICE.
.: Registration from '".".’ failed for ':.’ - No matching peer found
NOTICE.* .: Registration from '".".’ failed for ':.’ - Wrong password
NOTICE.* failed to authenticate as ‘.’$
NOTICE.
.: No registration for peer '.’ (from )
NOTICE.* .: Host failed MD5 authentication for '.’ (.)
NOTICE.
.: Failed to authenticate user .@.*
NOTICE.* .: failed to authenticate as '.
NOTICE.* .: tried to authenticate with nonexistent user '.
VERBOSE.SIP/-.Received incoming SIP connection from unknown peer
SECURITY.
SecurityEvent=“InvalidPassword”.RemoteAddress="IPV4/UDP//
SECURITY.
.
: SecurityEvent=“InvalidAccountID”.,Severity=“Error”,Service=“SIP”.,RemoteAddress=“IPV[46]/(UDP|TCP|TLS)//[0-9]+”
SECURITY.* .: SecurityEvent=“FailedACL”.,Severity=“Error”,Service=“SIP”.,RemoteAddress=“IPV[46]/(UDP|TCP|TLS)//[0-9]+”
SECURITY.
.: SecurityEvent=“InvalidPassword”.,Severity=“Error”,Service=“SIP”.,RemoteAddress=“IPV[46]/(UDP|TCP|TLS)//[0-9]+”
SECURITY.
.: SecurityEvent=“ChallengeResponseFailed”.,Severity=“Error”,Service=“SIP”.,RemoteAddress=“IPV[46]/(UDP|TCP|TLS)//[0-9]+”
SECURITY.
.: SecurityEvent=“ChallengeSent”.,Severity=“Informational”,Service=“SIP”.,AccountID="sip:.@0.0.0.0".*,RemoteAddress="IPV[46]/(UDP|TCP|TLS)//[0-9]+

Option: ignoreregex

Notes.: regex to ignore. If this regex matches, the line is ignored.

Values: TEXT

ignoreregex =

How can I make sure that I’m enabling f2b compatible logging in asterisk and enable security logs as well?!

give me the source you followed please

https://medium.com/@jamesemyn/intrusion-prevention-for-astersik-with-fail2ban-iptables-2c7e907bae4c

logger.conf section

This source only for the logger section
Or you fellow this source in all configuration?!
Your asterisk version ?!

Man you got to understand how fail2ban works. I use asterisk 16. what problem you are facing?

After editing jail.locla : I add [asterisk-iptables] jail
the problem is :
when i want to confirm whether Fail2Ban iptables rules are added into firewall using below command # iptables -L :

Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination  

thst’ mean fail2ban iptables rules does not added into firewall
when i want also to display the contents of the iptables table with the command #iptables -nL fail2ban-ASTERISK

# iptables -nL fail2ban-ASTERISK
iptables: No chain/target/match by that name.

that mean fail2ban iptables not added