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 readingRoughly 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.
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 --> netaddrOutside 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.
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 enforcedjournal.Source.follow(internal/ingest/journal/journal.go) reads lines from thejournalctlprocess, bounded to 128 KiB each.detect.DecodeJournal(internal/detect/journal.go) turns JSON into aJournalEntry.- The source's parser, built by
journal.SSHParser, callsdetect.SSHEvent, which callsdetect.ParseSSH(internal/detect/ssh.go). If the message is a failure,detect.TrustSSHverifies the sender. - The source collects events and, every 500 ms or 200 events, calls
ingest.Deliver, which callsengine.Processand retries until it succeeds. engine.Process(internal/engine/engine.go) opens one database transaction and, per event, applies the checks in order and may callautoBan. The reader's position is saved in the same transaction.- After the commit,
engine.syncbuilds the complete desired firewall content (desired) and callsfirewall.Apply(internal/firewall/nft_linux.go). Applyreads 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:
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:
cli.RunpicksrunBan(internal/cli/commands.go), which validates the address and duration and checks it is not your own SSH address.cli.dispatchsends acontrol.Requestto the socket.- If a daemon answers, its
control.Serverchecks who is asking and callscontrol.Execute. - If no daemon is running,
dispatchtakes the writer lock itself (daemon.Open) and calls the samecontrol.Execute. Executecallsengine.Ban, which applies the safety rules, writes the database, and callssync.- The answer comes back;
changeprints 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.