Fail2ban integration and alternatives on FreeBSD AI-pedia

A comprehensive guide to implementing Fail2ban on FreeBSD, configuring packet filters such as PF and IPFW, and evaluating native lightweight alternatives like Sshguard and Blocklistd.

4,031 words · about 18 minutes to read · revised 21 November 2026 · written with gemini-3.8-flash-tiered

🤖 Written by Wren, the chat's AI, building on Wikipedia and on questions people asked in the chat. AI writing can be wrong or out of date: check anything that matters with a reliable source.

At a glance
Original authorCyril Jaquier
Initial release dateOctober 7, 2004
Software typeHost-based intrusion prevention system (HIPS)
Primary programming languagePython
Supported operating systemsPOSIX-compliant systems (FreeBSD, OpenBSD, Linux, macOS)
Default FreeBSD package namepy311-fail2ban (or security/py-fail2ban)
Supported FreeBSD firewallsPacket Filter (PF), IPFW, IPFilter
Native FreeBSD base alternativeblocklistd (formerly blacklistd)
Native FreeBSD port alternativesshguard (written in C)
Software licenseGNU General Public License version 2 (GPLv2)

Host-based intrusion prevention systems protect networked computers by monitoring authentication attempts and blocking network addresses that demonstrate malicious behavior. When internet-facing services such as Secure Shell (SSH), File Transfer Protocol (FTP), or Simple Mail Transfer Protocol (SMTP) are exposed to public networks, automated bots continually attempt unauthorized access using credential dictionaries and brute-force methods. While secure authentication mechanisms, such as cryptographic keys, prevent unauthorized entry, repeated authentication failures consume system bandwidth, fill system logs, and exhaust computational resources. Automated intrusion prevention daemons mitigate these attacks by inspecting system activity and dynamically inserting firewall rules to drop incoming traffic from offending addresses.

Fail2ban is one of the most widely used intrusion prevention frameworks for POSIX-compliant operating systems. Written in Python and released under the GNU General Public License version 2, Fail2ban reads system log files, parses failed authentication events using regular expressions, tracks failure frequencies across configurable time windows, and modifies firewall rules when defined thresholds are crossed. Although developed primarily with Linux systems in mind, Fail2ban is ported to FreeBSD and can control FreeBSD packet filtering subsystems, including Packet Filter (PF) and IPFW.

On FreeBSD, deploying Fail2ban requires addressing specific architectural characteristics, such as the location of configuration files, log rotation mechanisms, and firewall abstractions. Furthermore, the FreeBSD ecosystem offers native alternatives, notably Sshguard and the base system daemon blocklistd (formerly blacklistd). These alternatives are implemented in the C programming language and do not depend on an external Python runtime, presenting different trade-offs regarding resource consumption, architectural complexity, and configuration flexibility.

History and Core Concepts of Fail2ban

Fail2ban was created by Swiss developer Cyril Jaquier in 2004 to provide an automated, modular response to SSH brute-force attempts. At the time of its initial release on October 7, 2004, system administrators frequently wrote custom shell or Perl scripts to parse /var/log/auth.log or /var/log/secure and manually execute firewall commands. Fail2ban formalized this approach into an extensible client-server architecture composed of two primary programs: fail2ban-server, a multithreaded daemon that monitors logs and maintains state, and fail2ban-client, a command-line utility that communicates with the server via a UNIX domain socket to query status, load configuration files, and manage operational rules.

The operational framework of Fail2ban relies on several interconnected abstractions:

When an application logs a message, Fail2ban evaluates the text against the filter's regular expressions. If a pattern matches, an internal failure counter associated with that remote IP address increments. If the counter reaches maxretry within the window defined by findtime, Fail2ban marks the address as banned, resets the counter, and invokes the ban action. After the duration defined by bantime elapses, Fail2ban invokes the unban action, which removes the firewall restriction.

Disambiguating Terminology: Fail2ban Jails versus FreeBSD Jails

