The engine: how decisions are made
Package internal/engine. It is the only code that changes ipfence's state.
Every public method takes one lock, so two things never change state at once.
| File | Contents |
|---|---|
engine.go |
processing events, scoring, bans, IPv6 escalation, maintenance, reconciliation |
commands.go |
Enable, Disable, Ban, Unban, Allow, Unallow |
snapshot.go |
the read-only view used by status |
It is given its dependencies (database, firewall, settings, clock, list of local addresses, notifier), which is why tests can run it with a fake firewall and a clock they control.
Processing a batch
Process(batch) runs in one database transaction. Either everything below is
saved, or nothing, and the reader retries.
Diagram source
flowchart TD
S["expire due bans"] --> E["for each event"]
E --> V{"known detector, address, key?"}
V -- no --> c1["ignored.invalid"]
V -- yes --> O{"older than the window?"}
O -- yes --> c2["ignored.stale"]
O -- no --> F{"more than 5 min in the future?"}
F -- yes --> c3["ignored.future"]
F -- no --> P{"through a trusted proxy?"}
P -- yes --> c4["ignored.behind_proxy"]
P -- no --> X{"exempt?"}
X -- yes --> c5["ignored.REASON"]
X -- no --> B{"already banned, directly or by a range?"}
B -- yes --> c6["ignored.already_banned"]
B -- no --> R{"at or before the end of the last ban?"}
R -- yes --> c7["ignored.replayed"]
R -- no --> H{"record hit: new?"}
H -- no --> c8["ignored.duplicate"]
H -- yes --> SC["score = hits in window, this detector"]
SC --> T{"score >= threshold?"}
T -- no --> E
T -- yes --> BAN["autoBan, clear hits"]
BAN --> V6{"IPv6 and enforcing?"}
V6 -- yes --> ESC["consider prefix escalation"]After the commit: if anything changed and enforcement is on, sync updates the
firewall; then decisions are logged and passed to the notifier.
Why each check exists
| Check | Prevents |
|---|---|
| stale | replaying old logs causing bans |
| future | clock errors or odd timestamps counting forever |
| proxied | banning a shared proxy |
| exempt | lockout and self-harm |
| already banned | piling up offenses while blocked |
| replayed | the same history re-banning after rotation or a lost bookmark |
| duplicate | one record counted twice |
Exemptions
Exemption is checked in this order and the first match names the counter:
unusable_address(unspecified, multicast, broadcast)loopbacklocal_address(this host)allowlisted(settings file oripfence allow)trusted_proxyprivate_address(private or link-local, unlessauto_ban_private)
The list of this host's addresses is refreshed on each use; if the lookup fails, the last good list is kept and status reports the problem.
Scoring
Each event has weight 1. A score is the sum of stored hits for one address and one detector inside that detector's window. SSH failures and web probes are not added together.
| Detector | Default threshold | Default window |
|---|---|---|
ssh-auth |
5 | 10 minutes |
nginx-probe |
3 | 10 minutes |
caddy-probe |
3 | 10 minutes |
One SSH login attempt for a non-existent account produces two messages ("Invalid user" and "Failed password"), so it scores 2.
Choosing the ban
autoBan:
- Stop if 20,000 bans are active (
refused.capacity). nextOffense: previous count plus one, or 1 if the last ban ended more thanforget_after(30 days) ago.- Duration from the ladder:
15m,6h, then7dfor the third and later. - If
permanent_afteris set, the offense has reached it, and every hit in this score was high confidence: no expiry. - Save the ban; clear that address's hits; save the offense record with
LastEnd= the ban's planned end.
Observe mode
While enforcement is off the same steps run, but the ban is saved with
observed = true, never sent to the firewall, and the offense count is not
increased. Dry-run decisions therefore cannot make a later real ban longer.
Offense lifecycle
Diagram source
stateDiagram-v2
[*] --> Quiet
Quiet --> Counting: first failure
Counting --> Quiet: window passes
Counting --> Banned: threshold reached
Banned --> Served: expires, unbanned or allowed
Served --> Counting: new failure after the ban ended
Served --> Quiet: 30 days without a ban (count resets)IPv6 prefix escalation (off by default)
After a new automatic IPv6 ban, if enabled: count distinct single addresses in the
configured prefix that were automatically banned within ipv6.window and after
the prefix's own last ban ended. At the threshold, ban the prefix for the ladder
duration of the prefix's own offense count. Skipped, and counted as
escalation.skipped_trusted_overlap, if the prefix overlaps any allowlisted,
local or trusted proxy address. Never permanent.
Manual commands
Ban
Order of checks: duration at least 1 second (or permanent); enforcement on; then
checkManual:
| Refused when | Because |
|---|---|
wider than /8 (IPv4) or /32 (IPv6) |
a typo could cut off enormous numbers of users |
| overlaps loopback | would break the machine |
| overlaps unspecified, multicast or broadcast | meaningless and disruptive |
| equals one of this host's addresses | self-harm |
| entirely covered by an allowlist entry | the allowlist always wins |
Notes (allowed, but told): allowlisted or local addresses inside the range will
not be blocked; trusted proxies inside it will be; ranges can block bystanders.
An existing ban for the same prefix is ended as replaced.
The command line adds one more guard before the engine: the range containing your
current SSH client needs --force.
Unban
Ends the ban for exactly that prefix. If there is none, the error names any
range covering it or narrower bans inside it. The offense record's LastEnd
becomes now, so earlier events cannot immediately re-ban; --reset-history also
sets the count to zero.
Allow and Unallow
Allow saves the entry, ends every ban inside it (allowlisted), and keeps
wider bans, which the firewall's allow set then exempts it from. /0 is refused.
Unallow removes only entries added with allow; built-in, host and
settings-file entries are refused with the reason.
Enable and Disable
Enable: check the firewall is absent or ours; end observed bans as replaced
and mark their history as answered; set the flag; sync. If sync fails the flag
is turned back off, so enabling is all or nothing.
Disable: mark bans not enforced, turn the flag off, then remove the table. If
the table cannot be proven ours it stays, the command reports it, and enforcement
is still off.
Maintenance and reconciliation
Maintain runs at start and every 15 seconds:
- end due bans (
expired); - end bans now fully covered by the allowlist (a settings change);
- prune: history older than 90 days or beyond 10,000 rows; hits older than
24 hours or beyond 50,000; offense records past
forget_after(never those with an active ban), at most 100,000; - if enforcing,
sync.
sync builds the entire desired state from the database (desired): active,
real, unexpired bans (single addresses; ranges flattened) and the merged allow
list, calls firewall.Apply, and records success or the error on each ban.
Because it always sends the complete state, any earlier failure or external change
is repaired by the next run.
The snapshot
Snapshot reads the database, then asks the firewall what it holds now. If the
table is not owned, no ban is reported as in the firewall, whatever the database
last recorded. It also adds the Degraded messages.
Tests
engine_test.go uses a fake firewall and a controllable clock. It covers
thresholds, windows, clock skew, duplicates, escalation and decay, replay,
exemptions, observe mode, restarts, every manual command, firewall failure and
recovery, foreign tables, permanent bans, IPv6 policy, capacity and the allowlist
view.