ipfence home page local-first intrusion prevention for Linux

Manual pages

Code tour

This is your map of the codebase: what is where, how a log line travels through it, and where to go to change something. It assumes you have read What ipfence does. Go knowledge helps but is not required to follow the shape.

The repository

Plain text

cmd/ipfence/            the program's entry point (13 lines: it calls the CLI)
internal/               all the real code; "internal" means only this module can import it
  product/              every name that a rename would change
  netaddr/              IP addresses and ranges
  config/               the settings file
  detect/               turning log records into events
  ingest/               what the log readers share
    journal/            reading the systemd journal
    file/               following log files
  engine/               the decisions
  store/                the database
  firewall/             nftables
    fwtest/             a pretend firewall used by tests
  discovery/            finding services on the machine
  daemon/               the long-running program
  control/              commands travelling to the daemon
  cli/                  what you type and what is printed
  status/               the shape of the status report
  safepath/             refusing dangerous files and directories
  hook/                 running your optional program
systemd/                the service definition
scripts/build.sh        builds the release binaries
test/e2e/               scripts that test the whole thing in a throwaway machine
docs/                   what you are reading

Roughly 9,800 lines of program code and 5,300 lines of tests.

Dependency direction

Arrows mean "uses". Lower boxes know nothing about higher ones, which is why they can be tested on their own.

clidaemoncontrolenginediscoveryingesthookdetectfirewallstoreconfigsafepathnetaddr
Diagram source
flowchart TD
    cli --> daemon
    cli --> control
    daemon --> engine
    daemon --> discovery
    daemon --> ingest
    daemon --> control
    daemon --> hook
    control --> engine
    ingest --> engine
    ingest --> detect
    discovery --> detect
    discovery --> firewall
    engine --> store
    engine --> firewall
    engine --> detect
    engine --> config
    config --> detect
    store --> safepath
    detect --> netaddr
    firewall --> netaddr
    engine --> netaddr

Outside libraries

Library Used for
github.com/google/nftables speaking netlink to the firewall
modernc.org/sqlite SQLite written in Go, so no C compiler is needed
github.com/BurntSushi/toml reading the settings file
github.com/mdlayher/netlink, golang.org/x/sys low-level Linux calls

Why some files end in _linux.go and _other.go

The program only runs on Linux. The _other.go files are stand-ins so the platform-independent parts can be built and tested on Windows or macOS during development.

A log line's journey

The most useful thing to understand. Follow one failed SSH login.

firewallstoreengine.Proce-ssdetectjournal.Sourc-ejournalctlfirewallstoreengine.Proce-ssdetectjournal.Sourc-ejournalctlwindow,exemption,duplicates, score,banone JSON lineDecodeJournalSSHParser: ParseSSHthen TrustSSHEventBatch of events and cursorone transactionApply desired statereportmark enforced
Diagram source
sequenceDiagram
    participant JC as journalctl
    participant JS as journal.Source
    participant P as detect
    participant EN as engine.Process
    participant ST as store
    participant FW as firewall
    JC->>JS: one JSON line
    JS->>P: DecodeJournal
    JS->>P: SSHParser: ParseSSH then TrustSSH
    P-->>JS: Event
    JS->>EN: Batch of events and cursor
    EN->>ST: one transaction
    Note over EN,ST: window, exemption, duplicates, score, ban
    EN->>FW: Apply desired state
    FW-->>EN: report
    EN->>ST: mark enforced
  1. journal.Source.follow (internal/ingest/journal/journal.go) reads lines from the journalctl process, bounded to 128 KiB each.
  2. detect.DecodeJournal (internal/detect/journal.go) turns JSON into a JournalEntry.
  3. The source's parser, built by journal.SSHParser, calls detect.SSHEvent, which calls detect.ParseSSH (internal/detect/ssh.go). If the message is a failure, detect.TrustSSH verifies the sender.
  4. The source collects events and, every 500 ms or 200 events, calls ingest.Deliver, which calls engine.Process and retries until it succeeds.
  5. engine.Process (internal/engine/engine.go) opens one database transaction and, per event, applies the checks in order and may call autoBan. The reader's position is saved in the same transaction.
  6. After the commit, engine.sync builds the complete desired firewall content (desired) and calls firewall.Apply (internal/firewall/nft_linux.go).
  7. Apply reads the table, Classifys it, queues changes (stage), and commits them in one netlink batch.

For web logs, steps 1 to 4 are file.Source.Run, file.Tailer.Poll, NginxFormat.Parse or ParseCaddy, and detect.WebEvent with detect.MatchProbe.

Startup

ipfence daemon runs cli.runDaemon, which loads the settings and calls daemon.Run:

every 15 severy 60 sstop signaldaemon.Open: private directories,writer lock, database, firewall,enginecontrol.Listen: create thecommand socketengine.Maintain: restore bans,expire old onesdiscover: run discovery, startreaders for ready servicesserve commands; run the hookworkertell systemd READYloopMaintaindiscover againstop readers, close socket,release lock; the firewall isuntouched
Diagram source
flowchart TD
    A["daemon.Open: private directories, writer lock, database, firewall, engine"] --> B["control.Listen: create the command socket"]
    B --> C["engine.Maintain: restore bans, expire old ones"]
    C --> D["discover: run discovery, start readers for ready services"]
    D --> E["serve commands; run the hook worker"]
    E --> F["tell systemd READY"]
    F --> G{"loop"}
    G -->|every 15 s| H["Maintain"]
    G -->|every 60 s| D2["discover again"]
    G -->|stop signal| I["stop readers, close socket, release lock; the firewall is untouched"]

A command

sudo ipfence ban 203.0.113.9 --for 1h:

  1. cli.Run picks runBan (internal/cli/commands.go), which validates the address and duration and checks it is not your own SSH address.
  2. cli.dispatch sends a control.Request to the socket.
  3. If a daemon answers, its control.Server checks who is asking and calls control.Execute.
  4. If no daemon is running, dispatch takes the writer lock itself (daemon.Open) and calls the same control.Execute.
  5. Execute calls engine.Ban, which applies the safety rules, writes the database, and calls sync.
  6. The answer comes back; change prints it and chooses the exit code.

Where to change things

To change... Edit Also
a product or file name internal/product/product.go go.mod, unit, scripts, docs
which SSH messages count internal/detect/ssh.go real fixtures in testdata, tests
which web requests are probes internal/detect/probes.go false-positive tests
a new Nginx format preset nginxPresets in internal/detect/web.go tests
ban lengths or thresholds (defaults) config.Default docs/configuration.md
a new setting structs and validate in internal/config/config.go tests, reference
who is exempt engine.Exemption engine tests
how bans are decided engine.Process, autoBan engine tests
the firewall rules internal/firewall/model.go and nft_linux.go model tests and kernel tests
the database add a migration in store.go (never edit an old one) store tests
what status prints internal/cli/render.go, internal/status CLI tests, bump SchemaVersion if meaning changes
a new command commands map in internal/cli/cli.go usage text, tests, reference
the service sandbox systemd/ipfence.service the end-to-end script

After any change, follow Testing.

Deeper

  1. Detection
  2. The engine
  3. Readers
  4. Storage
  5. Firewall
  6. Discovery
  7. Daemon, commands and reports
  8. Safety mechanisms
  9. Testing
  10. Design decisions