The term "jail" carries two distinct meanings within FreeBSD administration, and conflating them causes operational confusion:

When deploying Fail2ban on FreeBSD, an administrator may configure Fail2ban on the host operating system to monitor log files generated by various FreeBSD jails, or an administrator may install an independent instance of Fail2ban inside an individual FreeBSD jail. If running inside a FreeBSD jail, Fail2ban cannot directly modify host firewall rules unless the jail is configured with administrative network privileges (via vnet virtual network stacks) or communicates with the host system through an external management socket.

The FreeBSD Operational Environment

FreeBSD differs from Linux distributions in filesystem hierarchy, system logging, process supervision, and kernel packet filtering. Successfully integrating Fail2ban requires accommodating these differences.

Filesystem Hierarchy and Configuration Paths

FreeBSD maintains a strict separation between the base operating system and third-party software installed from the FreeBSD Ports and Packages Collection. Base system utilities reside in /bin, /sbin, /usr/bin, and /usr/sbin, with base configuration files stored in /etc. Third-party packages install binaries into /usr/local/bin and /usr/local/sbin, while their configuration files reside within /usr/local/etc.

Consequently, Fail2ban configuration files on FreeBSD are not located in /etc/fail2ban/ (as on Linux), but in /usr/local/etc/fail2ban/. System initialization parameters are managed through /etc/rc.conf rather than systemd service units.

Logging and Log Rotation

FreeBSD uses syslogd(8) for system logging and newsyslog(8) for scheduled log file rotation and compression. Default log destinations on FreeBSD differ slightly from traditional Linux layouts:

Log rotation managed by newsyslog periodically rotates log files, creating new empty files and compressing old ones. Fail2ban must detect when a log file is rotated so it does not continue reading from an unlinked inode. On FreeBSD, Fail2ban uses file polling mechanisms or Python filesystem monitoring modules to track file recreation and resume tracking at byte zero of the new file.

Installation and Configuration of Fail2ban on FreeBSD

Fail2ban is available in the FreeBSD Ports and Packages Collection under the category security/py-fail2ban. Binary packages are compiled against specific Python versions tracked by the package repository.

Installing via Binary Packages or Ports

To install the precompiled binary package using the FreeBSD package manager, run:

# pkg install py311-fail2ban

Alternatively, to compile Fail2ban from source using the Ports Collection, run:

# cd /usr/ports/security/py-fail2ban
# make install clean

The package installation creates the default directory structure under /usr/local/etc/fail2ban/ and installs the initialization script /usr/local/etc/rc.d/fail2ban.

Configuration Structure

Fail2ban uses hierarchical configuration files ending in .conf and .local. Configuration files ending in .conf represent default values provided by the package maintainers and upstream developers; these files should not be modified directly, as future software updates overwrite them. Local modifications, overrides, and site-specific settings are placed in matching files ending in .local, which take precedence over .conf files.

The key configuration files include:

To begin configuring Fail2ban on FreeBSD, create a jail.local file in /usr/local/etc/fail2ban/:

# cp /usr/local/etc/fail2ban/jail.conf /usr/local/etc/fail2ban/jail.local

Within jail.local, the [DEFAULT] section establishes global defaults. In this section, administrators designate the active packet filtering system and provide an IP ignore list to prevent administrative lockouts:

[DEFAULT]
ignoreip = 127.0.0.1/8 ::1 192.168.1.0/24
bantime  = 1h
findtime = 10m
maxretry = 5
banaction = pf
banaction_allports = pf

In the configuration above, ignoreip specifies addresses, address blocks, or hostnames that Fail2ban will never block. This prevents local administrative workstations or monitoring appliances from being inadvertently banned due to repeated connection errors.

Integrating Fail2ban with FreeBSD Firewalls

FreeBSD includes three distinct kernel-level packet filtering subsystems: Packet Filter (PF), IPFW (IP Firewall), and IPFilter (IPF). Fail2ban includes action definitions for all three, but PF and IPFW are the most common in modern FreeBSD deployments.

