ipfence home page local-first intrusion prevention for Linux

Manual pages

The firewall code

Package internal/firewall. It owns one nftables table and nothing else.

File Contents Needs Linux
firewall.go types, states, the Backend interface no
model.go what the table should be, and Classify no
plan.go what elements to add or remove no
nft_linux.go reading and writing the kernel yes
fwtest/fake.go a pretend firewall for tests no

Separating the decisions (model, plan) from the kernel calls means the rules about ownership can be tested without a kernel, and the kernel tests focus on behaviour.

The interface

Go

type Backend interface {
    Inspect(ctx) (Report, error)            // never changes anything
    Apply(ctx, Desired) (Report, error)     // create or repair, make sets match
    Remove(ctx) (Report, error)             // delete the table if provably ipfence's
}

Expected structure

NewSpec builds it from the install identity, the priority and whether a forward chain is wanted:

Object Definition
owner_v1_<install id> a chain with no hook and no rules: the ownership marker
ban4, ban6 address sets with timeouts
ban4net, ban6net interval sets with timeouts
allow4, allow6 interval sets
input filter chain, input hook, configured priority, policy accept
forward the same on the forward hook, only with docker.mode = "forward"

Four rules per chain. Their canonical form:

Plain text

nfproto=4 iifname!=lo saddr@ban4 saddr!@allow4 counter drop

Each rule also carries a comment, ipfence:v1:<chain>:<set>.

Classification

noyesnoyesnoyesyesnotable inet ipfence?absentexactly one marker chain,unmodified; only known chains,sets and rules; correct types; noother objects?foreignmarker names this install?other-installanything missing, dormant,unwanted or at another priority?driftedowned
Diagram source
flowchart TD
    A{"table inet ipfence?"} -- no --> ABS["absent"]
    A -- yes --> B{"exactly one marker chain, unmodified; only known chains, sets and rules; correct types; no other objects?"}
    B -- no --> FOR["foreign"]
    B -- yes --> C{"marker names this install?"}
    C -- no --> OTH["other-install"]
    C -- yes --> D{"anything missing, dormant, unwanted or at another priority?"}
    D -- yes --> DR["drifted"]
    D -- no --> OWN["owned"]
State Apply Remove
absent creates nothing to do
owned updates sets removes
drifted rebuilds chains, updates sets removes
other-install refused removes
foreign refused refused
unavailable refused refused

How a rule is judged "ours": the kernel's expressions are converted back to the canonical form by signature. Any unexpected expression, register or offset yields unknown. A rule with our comment but a different body is therefore foreign.

Applying

kernelbackendenginekernelbackendenginealt[notwritable]Apply(desired)list table, chains,rules, sets, objectsClassifyErrUnsafe, nothingchangedread set elementsplan changesone batch (all ornothing)read backreport
Diagram source
sequenceDiagram
    participant E as engine
    participant B as backend
    participant K as kernel
    E->>B: Apply(desired)
    B->>K: list table, chains, rules, sets, objects
    B->>B: Classify
    alt not writable
        B-->>E: ErrUnsafe, nothing changed
    else
        B->>K: read set elements
        B->>B: plan changes
        B->>K: one batch (all or nothing)
        B->>K: read back
        B-->>E: report
    end
  • A new table uses create-exclusive, so a table appearing in between makes the batch fail instead of being adopted.
  • A drifted table is repaired in a single batch: missing sets added, chains flushed, deleted and recreated. Elements in kept sets survive. There is no moment without rules.
  • If the batch fails, it is tried once more from a fresh read (an entry may have expired in between).

Updating the sets

Single addresses

PlanHosts compares wanted and present entries. Expiry differences under 5 seconds are ignored, so reconciliation does not rewrite everything. Changes are queued as "add, delete, add", which cannot fail just because an entry expired a moment ago.

A remaining time under 1 second is treated as expired: the kernel reads a zero timeout as "never expires".

Ranges

Overlapping bans are flattened into non-overlapping ranges, each with the latest expiry covering it:

Plain text

10.0.0.0/24  for 1 h        10.0.0.0   - 10.0.0.63    2 h
10.0.0.0/26  for 2 h   ->   10.0.0.64  - 10.0.0.255   1 h

If a set's ranges differ from the wanted ones, it is emptied and refilled in the same batch. An interval is stored as a start element and an "end" element at the first address after it.

Two kernel behaviours found by testing

Problem Cause Fix
network bans failed with "invalid argument" this kernel rejects a timeout on an interval end element only start elements carry a timeout
removing thousands of bans failed with "message too long" a whole batch is one netlink message, limited by the socket buffer large send and receive buffers (16 MiB, 8 MiB)

Element messages are also split into groups of 256, because one netlink attribute is limited to 64 KiB. All groups remain in the same batch.

Limits

MaxEntries = 20,000 active bans, exercised by a kernel test that adds, rechecks, re-times and removes that many.

Kernel tests

nft_integration_linux_test.go builds three network namespaces (client, server, backend) with virtual cables, runs the code only inside them, and checks real connectivity: bans and unbans, ranges and allow precedence, kernel expiry, permanent entries, loopback, persistence, other tables untouched, foreign and modified tables refused, other installs, drift repair, 20,000 entries, and the forward chain.

They need root and run only with IPFENCE_INTEGRATION=1.