How iximiuz/pathviz follows a packet through netfilter using NFLOG, Go callbacks, and a fingerprint designed to survive ordinary NAT.
· 9 min read

How PathViz Tracks a Packet Across Netfilter Hooks in Go


Capturing a packet in netfilter is easy. Matching the event from PREROUTING with the one from POSTROUTING is harder because NAT may have rewritten the addresses and ports you would normally use as an identity.

iximiuz/pathviz tackles that problem with a compact fingerprint built from fields that ordinary forwarding and address or port translation leave alone. The design is deliberately pragmatic: PathViz is a learning and demonstration tool, not a collision-proof packet-capture system.

What PathViz actually installs

The package documentation describes the basic arrangement: a dedicated nftables table places probe chains around the classic iptables stages, sends matching packets to an NFLOG group, and reconstructs their paths for the web UI.

The data source is NFLOG, the netfilter logging target that ships matched packets to userspace over a netlink socket. probe.go names the table pathviz and adds an exit probe at priority 500 to every hook:

// exitPriority is higher than every classic iptables/nftables priority
// (srcnat is 100, SELinux last is 225, conntrack helpers are 300).
exitPriority = 500

A packet that reaches an exit probe survived the whole hook. Those end-of-hook chains let PathViz tell “dropped somewhere in filter” apart from “made it all the way through”.

Reading NFLOG with a Go callback

capture.go binds to the group with florianl/go-nflog v2.3.0:

nf, err := nflog.Open(&nflog.Config{
	Group:    uint16(group),
	Copymode: nflog.CopyPacket,
	Bufsize:  uint32(copyRange),
	// Deliver every packet right away instead of batching.
	QThresh: 1,
	// Per-group sequence numbers reveal lost events.
	Flags: nflog.FlagSeq,
})

QThresh: 1 asks NFLOG to flush after one queued packet rather than waiting for a larger batch. FlagSeq asks the kernel to attach per-group sequence numbers, allowing PathViz to spot gaps between delivered events.

Bufsize comes from one of two constants. headerRange = 256 is enough, per its comment, to hold “the headers and the fingerprinted payload prefix with a wide margin”, and is used when the packet view is off. packetRange = 2048 holds a full packet at a usual 1500-byte MTU, so the UI can render payloads like DHCP options or a TLS Client Hello. Copying two kilobytes per packet into userspace costs something, which is why main.go exposes --no-packet-view to fall back to 256.

Right after opening the socket, the code tries to enlarge the netlink read buffer. Failure is logged as a warning rather than aborting capture:

if err := nf.Con.SetReadBuffer(8 << 20); err != nil {
	log.Printf("warning: cannot enlarge the netlink buffer: %v", err)
}

Then two callbacks are registered with RegisterWithErrorFunc(ctx, c.onPacket, c.onError). Cancelling the context interrupts the library’s receive loop, while the packet and error callbacks decide whether an individual event should stop it. For a refresher on context in shutdown paths, see What is Context in Go?.

Detecting incomplete traces

PathViz watches for capture problems in two places.

The error callback separates shutdown noise from real trouble:

func (c *Capture) onError(err error) int {
	if c.ctx.Err() != nil || errors.Is(err, net.ErrClosed) {
		return 1 // shutting down
	}
	// ENOBUFS and friends mean the kernel dropped events for this socket.
	now := time.Now()
	c.mu.Lock()
	c.lost++
	c.mu.Unlock()
	c.tracker.Lost(now)
	log.Printf("capture error: %v", err)
	return 0
}

Return 1 and the handler stops; return 0 and it keeps going. The errors.Is(err, net.ErrClosed) check earns its place: closing the socket on shutdown pops out as a read error, and logging that as a capture failure would be noise.

On the packet side, sequence numbers reveal discontinuities between events that did arrive:

if a.Seq != nil {
	c.mu.Lock()
	gap := c.haveSeq && *a.Seq != c.lastSeq+1
	if gap {
		c.lost += uint64(*a.Seq - c.lastSeq - 1)
	}
	c.lastSeq, c.haveSeq = *a.Seq, true
	c.mu.Unlock()
	if gap {
		c.tracker.Lost(now)
	}
}

The mutex is unlocked before c.tracker.Lost(now) runs. Both callbacks avoid calling the tracker while holding the capture lock, which keeps lock ownership local to Capture.

The resulting lost value is a health indicator, not a guaranteed count of missing packets. A sequence gap contributes its apparent size, while a socket error contributes one because the callback cannot know how many events the kernel dropped. The same incident can also surface through both mechanisms.

Giving retained packet bytes their own storage

The callback gets a.Payload as a slice into the decoded netlink message. PathViz retains packet bytes for the web UI, so it copies the payload into independently owned storage:

if c.keepBytes {
	// The bytes are copied: the journey keeps them after this callback returns.
	ev.Raw = bytes.Clone(*a.Payload)
}

The dependency does not document the payload as expiring when the callback returns, so this is not a fix for a demonstrated buffer-reuse bug. The clone instead makes PathViz’s ownership explicit and avoids keeping the larger received message alive through a small subslice. bytes.Clone, added in Go 1.20, expresses that intent in one line.

Interface names are cached, misses are not

ifname maps an interface index to a name. The cache is only written on success:

func (c *Capture) ifname(idx uint32) string {
	if idx == 0 {
		return ""
	}
	c.mu.Lock()
	defer c.mu.Unlock()
	if n, ok := c.ifnames[idx]; ok {
		return n
	}
	name := fmt.Sprintf("if%d", idx)
	if ifc, err := net.InterfaceByIndex(int(idx)); err == nil {
		name = ifc.Name
		c.ifnames[idx] = name
	}
	return name
}