Packet Filter (PF) Integration

PF, originally developed by the OpenBSD project and ported to FreeBSD, provides high-performance stateful packet filtering. PF utilizes an internal data structure called a table to hold groups of IPv4 and IPv6 addresses. Tables are evaluated using radix tree lookups, allowing PF to query large collections of thousands of IP addresses with minimal processing overhead.

To integrate Fail2ban with PF, the administrator must configure a persistent table in /etc/pf.conf. A persistent table remains active in memory even when it contains no addresses, preventing PF from generating errors when empty.

Edit /etc/pf.conf to declare the table and insert the block rule:

# /etc/pf.conf

# Declare a persistent table for Fail2ban
table <fail2ban> persist

# Drop packets from banned addresses immediately
block quick proto tcp from <fail2ban> to any

# Standard ruleset continues below
pass in on em0 proto tcp to any port 22 keep state
pass out all keep state

The quick keyword in PF rule syntax halts further ruleset evaluation; if an incoming packet matches an address currently stored in the <fail2ban> table, the packet is immediately dropped, preventing processing by subsequent rules.

After updating /etc/pf.conf, check the ruleset syntax and reload the firewall configuration:

# pfctl -nf /etc/pf.conf
# pfctl -f /etc/pf.conf

In Fail2ban's /usr/local/etc/fail2ban/jail.local, set the action parameter to pf:

banaction = pf

The standard action file /usr/local/etc/fail2ban/action.d/pf.conf contains the commands executed by the daemon. When an address is banned, Fail2ban runs:

/sbin/pfctl -t <tablename> -T add <ip>

When the ban expires, Fail2ban executes:

/sbin/pfctl -t <tablename> -T delete <ip>

Administrators can inspect the current contents of the PF table from the command line using pfctl:

# pfctl -t fail2ban -T show

IPFW Integration

IPFW is the native stateful and rule-based packet filter developed within the FreeBSD project. IPFW also supports tables for efficient IP lookup. In modern FreeBSD versions, IPFW supports named tables as well as legacy numbered tables.

To integrate Fail2ban with IPFW, a rule referencing a table must be added to the IPFW ruleset. For example, add the following rule to your IPFW configuration script (such as /etc/rc.firewall or a custom ruleset):

# Add drop rule for the Fail2ban table
ipfw add 100 deny ip from table\(fail2ban\) to any

In /usr/local/etc/fail2ban/jail.local, set the firewall action parameter:

banaction = ipfw

Fail2ban uses /usr/local/etc/fail2ban/action.d/ipfw.conf to manipulate the IPFW table. When a ban occurs, it executes:

/sbin/ipfw table <tablename> add <ip>

When the ban expires, it executes:

/sbin/ipfw table <tablename> delete <ip>

To view the banned addresses stored within an IPFW table, run:

# ipfw table fail2ban list

Configuring Standard Jails on FreeBSD

Jails are enabled within /usr/local/etc/fail2ban/jail.local. Because FreeBSD uses standard paths that differ from Linux, log paths and backend handlers must be verified.

Protecting OpenSSH (sshd)

OpenSSH is included in the FreeBSD base system. Its connection and authentication logs are written to /var/log/auth.log. A basic OpenSSH jail configuration is defined as follows:

[sshd]
enabled  = true
port     = ssh
filter   = sshd
logpath  = /var/log/auth.log
maxretry = 3
findtime = 15m
bantime  = 24h

In this configuration, three failed SSH authentication attempts within 15 minutes result in an immediate 24-hour ban implemented through the configured banaction (such as PF or IPFW).

Protecting Mail and Web Services

Third-party servers installed from the Ports collection write logs to distinct locations. For example, the Dovecot IMAP/POP3 authentication service writes logs either to /var/log/maillog or to a dedicated file specified in its configuration.

[dovecot]
enabled  = true
port     = pop3,pop3s,imap,imaps,submission,sieve
filter   = dovecot
logpath  = /var/log/maillog
maxretry = 5

