ARCAMUSA VOICE ENGINEERING

Fail2Ban for Asterisk: SIP Brute-Force Protection Without Locking Out Users

Use log-based banning as one security layer while accounting for shared NAT, false positives, observability and safe recovery.

Fail2Ban is a response layer, not authentication

Fail2Ban reads trusted logs, matches repeated failure events, and asks a firewall backend to block a source temporarily. It cannot replace SIP authentication, network allowlists, endpoint matching, strong credentials, rate controls or a restricted dialplan. A bad expression can ban legitimate shared-NAT users or allow an attacker to cause a denial of service, so test the exact log format before enabling enforcement.

Choose and verify the Asterisk log source

READ ONLYSENSITIVE OUTPUT
Log-source discoveryCOMMANDBASH
sudo asterisk -rx "logger show channels"
sudo journalctl -u asterisk --since '-10 minutes' --no-pager
sudo tail -n 100 /var/log/asterisk/security
sudo tail -n 100 /var/log/asterisk/messages

Use only a source that contains consistent authentication/security events and trustworthy source addresses. If Asterisk writes to journald, a file logpath may be wrong; if it writes security events to a dedicated file, make sure rotation preserves ownership and the jail follows the active file. Logs can contain telephone numbers, URIs and network details, so protect and redact them.

/etc/asterisk/logger.conf — illustrativeCONFIGINI
[logfiles]
security => security
messages => notice,warning,error

Build and test a narrow filter

CONFIG CHANGEWARNING / DO NOT COPY BLINDLY
/etc/fail2ban/filter.d/asterisk-auth.localWARNING / DO NOT COPY BLINDLYINI
[INCLUDES]
before = common.conf

[Definition]
failregex = ^%(__prefix_line)sSecurityEvent="InvalidPassword".*RemoteAddress="IPV[46]/[^/]+/<HOST>/[0-9]+".*$
ignoreregex =

The expression is an illustrative format that must match the installed Asterisk security-event output exactly. Anchor trusted structure and let <HOST> capture only the source-address field; never capture an address from attacker-controlled free text. A mismatch yields zero protection, while an overly broad expression creates false bans.

Offline filter testCOMMANDBASH
sudo fail2ban-regex /var/log/asterisk/security /etc/fail2ban/filter.d/asterisk-auth.local --print-all-matched
# Review every matched and missed line before enabling a jail.
Illustrative test summaryOUTPUTCONSOLE
Lines: 25 lines, 0 ignored, 3 matched, 22 missed
[processed in 0.01 sec]
# Illustrative; every matched line must be a true failure event.

Create a disabled-by-default jail plan

CONFIG CHANGEPRODUCTION CAUTION
/etc/fail2ban/jail.d/asterisk-auth.localCONFIGINI
[asterisk-auth-example]
enabled = false
filter = asterisk-auth
port = 5060,5061
protocol = all
logpath = /var/log/asterisk/security
backend = auto
findtime = 10m
maxretry = 8
bantime = 30m
# Select an action compatible with the host firewall backend.

findtime is the observation window, maxretry the failures required within it, and bantime the block duration. The values are examples, not universal safe thresholds. Baseline authorized retry behavior, scanners and traffic volume first. The action must match nftables, iptables or another approved backend; do not assume a packaged default fits the host.

WHAT THIS CONFIGURES

A generic disabled jail joining one filter, log and firewall action.

WHY IT EXISTS

Repeated validated failures can trigger a temporary network block.

EXPECTED STATE

Offline regex matches only real failures; jail starts without backend errors.

VERIFY WITH

`fail2ban-client status` and controlled non-production test events.

IF IT FAILS

Disable the jail and inspect log format/backend messages.

ROLLBACK

Set enabled=false, reload Fail2Ban and remove only rules owned by the jail.

SECURITY IMPACT

False positives can deny an entire NAT population; broad allowlists can create bypasses.

Verify status and firewall integration

READ ONLY
Validation sequenceCOMMANDBASH
sudo fail2ban-client -t
sudo systemctl reload fail2ban
sudo fail2ban-client status
sudo fail2ban-client status asterisk-auth-example
Illustrative healthy jail statusOUTPUTCONSOLE
Status for the jail: asterisk-auth-example
+- Filter
|  +- Currently failed: 0
|  +- Total failed: 3
|  +-- File list: /var/log/asterisk/security
+-- Actions
   +- Currently banned: 0
   +-- Banned IP list:

