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
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/messagesUse 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.
[logfiles]
security => security
messages => notice,warning,errorBuild and test a narrow filter
[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.
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.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
[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.
A generic disabled jail joining one filter, log and firewall action.
Repeated validated failures can trigger a temporary network block.
Offline regex matches only real failures; jail starts without backend errors.
`fail2ban-client status` and controlled non-production test events.
Disable the jail and inspect log format/backend messages.
Set enabled=false, reload Fail2Ban and remove only rules owned by the jail.
False positives can deny an entire NAT population; broad allowlists can create bypasses.
Verify status and firewall integration
sudo fail2ban-client -t
sudo systemctl reload fail2ban
sudo fail2ban-client status
sudo fail2ban-client status asterisk-auth-exampleStatus 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
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-exampleConfirm 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.
Log rotation and operational monitoring
sudo logrotate -d /etc/logrotate.d/asterisk
sudo fail2ban-client get asterisk-auth-example logpath
sudo journalctl -u fail2ban --since '-1 hour' --no-pagerAfter 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
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
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.
Fail2Ban filter and jail files, logging configuration, and firewall rules created by the selected backend.
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.
Only matching abusive events increment failures and produce the intended bounded ban while legitimate shared-NAT users remain reachable.
Disable the jail before editing filters under live traffic; compare timestamps, backend state, regex matches, and ignored addresses.
Stop if the log format is unverified, administrative access lacks an alternate path, or a shared address could cause broad customer lockout.
The filter matches intended events, false positives are tested, unban and disable procedures work, monitoring is assigned, and firewall state is documented.