Similarly, an Nginx reverse proxy or web server installed from packages logs to /var/log/nginx/. An HTTP authentication jail can be declared to protect password-restricted web areas:

[nginx-http-auth]
enabled  = true
filter   = nginx-http-auth
port     = http,https
logpath  = /var/log/nginx/error.log
maxretry = 3

Service Management and Diagnostics

Once configuration files are in place, Fail2ban must be enabled in the FreeBSD system configuration database /etc/rc.conf.

Enabling and Starting the Service

To enable the daemon across system reboots, execute:

# sysrc fail2ban_enable="YES"

Start the service using the service(8) framework:

# service fail2ban start

The service startup status can be checked by querying the daemon process:

# service fail2ban status

Using fail2ban-client for Runtime Management

The fail2ban-client command interacts with the running server daemon. It can report global operational statistics, list active jails, and manage individual IP bans without restarting the service.

To retrieve a list of all active jails:

# fail2ban-client status

To retrieve detailed statistics for a specific jail, including currently banned IP addresses:

# fail2ban-client status sshd

To manually ban an IP address across a specific jail:

# fail2ban-client set sshd banip 198.51.100.42

To manually unban an address:

# fail2ban-client set sshd unbanip 198.51.100.42

To verify that regular expressions correctly match target logs without altering firewall states, use the fail2ban-regex diagnostic utility:

# fail2ban-regex /var/log/auth.log /usr/local/etc/fail2ban/filter.d/sshd.conf

The utility outputs the total lines evaluated, the number of matches, and the specific IP addresses extracted, allowing administrators to debug custom filters safely.

FreeBSD-Native Alternatives to Fail2ban

While Fail2ban provides extensive regular expression libraries and multi-application support, many FreeBSD administrators avoid it due to its reliance on Python and associated runtime libraries. On server installations prioritizing minimal resource consumption and base-system integration, two primary C-based alternatives are widely deployed: Sshguard and Blocklistd.

Sshguard

Sshguard is an open-source intrusion prevention daemon written in C. It was created to protect services against brute-force attacks while maintaining a low memory and CPU footprint. Originally designed solely for OpenSSH, Sshguard has expanded to parse log streams from multiple services, including Sendmail, Postfix, Dovecot, and OpenVPN.

Architectural Model of Sshguard

Unlike Fail2ban, which scans log files by periodically polling them from disk or tracking file descriptors via Python wrappers, Sshguard can receive log lines directly from syslogd(8) via an operating system pipe, or monitor log files directly. Because it is written in compiled C and uses a lightweight parsing engine (lex/yacc grammar definitions), its execution overhead is significantly lower than that of Fail2ban.

Sshguard maintains a cumulative scoring system for attacking addresses. Each detected failure adds an offense score to the attacking IP address. When the cumulative score exceeds a specified threshold, the address is banned. Sshguard features an escalating ban duration: repeated bans result in progressively longer blocking periods, culminating in permanent bans stored in a local state database.

Installation and Configuration on FreeBSD

Sshguard is available via FreeBSD packages:

# pkg install sshguard

Sshguard interfaces natively with PF by manipulating an address table (typically named <sshguard>). In /etc/pf.conf, the administrator defines the table and a matching block rule:

table <sshguard> persist
block in quick proto tcp from <sshguard> to any port 22

Sshguard configuration is managed through /usr/local/etc/sshguard.conf. A typical configuration for FreeBSD PF is configured as follows:

# /usr/local/etc/sshguard.conf
BACKEND="/usr/local/libexec/sshg-fw-pf"
FILES="/var/log/auth.log /var/log/maillog"
THRESHOLD=30
BLOCK_TIME=120
DETECTION_TIME=1800
BLACKLIST_FILE="100:/var/db/sshguard/blacklist.db"

Enable and start Sshguard via /etc/rc.conf:

# sysrc sshguard_enable="YES"
# service sshguard start

Blocklistd (Formerly Blacklistd)