Configuration test must pass before reload. Status should name the intended log and action with no errors. Confirm the firewall contains only rules created by the selected backend. A zero banned count can be healthy; it is not proof the filter works, which is why controlled log fixtures and fail2ban-regex are required.

Controlled unban and incident handling

CONFIG CHANGEPRODUCTION CAUTION
Controlled unban of documentation addressCOMMANDBASH
sudo fail2ban-client set asterisk-auth-example unbanip 192.0.2.30
sudo fail2ban-client get asterisk-auth-example banip
sudo fail2ban-client status asterisk-auth-example

Confirm ownership and incident context before unbanning. Record why the address was blocked and whether the underlying endpoint credential or behavior was corrected. An unban is not remediation if the source remains compromised. Never copy a production banned list into a public ticket.

Shared NAT, allowlists and thresholds

False-positive controls
ConditionRiskControl
Many devices behind one NATFailures aggregate against one public address.Model normal retries and alert before enforcement.
Carrier/SBC address allowlisted broadlyCompromised trusted source bypasses banning.Use smallest approved ranges plus upstream controls.
Low maxretryNormal credential rollover can ban users.Use measured thresholds and staged rollout.
Long bantimeOperational mistake becomes extended outage.Start bounded; monitor and document unban.
DNS hostname resolves dynamicallyStatic firewall identity becomes stale.Use supported address governance; do not scrape DNS blindly.

Log rotation and operational monitoring

Rotation/backend checksCOMMANDBASH
sudo logrotate -d /etc/logrotate.d/asterisk
sudo fail2ban-client get asterisk-auth-example logpath
sudo journalctl -u fail2ban --since '-1 hour' --no-pager

After rotation, confirm Asterisk writes the new file and Fail2Ban follows it. Monitor filter failures, backend command errors, rapidly growing ban counts and recurrent authorized sources. Compression timing and inode replacement can affect tailing depending on backend. Test rotation in a controlled window rather than waiting for production midnight behavior.

Disable and roll back safely

CONFIG CHANGERELOAD REQUIRED

Set the custom jail to disabled, validate configuration, reload Fail2Ban, and confirm its jail and owned firewall rules disappear. Preserve the filter and test evidence for review rather than deleting diagnostic history. Do not flush the entire host firewall: that would remove unrelated security controls. Restore the prior .local files from backup if package defaults were overridden.

Related engineering resources

Stage enforcement and measure efficacy

Begin with offline fixtures that include true failures, legitimate authentication challenges, malformed input and attacker-controlled text. Next observe matches without a blocking action, compare source frequency to known endpoint populations, and obtain approval for thresholds. Enable on a limited surface during a staffed window with an out-of-band administrative path. Measure true-positive bans, false-positive bans, time to unban and backend errors.

A ban count is not a security outcome by itself. Review whether attempts moved to new addresses, whether credentials were exposed, and whether upstream rate controls or source allowlists should carry more of the load. Revisit expressions after Asterisk or logging upgrades because message formats can change. Fail closed only where the consequences and recovery path are explicitly understood.

Authoritative references

Implementation closure

Inputs required

Actual Asterisk security log path and sample lines, firewall backend, trusted administrative sources, shared-NAT risk, ban thresholds, and an out-of-band recovery path.

Change surface

Fail2Ban filter and jail files, logging configuration, and firewall rules created by the selected backend.

Apply and reload semantics

Run fail2ban-regex offline, enable the jail in a safe window, inspect jail status and firewall state, then test one authorized and one synthetic rejected event.

Healthy result

Only matching abusive events increment failures and produce the intended bounded ban while legitimate shared-NAT users remain reachable.

Failure path

Disable the jail before editing filters under live traffic; compare timestamps, backend state, regex matches, and ignored addresses.

Stop conditions

Stop if the log format is unverified, administrative access lacks an alternate path, or a shared address could cause broad customer lockout.

Definition of done

The filter matches intended events, false positives are tested, unban and disable procedures work, monitoring is assigned, and firewall state is documented.

Last substantively reviewed: 2026-09-13