Architecture
Data flow
Diagram source
flowchart LR
J[journald] -->|journalctl JSON| R[readers]
F[access logs] -->|tailer| R
R -->|events + position| E[engine]
CLI[ipfence CLI] -->|root-only Unix socket| E
E <-->|one transaction| DB[(SQLite)]
E -->|desired state| FW[firewall]
FW -->|netlink batch| K[[nftables: inet ipfence]]
E -.optional.-> H[your hook]- A reader parses a trusted record into an event: service, kind, source address, time and a key that identifies the record. No user name or raw line goes further.
- The engine checks the time window, the exemptions and whether the address is already banned, stores a scoring hit, and bans when the window's score reaches the threshold.
- Hits, bans, offense counts and the reader's position are committed in one transaction. A record is therefore counted once, even across a crash.
- The firewall package makes the kernel's sets match the database in one netlink batch.
- status reads the database and then the kernel, and says when they differ.
Source layout
| Path | Responsibility |
|---|---|
cmd/ipfence |
entry point |
internal/product |
every name that a rename would change |
internal/config |
override-only TOML, defaults, validation |
internal/netaddr |
address parsing, classification, range arithmetic |
internal/detect |
OpenSSH, journal, Nginx and Caddy parsers, probe list |
internal/ingest, .../journal, .../file |
readers, cursors, tailing |
internal/engine |
policy, scoring, commands, snapshot |
internal/store |
SQLite schema, migrations, transactions |
internal/firewall |
ownership, expected structure, reconciliation |
internal/discovery |
local service, interface and Docker discovery |
internal/daemon |
lock, lifecycle, reader supervision |
internal/control |
request format, Unix socket |
internal/cli, internal/status |
commands and reports |
internal/safepath, internal/hook |
file safety, optional hook |
One writer
The database and the firewall are changed by exactly one process at a time.
- The daemon holds an exclusive
flockon/run/ipfence/writer.lockfor its whole life and serves commands on/run/ipfence/control.sock(mode 0600, and the kernel-reported peer user must be root or the daemon's user). - The protocol is one JSON request and one JSON response per connection, with unknown fields rejected and sizes and time bounded.
- If no daemon is listening, a command takes the same lock and runs the same
code in its own process. That is why
unbanworks when the daemon is down. - If the lock is held but the socket does not answer, the command fails (exit 4) instead of writing around it.
- Inside the process the engine serializes every mutation.
State and reconciliation
SQLite is the intended state; the kernel is made to match it.
- A change commits to the database first, then to the firewall. If the firewall step fails, the ban is shown as not enforced with the error, and reconciliation retries.
- Reconciliation runs at daemon start, after every change, and every 15 seconds. It expires bans, ends bans that the allowlist now covers, and repairs a missing or altered table.
- Timed bans are also timed in the kernel, so they expire with no daemon running.
- After a reboot the kernel is empty; the daemon restores unexpired bans at start.
- Stopping the daemon changes nothing in the kernel. Only
ipfence disableremoves the table.
The database (schema version in the schema_version table) holds the install
identity, bans and history, offense counts, recent scoring hits, the command
allowlist, reader positions and counters. Limits: history 90 days or 10,000
rows, 50,000 hits, 100,000 offense records, 20,000 active bans. A file that is
corrupt, newer, not SQLite or not ipfence's is refused and left untouched.
The nftables table
Plain text
table inet ipfence
chain owner_v1_<install id> empty; the ownership marker
set ban4, ban6 single addresses, with timeouts
set ban4net, ban6net ranges, with timeouts
set allow4, allow6 ranges, never dropped
chain input (filter, hook input, priority -10, policy accept)
chain forward (only with docker.mode = "forward")Each chain holds four rules of this shape:
Plain text
iifname != "lo" ip saddr @ban4 ip saddr != @allow4 counter drop comment "ipfence:v1:input:ban4"- Deny only. No rule accepts. A drop in any chain is final, while an accept in one chain does not bind later chains, so ipfence cannot open anything.
- Allowlist precedence is part of every rule, so it also holds when a network ban covers an allowed address.
- Loopback is excluded twice: by the interface test and by the allow sets.
- Overlapping network bans are split into non-overlapping ranges, each with the latest expiry that covers it.
Ownership
A table name proves nothing. Before any change the table is read and classified:
| State | Meaning | Changed by ipfence? |
|---|---|---|
| absent | no such table | created with create-exclusive semantics |
| owned | marker matches this install; every object as expected | yes |
| drifted | ours, but something is missing, dormant or at another priority | repaired in one batch |
| foreign | any unknown chain, set, rule or object, wrong type or policy, or no marker | never |
| other-install | a well-formed ipfence table with another install's marker | only removed by disable |
Foreign beats every other state: if you add a rule inside inet ipfence,
ipfence stops touching the table and says so until you remove the rule. No code
path flushes the ruleset.
Another process holding root can still change the table between the read and the write; ipfence does not defend against that.
Hook priority
The default is -10: after connection tracking (-200) and destination NAT (-100),
before the usual filter chains (0) used by ufw, Docker's iptables rules and
firewalld (+10). Because ipfence only drops, enforcement does not depend on
winning a tie; the order only decides what other chains get to see. No priority
is right for every configuration, and equal priorities have no defined order, so
the value is configurable.
Choices and their costs
| Choice | Why | Cost |
|---|---|---|
journalctl subprocess |
static CGO-free binary, no libsystemd | needs the binary at runtime |
| Polling tailer woken by inotify | handles rename and truncation without a dependency | copytruncate loses lines |
| Whole-set reconciliation | one code path, self-repairing | reads every element each pass (tested to 20,000) |
| Interval sets replaced as a whole | atomic and simple | network bans are rewritten when any of them changes |
| Synchronous readers | the log is the queue; nothing is dropped for backpressure | a slow database slows reading |