blocklistd (originally named blacklistd before being renamed in FreeBSD 13 and 14 to reflect inclusive terminology) represents a fundamentally different architectural model for intrusion prevention. Developed initially by Christos Zoulas for NetBSD, it was subsequently imported directly into the FreeBSD base system.

The Passive Log Parsing vs. Direct Notification Paradigm

Fail2ban and Sshguard both employ passive log parsing. In this traditional model, an application daemon (such as sshd) writes an authentication failure string to a local log file via syslogd. An external monitoring daemon reads the log file, interprets the text using pattern-matching heuristics, and alters the firewall. This approach suffers from several inherent limitations:

blocklistd eliminates log parsing entirely through a proactive notification model. Instead of writing to a text file and waiting for a third-party daemon to read it, network daemons are modified to include native support for libblocklist. When an application encounters an authentication failure or protocol violation, it calls the libblocklist C API directly. The library sends a structured binary message across a local UNIX domain socket (/var/run/blocklistd.sock) to the blocklistd daemon.

The message conveys the network file descriptor, the failure status, and an optional message. blocklistd reads the connecting IP address directly from the socket file descriptor via the kernel, rendering address spoofing impossible. If the configured failure threshold is reached, blocklistd executes a firewall script to block the address immediately.

Configuring Blocklistd on FreeBSD

Because blocklistd is part of the FreeBSD base system, no packages need to be installed. Furthermore, the version of OpenSSH included in the FreeBSD base system is pre-compiled with libblocklist support.

To use blocklistd with PF, add an anchor and table to /etc/pf.conf:

# /etc/pf.conf
anchor "blocklistd/*"
table <blocklistd> persist
block in quick proto tcp from <blocklistd> to any

PF anchors allow sub-rulesets to be inserted dynamically by external processes. blocklistd uses the helper script /usr/libexec/blocklistd-helper to populate rules within this anchor or manipulate the PF table.

Configuration of rules is managed in /etc/blocklistd.conf. Each line defines service interfaces, ports, protocols, failure thresholds, and ban durations:

# /etc/blocklistd.conf
# [target]     type  proto  owner  support  nfail  duration
[local]
ssh            stream  tcp    *      *        3      24h
ftp            stream  tcp    *      *        3      24h

# Global defaults
*              *       *      *      *        3      60m

In this configuration, when OpenSSH alerts blocklistd of three failed attempts from a single source, blocklistd blocks the address for 24 hours.

To enable blocklistd and configure OpenSSH to notify it, edit /etc/rc.conf and /etc/ssh/sshd_config:

# Enable the blocklistd daemon in /etc/rc.conf
sysrc blocklistd_enable="YES"
sysrc blocklistd_flags="-r"

In /etc/ssh/sshd_config, ensure the integration is active:

UseBlocklist yes

(Note: In older FreeBSD releases, this directive is spelled UseBlacklist yes).

Start the daemon and reload the SSH service:

# service blocklistd start
# service sshd reload

The state of blocklistd can be queried using blocklistctl:

# blocklistctl dump -a

This command outputs the tracked IP addresses, the remaining ban duration, and the failure count for each tracked endpoint.

Comparative Analysis of Solutions

Choosing between Fail2ban, Sshguard, and Blocklistd requires balancing configuration flexibility, runtime overhead, and service support. The following table highlights the architectural differences between the three tools on FreeBSD:

Feature / Attribute Fail2ban Sshguard Blocklistd
Implementation Language Python C C
Operating System Presence Ports / Packages Ports / Packages FreeBSD Base System
Detection Mechanism Passive log parsing (regex) Log parsing (lex/yacc grammar) Direct IPC socket notifications
External Dependencies Python runtime, py-setuptools None (libc only) None (libc only)
Memory Footprint Moderate (~30MB–80MB) Low (~2MB–5MB) Minimal (<2MB)
Application Support Extensive (hundreds of pre-built filters) Moderate (SSH, mail, common VPNs) Requires libblocklist patch
Firewall Support (FreeBSD) PF, IPFW, IPFilter PF, IPFW, IPFilter PF, IPFW
Log Injection Resistance Low (requires strict regex) Moderate Immune (kernel socket inspection)
Configuration Complexity Moderate (hierarchical INI) Low (single configuration file) Low (single configuration file)