A failed lookup returns if<N> and leaves the cache untouched, so a later lookup gets another shot at the real name. That matters for veth pairs and tunnel devices that may appear after an earlier lookup failed.

The NAT-invariant fingerprint

The packet matcher is the central idea. packet.go states its intended invariant on the Packet struct:

// fingerprint identifies the packet across all hooks. It is built only from
// the bytes that neither NAT nor forwarding rewrites.
fingerprint string

For IPv4, parseIPv4 assembles it from the IP ID, the fragment field masked down to offset plus the MF bit, the protocol, and the L4 length:

// NAT-invariant part of the IP header: ID, fragment offset and the MF bit,
// protocol, and the L4 length.
fp := make([]byte, 0, 96)
fp = append(fp, 4, b[4], b[5], byte(fragField>>8)&0x3f, byte(fragField), proto)
fp = binary.BigEndian.AppendUint16(fp, uint16(p.Len-ihl))

Addresses and ports are absent because NAT can rewrite them; TTL is absent because forwarding decrements it. The IPv6 path begins with the version, flow label and payload length, then adds transport-specific fields where available.

Two things jump out as Go choices rather than networking ones. The fingerprint is a string, not a []byte: Go strings are immutable and comparable, so they drop straight into a map key without a wrapper type or a hex encoding. And binary.BigEndian.AppendUint16 appends instead of writing into a fixed array, which is why make([]byte, 0, 96) preallocates capacity and length zero.

Header bytes aren’t the whole story. A payload prefix goes into the fingerprint too, bounded by:

// maxFingerprintPayload caps how many payload bytes take part in the fingerprint.
const maxFingerprintPayload = 48

The 48-byte bound keeps the per-event fingerprint work fixed while adding more distinguishing material than the headers alone. It works alongside rememberFor = "500ms" in probe.go: dynamic nftables set entries expire after half a second, reducing the window in which a look-alike packet can be confused with the original.

This is best-effort identity rather than a protocol guarantee. Collisions remain possible, and helpers or middleboxes can rewrite fields such as TCP sequence numbers or payload bytes. PathViz’s short observation window and low-volume teaching use case make that trade-off reasonable, but the fingerprint should not be described as something no NAT can ever change.

A dissector that refuses to fail

dissect.go turns captured bytes into layers and fields for the UI. Because NFLOG truncates at Bufsize, every single read can run off the end of the buffer. The answer is a set of bounds-checked accessors:

func (d *dissector) has(off, n int) bool { return off >= 0 && n >= 0 && off+n <= len(d.b) }

func (d *dissector) u16(off int) uint16 {
	if !d.has(off, 2) {
		return 0
	}
	return binary.BigEndian.Uint16(d.b[off:])
}

Readers return zero past the end rather than panicking, and slice hands back however many bytes were actually captured:

func (d *dissector) slice(off, n int) []byte {
	if off < 0 || off >= len(d.b) || n <= 0 {
		return nil
	}
	return d.b[off:min(len(d.b), off+n)]
}

The zero value from a short read is not automatically presented as decoded data. add drops any field whose bytes were not captured in full, and end trims fields that fall outside the layer when a damaged length field cuts it short:

// A damaged length field can end the layer before its last fields.
kept := l.Fields[:0]
for _, f := range l.Fields {
	if f.Off >= l.Off && f.Off+f.Len <= to {
		kept = append(kept, f)
	}
}
l.Fields = kept

That l.Fields[:0] reslice is the in-place filter idiom, reusing the backing array instead of allocating. It is the same pattern covered in Filter a slice in Golang.

Dissect also smooths things out for JSON. An empty Layers becomes []Layer{} instead of nil, so the API emits [] and the frontend never has to check for null:

if d.layers == nil {
	d.layers = []Layer{}
}

Whatever the dissector can’t classify lands in a data layer. The doc comment makes the contract explicit: “It never fails: the bytes it cannot decode end up in a data layer.”

The CLI surface

main.go dispatches on the first non-flag argument and defaults to run:

args := os.Args[1:]
cmd := "run"
if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
	cmd, args = args[0], args[1:]
}

The commands are run, rules (print the nftables probe rules and exit), cleanup (remove probes a killed PathViz left behind), version, and help. The run and rules paths get a fresh flag.FlagSet from newFlagSet, built with flag.ContinueOnError and a Usage function that prints the shared help text. main checks for flag.ErrHelp before reporting an error, so --help exits cleanly. Our guide to the Go flag package covers the rest.

Filtering happens through --proto, --ip, --iface, and --port. They’re parsed by a small splitList helper wrapping strings.FieldsFunc, accepting commas or spaces. --iface additionally understands in:<name> and out:<name> prefixes, split apart by splitIface in probe.go.

Filter.Keeps explains why the direction prefix needs code on both sides of the kernel boundary:

// Keeps tells whether a finished journey satisfies the interface part of the
// filter. It weeds out the packets that the PREROUTING probes logged only
// because their output device was not known yet.

At PREROUTING there has been no routing decision yet, so there is no output device for a rule to match. The nftables rules let those packets through, and Go reapplies the interface filter once the journey is complete. The rules perform the filtering possible at capture time; Go applies the output-interface condition once the completed journey contains that information.

Security defaults worth noticing

The web UI listens on 127.0.0.1:7070 by default and mints a random access token per run, printed inside the URL. You can bring your own with --token-file or PATHVIZ_TOKEN; the usage text asks for “at least 16 characters, in a file only you can read”. Turning the token off requires --dangerously-skip-token, a name chosen so nobody reaches for it absentmindedly.

PathViz runs as root and can display packet payloads, so the token is access control for sensitive data, not a substitute for transport security. Its documentation recommends SSH forwarding or a TLS reverse proxy when the UI must be reached from another machine.