Evaluation of Trade-offs

The selection of an intrusion prevention tool depends largely on the operational requirements of the server environment:

Fail2ban is advantageous in complex application hosting environments. When an administrator manages customized software, web applications with specific authentication failure patterns, or diverse database systems, Fail2ban's regular expression framework allows arbitrary log parsing without modifying application source code. Organizations that manage mixed Linux and FreeBSD fleets often standardize on Fail2ban to maintain uniform configuration syntax and deployment automation scripts (e.g., Ansible, Puppet) across all platforms.

Sshguard offers a balanced compromise for standard server deployments. It eliminates the memory and dependency footprint of a Python runtime while remaining capable of parsing standard text logs from OpenSSH, Postfix, and Dovecot. Because it runs as a lightweight compiled binary, it is well suited for resource-constrained environments such as embedded systems, low-memory virtual private servers (VPS), or high-throughput firewalls where minimizing system overhead is paramount.

Blocklistd represents the most architecturally robust approach to brute-force prevention, but it is constrained by software ecosystem adoption. For servers primarily exposing base-system utilities—specifically OpenSSH and FTP—blocklistd is often preferred because it requires no ports or packages, consumes negligible resources, and eliminates log parsing vulnerabilities entirely. However, third-party software packages (such as Nginx, Apache, or custom web APIs) rarely include libblocklist instrumentation out of the box, limiting blocklistd's utility in general-purpose web application hosting unless administrators maintain custom source patches.

Operational Considerations and Edge Cases

Deploying automated intrusion prevention systems requires attention to operational details to prevent unintended lockouts, system degradation, or tracking failures.

Handling Log File Truncation and Rotation

Under FreeBSD, newsyslog(8) executes periodically via cron(8) (typically on the hour). When log files cross defined size or time thresholds, newsyslog archives the current file and creates a new one, sending a hangup signal (SIGHUP) to syslogd to reopen the log file descriptors.

When running Fail2ban, administrators must ensure that the backend file monitor reliably detects these events. Fail2ban supports multiple backends for tracking log growth, configured via the backend setting in jail.conf:

If Fail2ban stops detecting failed login events after an hourly log rotation, setting backend = polling in jail.local resolves the synchronization failure.

Mitigating Regular Expression Denial of Service (ReDoS)

Because Fail2ban uses regular expressions to parse untrusted text strings supplied by remote clients across the network, poorly designed regular expressions can lead to catastrophic backtracking. Catastrophic backtracking occurs when a non-deterministic finite automaton (NFA) regex engine attempts to match an ambiguous, nested pattern against an input designed to maximize backtracking paths. This condition spikes CPU utilization to 100%, causing the monitoring process to freeze and rendering the server vulnerable to unmonitored attacks.

When authoring custom filters on FreeBSD, administrators should:

Whitelisting and Emergency Recovery

Automated IP banning mechanisms risk blocking legitimate administrators who inadvertently enter incorrect passwords or run automated synchronization scripts with expired credentials. To mitigate this risk:

See also

Sources

Questions people asked

How does fail2ban work on FreeBSD, including installation and firewall integration? — answered 21 November 2026

It works fine on FreeBSD—it is right in ports and pkg as py-fail2ban (usually py311-fail2ban or whatever python version pkg is tracking).

The main trick is just tying it into your firewall backend. If you are using pf, you drop a persistent table into pf.conf (like table <fail2ban> persist) with a block rule, and set banaction = pf in /usr/local/etc/fail2ban/jail.local. It supports ipfw as well if that is what you run.

A lot of FreeBSD folks swear by sshguard instead, or the base blocklistd/blacklistd, just because they are written in C and do not drag Python into the security stack. But if you already know fail2ban syntax and regexes, fail2ban does the job.