Peios Learn
Documentation

Peios

Peios Peios Kernel Universal Directory Project

Developer Tools

Trail Acta Provium clackatoo CAF GCSL Pekit

Applications

Framewright

Standards and Conventions

Standards and Conventions Peios Specifications
Peios Kernel

NTFE

Single-page view · as markdown

Overview

Peios Kernel / Internals / NTFE

NTFE — the Network Traffic Filtering Engine — is the kernel's packet filter. It executes the packet layers of PNP, the Peios Network Policy: PNP is the policy language and its registry layout under Machine\System\Network, and NTFE is one of the components that carry it out (netd is another, for the interface layer). It stands at the netfilter seats, judges every traversal against the policy it reads from the LCS registry itself, and applies the result: a verdict on the packet, side effects on the flow and machine, and an event for whoever is watching. No userspace process is in the enforcement path; the viewer daemon (pnpd) observes and authors, it never decides.

What it replaced #

Peios ships a clean slate below NTFE. The netfilter hook framework and conntrack (built in, with events, zones and timeouts; helpers off) are kept, as are nf_defrag and the nf_reject machinery NTFE uses to phrase refusals. With helpers off nothing assigns a helper to a flow (only a conntrack entry a privileged process creates over ctnetlink, naming one, could carry it), so no flow is expected by another: ct->master stays NULL, and the Flow layer's Related fact (The snapshot) is false on every flow the stack tracks. Everything that was a policy frontend is configured out: nf_tables, the xtables family (iptables, ip6tables, ebtables, arptables), ipset, NFQUEUE, NFLOG, the flow table offload, bridge netfilter, the netfilter BPF link and IPVS. NF_NAT is built but dormant. The kernel config gate (peios/verify-config.sh) asserts both halves so a merge cannot quietly bring a frontend back.

One consequence is worth knowing: conntrack's hooks are demand-activated, historically by a ct-using iptables rule. With no frontend left, NTFE pins them itself at init (nf_ct_netns_get(&init_net, NFPROTO_INET)); without that pin nf_ct_get() is NULL on every packet and the FlowState fact reads untracked forever.

Two halves #

The engine is split along the line that kernels are good at and pure code is good at.

net/ntfe/ (C) owns everything that touches the kernel: the hook registrations and the dispatch law (seats.c), building the fact snapshot from an sk_buff (snapshot.c), RCU publication of policy generations (policy.c), walking the registry into the builder (ingest.c), the three machinery stores — flow tags on a conntrack extension (tags.c), counter tables (counters.c), report emission into KMES (report.c) — the Flow layer's sentence cache and dispatch (flow.c), the refusals a REJECT sends (refuse.c), and the verdict event ring behind /dev/peios-ntfe (events.c).

pnp-core (Rust, security/pkm/pnp_core) owns everything the policy means: the action language, the fact vocabulary and operators, registry-shaped ingestion and validation, the forest, and the evaluation algorithm. It is no_std, allocates only through the fallible PKM wrappers, and has no I/O. The same source compiles twice: under cargo, where a test suite encodes every ratified law by name, and into the kernel, compiled from security/pkm/pnp_core as modules of the security/pkm Rust crate and reached over a C ABI (security/pkm/kacs/ntfe_runtime.rs, the bridge). Nothing about a rule's semantics exists in C.

The bridge is the only place the two meet. C hands it a snapshot and a forest; it resolves the forest's machinery facts against the packet by calling back into the stores, evaluates, and applies the effects — after collation, so a COUNT lands after this packet's own reads and a REPORT can carry the verdict.

Terms #

  • Traversal — one packet passing one direction through the machine.
  • Seat — a netfilter hook NTFE stands at: the device ingress and egress seats (per interface) and the two IP seats, inbound (LOCAL_IN) and outbound (LOCAL_OUT).
  • Layer — one of the three rule forests, RawPacket, Packet and Flow, each a registry key under Machine\System\Network\Rules.
  • Flow — what conntrack tracks: a tuple-identified, bidirectional exchange. The unit the Flow layer judges.
  • Sentence — the Flow layer's cached verdict on a flow: verdict, generation, expiry, on the flow's conntrack extension.
  • Snapshot — the immutable set of facts one traversal is judged against at its seat.
  • Generation — one published policy. Advances on every successful ingestion; 0 means nothing was ever ingested and every layer is permissive, loudly.
  • Forest — a layer's rule trees plus the machinery names it mentions: the tags it reads or writes, the counter streams it writes, and the counter views it reads.
  • Effect — a side effect an evaluation yields (TAG, COUNT, REPORT, a prompt), applied by the glue.
  • Confession — a counter in the engine status for something the engine refused or could not do. Nothing in NTFE fails silently.
  • Owner — the identity KACS stamps on an inet socket (Socket Identity): the effective token and process facts at the last act that committed the socket to a role. What the Flow layer's Local.* facts are read from.
  • Endpoint kind — what stands at a local end of a flow: program, kernel, shared or none (The identity facts).

The chapter follows a packet: the seats it meets (Seats and dispatch), the snapshot taken of it (The snapshot), how the forest judges it (Evaluation), where that forest came from (Ingestion and generations), the stores its effects land in (The stores), the event that records it (The event stream), what happens when it is the first packet of a flow (The Flow layer), and who stands at its local end (The identity facts). NTFE ABI Reference is the generated ABI of /dev/peios-ntfe; NTFE ABI Notes is what the ABI tables cannot say.

Build configuration #

CONFIG_PEIOS_NTFE (bool) depends on SECURITY_PKM, NETFILTER, NETFILTER_INGRESS, NETFILTER_EGRESS and NF_CONNTRACK=y — NTFE is built in and reads flow facts on the packet path, so conntrack must be too. CONFIG_PEIOS_NTFE_KUNIT builds the kernel-resident tests (pkm_kunit_ntfe), defaulting to SECURITY_PKM_KUNIT. The production fragment (build/config/pkm.fragment) enables NTFE and configures the nf_tables/xtables family out; peios/verify-config.sh asserts both.

Related explanations #

  • Event records and status semantics
  • Device operations and errors

Calling the subsystem #

The native NTFE interface reference collects the caller contracts and generated ABI tables.

Seats and dispatch

Peios Kernel / Internals / NTFE

The seats #

NTFE registers at four kinds of netfilter hook.

  • Device ingress (NF_NETDEV_INGRESS) and device egress (NF_NETDEV_EGRESS), per interface. A netdevice notifier registers both on every NETDEV_REGISTER in init_net and unregisters them on NETDEV_UNREGISTER; because register_netdevice_notifier() replays NETDEV_REGISTER for devices that already exist, boot-time interfaces get their seats too. These seats see frames — the Ethernet header is present, VLAN tags are visible, and on the inbound side conntrack has not yet run.
  • IP inbound (NF_INET_LOCAL_IN, IPv4 and IPv6) at priority NF_IP_PRI_FILTER. Conntrack and defragmentation have run; the packet is whole and its flow is classified — and still unconfirmed, since conntrack confirms at the end of this hook.
  • IP outbound (NF_INET_LOCAL_OUT, IPv4 and IPv6) at filter priority. The first point after conntrack has classified a locally generated packet's flow; the sending socket is attached; the entry is unconfirmed until POST_ROUTING.

Only init_net is instrumented: Peios has no container or network namespace story yet, and the notifier ignores devices in other namespaces. Of netfilter's other hooks, FORWARD is empty on a host that does not forward, and PRE_ROUTING and POST_ROUTING see nothing the IP seats do not, save NAT.

The dispatch law #

The ratified law, with the Flow layer's clause:

RawPacket matches all traffic at the device seats, unconditionally. The Packet layer judges every traversal exactly once, at its proper seat — inbound IP at the IP hook, everything outbound at egress — falling back to the ingress seat iff the traversal will never reach its proper seat. The Flow layer judges every tracked flow once per local endpoint, at the IP seats, and its sentence answers for every later packet of the flow.

"Will never reach its proper seat" is decidable at ingress from two facts, and peios_ntfe_traversal_reaches_ip_seat() decides it: the ethertype (only ETH_P_IP and ETH_P_IPV6 cross the IP hooks) and the device's disposition (netif_is_bridge_port() — a frame on a bridge-enslaved port is switched at L2 and never enters this device's IP stack; a copy delivered to the bridge device itself is a separate traversal on that device, judged there).

So at each seat the hook builds one snapshot and judges an ordered list of layers:

SeatLayers, in traversal order
Ingress, IP frame on a plain portRawPacket only (the Packet layer is deferred to LOCAL_IN)
Ingress, non-IP frame or bridge portRawPacket, then Packet (the fallback judgment)
LOCAL_INPacket, then the flow's sentence or Flow
LOCAL_OUTthe flow's sentence or Flow
EgressPacket, then RawPacket

Traversal order is wire order: RawPacket is wire-proximate, so it is first in and last out; Flow is innermost, last in and first out. Each per-packet layer is evaluated once per traversal, and the first non-PASS verdict ends the traversal. A layer with no published forest is permissive and counted as such — at generation 0 that is every layer.

At the IP seats, a packet goes on to the flow dispatch (The Flow layer) — at LOCAL_IN once the Packet layer has passed it, at LOCAL_OUT before any Packet judgment, since the Packet layer judges outbound traffic at egress, after it: an untracked packet has no flow to judge and is accepted, so inbound the Packet verdict stands and outbound egress judges it next; a tracked packet with a current sentence gets that sentence, and one without is evaluated by the Flow forest and sentenced.

Applying a verdict #

PASS continues to the next layer, then NF_ACCEPT. DROP is NF_DROP. REJECT is NF_DROP plus a refusal, phrased by the kind the rule chose and the packet's protocol:

KindIPv4IPv6
Refused (default)TCP: RST; else ICMP port-unreachableTCP: RST; else ICMPv6 port-unreachable
ProhibitedICMP ICMP_PKT_FILTERED (type 3, code 13)ICMPv6 ICMPV6_ADM_PROHIBITED (type 1, code 1)

Every seat can refuse IP traffic — the ingress seat only on an Ethernet device. refuse.c builds the answer with the kernel's frame-less reject builders (nf_reject_skb_v4_tcp_reset(), nf_reject_skb_v4_unreach() and the v6 pair — the ones nftables' netdev reject uses), attaches the flow to it (nf_ct_attach(), so conntrack files it as the reply it claims to be), marks it, and delivers it:

  • from the ingress seat, to the peer on the wire — dev_hard_header() with the offending frame's MACs swapped, then dev_queue_xmit(); that needs an Ethernet device (ARPHRD_ETHER) and a link header to swap, so at the ingress seat of any other device — the loopback device, a tunnel — a REJECT always degrades (below);
  • from every other seat, to ourselves — skb_dst_set_noref() from the offending packet's route, ip_route_me_harder() (or the v6 helper), then ip_local_out(). Inbound, that routes the answer out to the peer with our address as its source; to a link-local address it is routed on the device the offending packet arrived on, without the helper, which would scope the lookup to the loopback device the local delivery route names; outbound, the answer is the peer's, addressed to us, so the route lands on the loopback device and the stack's own RST and ICMP-error handlers fail the local socket at once, with the error the kernel maps the answer to: ECONNREFUSED for a reset or a port unreachable, EHOSTUNREACH for IPv4's admin-filtered, EACCES for IPv6's admin-prohibited. TCP takes an ICMP error that reaches a socket its owner is holding as a soft error, and a refused SYN is refused inside connect(), which holds it: so an ICMP answer to a held TCP socket is sent a tick later (one jiffy, on the system workqueue), once the call has let go. A reset needs no wait: TCP queues it on the socket's backlog. The loopback device retains the route the packet was sent with, so the foreign source address never meets source validation.

The builders read the offending packet from skb->data as though it pointed at the network header, as it does at the IP hooks; at the egress seat it points at the link header the device has pushed, so refuse.c pulls the packet to its network header for the build and pushes it back after.

When the refused packet belongs to an established TCP flow, the far end is torn down too: peios_ntfe_teardown_build() turns the refused packet itself into a reset — same addresses, ports, sequence and acknowledgement numbers, RST set, no data — marks it, and sends it where the packet was going by the same routed path (outbound, to the peer on the wire; inbound, to our own socket over loopback). The refused end gets the kind's story; the far end gets the only story TCP listens to mid-connection. Counted in teardowns_emitted. New flows and UDP have no far end; a reset is never answered with a reset; the ingress seat has no flow facts and never tears down.

The answer is not sent, and the REJECT degrades to DROP (counted in reject_degraded, flagged REJECT_DEGRADED in the event, the kind still named), when there is nothing to send: a non-IP frame, a broadcast or multicast destination, an ingress frame on a non-Ethernet device, a builder that declines (a non-first fragment, which has no transport header to answer from; a failed checksum; a refusal of a refusal), a packet with no route to reason from, or an allocation failure. A first fragment passes the builders' fragment check and is declined by their checksum check instead — its transport checksum covers a payload it carries only part of — so one whose checksum the builder does not verify (one the stack has already marked as checked, or a protocol the builders skip: UDP with a zero checksum, SCTP, ESP, AH, GRE, UDP-Lite) is answered. Fragments meet the builders only at the device seats: LOCAL_IN sees reassembled packets. Refusals sent are counted in refusals_emitted.

The refusal law #

NTFE does not judge its own refusals. The answer refuse.c builds carries skb->ntfe_refusal, a bit the ntfe-refusal-bit patch adds to struct sk_buff inside its headers group (so clones and copies keep it); every hook checks it first and returns NF_ACCEPT without a snapshot, an evaluation or an event, counting refusals_bypassed. Refusals are verdict machinery, not traffic: without the bit, an inbound REJECT's RST would cross the egress seat and could be dropped — and attributed — by an outbound rule, and an outbound REJECT's forged peer answer would be judged as inbound traffic on its way to the socket.

Failing closed #

Evaluation can fail: the core allocates GFP_ATOMIC during a walk and an allocation can be refused. The hook then drops the packet, counts fail_closed, and emits an event attributed to fail-closed with the FAIL_CLOSED flag. Totality does not take "no answer" for an answer.

A snapshot that cannot be built — a frame too mangled to describe — is counted (parse_errors) and judged on its seat facts alone; the absent-fact law does the rest.

The snapshot

Peios Kernel / Internals / NTFE

Every judgment reads a snapshot: a fixed-size, stack-allocated struct peios_ntfe_snapshot built once per seat by peios_ntfe_snapshot_from_skb() and never mutated during evaluation. That immutability is a ratified law, not an implementation detail — nothing a rule writes is visible to the same evaluation's matching, so temporal feedback (the next packet sees it) is the only feedback there is.

Validity bits #

Many facts have meaningful zero values (port 0, TTL 0, VLAN 0), so presence is carried separately in has, a bitmask of PEIOS_NTFE_HAS_*: ethertype, MACs, source MAC alone, VLAN, TTL, DSCP, fragment, ports, TCP flags, ICMP, time, the flow's start time, and the network context. Address facts use addr_family (0, 4 or 6) as their validity; the protocol is valid iff a family is. Flow state uses its own ABSENT value; flow_related is valid iff flow is. The bridge turns each clear bit into None on the Rust side, and the absent-fact law makes every condition over a None false.

Extraction #

Seat facts first: seat, direction, interface (ifindex and name), the network context of that interface (below), whether the device is the loopback (IFF_LOOPBACK — the flow dispatch's "two endpoints" test), the packet length as the stack sees it (skb->len — not the wire length), and the wall clock (ktime_get_real_seconds() through time64_to_tm(), UTC, with tm_wday re-based so the DayOfWeek fact is ISO: 1 = Monday .. 7 = Sunday), kept alongside as epoch seconds (t_secs) for the time-flip arithmetic (Evaluation) and the sentence expiry check (The Flow layer).

Then the frame: the ethertype from skb->protocol. The VLAN id is the frame's tag if skb_vlan_tag_present(), else the device's if is_vlan_dev() — the VLAN is a fact of the frame at the device seats and of the device at the IP seats, where inbound the VLAN code has already stripped the tag and re-parented the packet onto the VLAN device, and outbound the tag is pushed only when that device transmits. (Before the Flow slice the IP seats read the stripped tag and Vlan was absent on VLAN interfaces there.) The MAC pair if the MAC header is set and the device is ARPHRD_ETHER; failing that, at an IP seat on an Ethernet device — a locally generated packet with no link header yet — the source alone, from the device's own address (HAS_SRC_MAC): present so every flow carries the same fact set, and not useful. The destination is unknown until neighbour resolution, after the seat: absent.

Then IP, from skb_network_offset():

  • IPv4 — addresses, TTL, DSCP (tos >> 2), the fragment flag (IP_MF set or a non-zero fragment offset), the protocol, and the L4 facts from ihl * 4 on. A non-first fragment (non-zero offset) has no L4 facts — its payload begins mid-datagram — though it still reads the protocol its header names.
  • IPv6 — addresses, hop limit, DSCP from the traffic class, and a bounded walk (eight hops) of the extension-header chain: hop-by-hop, routing and destination options are skipped by (hdrlen + 1) * 8; a fragment header sets the fragment fact, and a non-first fragment ends the walk with no L4 facts (there are none to read). The protocol fact is the header the walk stops at — so an MLD report behind a hop-by-hop header reads Protocol = icmpv6, as a rule would expect. Every way out of the walk names one: a non-first fragment reads the protocol its fragment header names, as a later IPv4 fragment reads its own; an extension header too short to read is itself the protocol; and after eight hops the next header is the protocol, with L4 facts if it is not another extension header.

Then L4, by protocol: ports for TCP, UDP and SCTP; the flag byte for TCP (TcpFlags is the TCP header's byte at offset 13, FIN in bit 0 through CWR in bit 7, the same encoding tcp_flag_byte() uses); type and code for ICMP and ICMPv6. Every header read goes through skb_header_pointer(), so a packet whose headers are paged or truncated yields absent facts rather than a fault.

Flow state and the flow #

At the ingress seat conntrack has not run and the flow state is ABSENT; at LOCAL_IN, LOCAL_OUT and egress, nf_ct_get() gives the entry and ctinfo maps to the fact: IP_CT_ESTABLISHED and its reply → established; IP_CT_RELATED and reply → related; IP_CT_NEW → new; anything else, or no entry at all, → untracked. The invalid value is reserved: distinguishing an incoherent packet needs conntrack's own verdict, which this seat does not receive.

The snapshot also carries flow: the struct nf_conn * itself (never a template), or NULL. This is the tag store's and the sentence's scope — TAG writes land on that entry's extension, tag reads come from it, and the Flow layer's verdict is cached there. It is the one pointer in the snapshot that outlives the extraction, and it is valid because the skb holds a reference to the entry for the duration of the hook.

With the flow come two facts that exist only on a flow: flow_related (ct->master != NULL — the flow was expected by another) and the flow's start time, read from the extension's start_secs (stamped when conntrack created the entry) through the same time64_to_tm() lowering as the clock, into the s_* fields (HAS_START). These are the Flow layer's Related and Start.* facts. flow_reply says whether this packet travels in the flow's reply direction — the Flow layer's view builder (The Flow layer) uses it to turn the packet's tuple back into the flow's.

What the core sees #

NtfeSnapshotC in security/pkm/kacs/ntfe_runtime.rs mirrors the C struct field for field (#[repr(C)]; keep them in lockstep). snapshot_from_c() lifts it into the core's Snapshot — an Option per fact — and the bridge then fills in the two machinery fact tables: tags, as (name hash, value) pairs for every tag name the forest can read that the flow carries, and counter_views, as (view index, value) for every view the forest reads that the store can answer for this packet. Both are resolved before evaluation, against the forest being evaluated, which is why the forest carries its name sets (Ingestion and generations).

Three visibility laws are enforced here, and again in the core, which builds a condition over a fact its layer never has never to hold (Ingestion and generations): a RawPacket forest is given no tags whatever the flow says (tags flow upward only, and RawPacket is the lowest layer; Packet and Flow forests read them); an ingress snapshot has no flow, so no tags exist to give; and the flow-only facts (Related, Start.*, and the identity facts) are given to a Flow forest alone — everywhere else they are absent by law, exactly as ingestion's lint says (Ingestion and generations). The clock is given to every layer, and so is the trace of consulted time conditions (Evaluation); only the Flow seat acts on it.

The network context #

Three string fields are not read from the packet either: network_id, network_name and network_trust, the Network.* facts. peios_ntfe_context_fill() (context.c) looks the device's name up in the active context table — the kernel's reading of netd's inventory, one entry per interface standing on an identified network, built by ingestion (Ingestion and generations) and published under RCU — and copies the entry's three strings in, setting HAS_NETWORK. The bridge lifts the id whenever the bit is set, and the name and trust only when non-empty (a record the operator has not labelled). No entry, no bit: an interface no network has been identified on carries no context, and every condition over the three facts is false there. The strings are bounded (40, 64 and 32 bytes with their NUL, PEIOS_NTFE_NETWORK_*_LEN); a longer registry value — a record's Name or Trust, or the Network an interface's Status names — is truncated at ingestion and the truncation logged once. The id of a record is its key name under Networks\, not a value, and is not truncated: a name of 40 bytes or more is ignored, record and all (Ingestion and generations).

The fields are the three Network.* facts the interface layer — the fourth layer, which netd builds and judges in userspace — conditions on beside its own (see the interface layer): netd fills them from the interface record when it judges an interface, the kernel from the table when it judges a packet, so Network.Trust.Equal reads the same record in either layer.

Flow refreshes these facts on a cache miss after capturing its cache invalidation generation (The Flow layer), because this packet snapshot can predate a context publication. Packet and RawPacket continue to use their traversal snapshot; their verdicts are not retained as Flow sentences.

The identity fields #

The snapshot's last fields are not extracted from the packet at all. The Flow layer's view builder (The Flow layer) sets them from the flow's extension: for the local end, and on loopback for the other end, the kind (program, kernel, shared, none), the process GUID, pid and comm, and a borrowed pointer to the KACS token the socket was stamped with — the extension holds the reference for the flow's life, so the pointer is valid for the hook. The bridge lifts a program end into a Principal the core's Local.* and Remote.* conditions question (The identity facts); every other snapshot leaves the fields zero, which lifts to absent.

Evaluation

Peios Kernel / Internals / NTFE

Evaluation is pnp_core::eval::evaluate(forest, snapshot, ctx): pure, allocation-fallible, and the same code under cargo and in the kernel. Its steps are the ratified design's six, in order.

1. Matching #

A rule matches iff it is enabled and every one of its conditions holds against the snapshot. Conditions are a conjunction; a value written as a list is a disjunction within that one field. A disabled rule never matches, so its subtree is unreachable.

Conditions are evaluated in the order ingestion stored them, which puts live-time conditions (Time.*) last, and the conjunction stops at the first false one. Every live-time condition actually reached — true or false — is consulted, and Rule::matches_traced() records into a MatchTrace the moment it would next flip (Condition::next_flip()): for hour, minute, second and day-of-week, the value sequence is scanned one cycle ahead with the condition's own operator, so Time.Hour.Equal 9-17 at 10:30 flips at 18:00 and Time.Hour.LessThan 24 never does; day-of-month, month and year answer "next midnight", since exact flips need calendar arithmetic nobody has asked for. A false condition is consulted too: a higher-priority rule that missed only on the clock may match later. A rule whose address or port conditions fail first never consults its clock and contributes nothing. The earliest consulted flip is the evaluation's expires_at — the Flow layer's sentence expiry (The Flow layer); the per-packet layers compute it and ignore it.

2. The trigger set #

The walk descends each tree from its root. A node triggers iff it matches and none of its children match: a matching child shadows its parent. Shadowing exists only within a lineage — two trees never shadow each other, and their order in the forest carries no meaning. The walk returns "matched" to the parent so the parent knows it was shadowed.

3. Resolving a triggered rule #

Every triggered rule's action list is resolved once. Verdict actions fold to the strictest listed; TAG and COUNT push effects; REPORT folds to the highest level listed and pushes one effect if that level is at or above CurrentReportingLevel (level >= CurrentReportingLevel; one report per rule per evaluation); PROMPT pushes a prompt-issued effect and, with no handler transport in this release, resolves its fallback in place (nesting bounded by MAX_PROMPT_CHAIN, 4). Side effects always execute — they are pushed before anyone knows whether the rule's verdict will win.

4. Abstention #

A triggered rule that yields no verdict abstains. The walk then goes up the rule's own parentage — the chain it descended by — to the nearest ancestor whose actions contain a direct verdict (a top-level PASS, DROP or REJECT; a verdict inside a PROMPT fallback does not count), and that ancestor speaks for the region: its full action list resolves, once. A speaker reached by several abstaining descendants in one evaluation executes only the first time (spoken tracks resolved speakers by identity). Intermediate abstaining ancestors execute nothing. If no ancestor bears a verdict, the branch contributes nothing and other trees or the backstop answer.

The attribution of a speaker's verdict is the speaker's path, not the abstaining descendant's.

5. Collation #

Every yielded verdict is a candidate (verdict, priority, path). The winner has the highest priority; at equal priority the strictest verdict: DROP (3) > REJECT(Refused) (2) > REJECT(Prohibited) (1) > PASS (0). The two reject ranks are a deterministic tie-break — the quieter story wins — that exists only because candidate order is meaningless. Priority is the rule's effective priority, resolved at ingestion: a rule's own Priority value, else its parent's, else 0.

6. The backstop #

No candidate at all: the verdict is DROP, attributed to backstop, and the evaluation is flagged so the event can say so. The backstop is compiled in and un-deletable; every permissive statement in a policy is therefore a visible rule.

The evaluation as data #

Tree traversal, ancestor fallback, and candidate collation live in pnp_core::machinery. Its domain adapter supplies matching, action resolution and verdict strictness. Packet and interface evaluation retain the pnp_core::eval::evaluate entry point and their existing fact and action types. Userspace domains can share the same traversal without constructing synthetic packet snapshots. The machinery computes results and optional explanation steps; callers retain responsibility for applying effects and refusing conflicts.

Evaluation carries the winning verdict, its attribution, the backstop flag, every effect to apply, every candidate (winners and losers alike) for observability, and expires_at. Effects reference their stores by name and hash: Effect::Tag { hash, op }, Effect::Count { hash, amount } with the amount already resolved (Length becomes the packet length, or 0 when the packet has none), Effect::Report { rule, level }, Effect::PromptIssued { rule, handler }.

The bridge #

ntfe_rust_evaluate(forest, snap, layer, reporting_level, out) is what policy.c calls under rcu_read_lock(). It:

  1. lifts the C snapshot (The snapshot) and resolves the forest's machinery facts through the stores — peios_ntfe_tag_lookup() for every tag name the forest mentions (Packet and Flow layers; RawPacket reads none), peios_ntfe_counter_read() for every view — and gives a Flow forest its own facts, Related and Start.*;
  2. evaluates with EvalContext { reporting_level };
  3. writes the verdict, the reject kind, the backstop flag, the attribution (cut to 95 bytes), the FNV-1a-64 of the whole attributing path (attributed_hash) and expires_at (0 = never) into struct peios_ntfe_outcome;
  4. then applies the effects — peios_ntfe_tag_apply(), peios_ntfe_counter_add(), peios_ntfe_report_emit() with the verdict it just computed — counting each species into the outcome.

Ordering 4 after 2 is what the snapshot-immutability law requires: a COUNT is applied after this packet's own view reads, so a rule cannot trip its own threshold, and a REPORT can name the verdict. Every allocation in 1–2 is GFP_ATOMIC (pnp-core's pkm_alloc in kernel mode); a failure returns -ENOMEM and the hook fails closed (Seats and dispatch). The store calls never sleep.

Policy ingestion and validation

Peios Kernel / Internals / NTFE

The kernel reads its own policy. There is no daemon that compiles rules and pushes them down; ingest.c walks the registry through the LCS source interface, feeds what it finds to the pnp-core builder over the bridge, and publishes the result as a generation — or keeps the previous one, loudly. The same walk reads netd's inventory beside the rules into the network context table (The snapshot), because to a flow the two change together: a network being recognised on an interface is as much a policy change as a rule being written.

Discovery and change notification #

At LCS bootstrap, NTFE's key is discovered fifth alongside the other kernel-owned subtrees: pkm_lcs_walk_absolute_components() resolves Machine\System\Network (the leading Machine hive component is resolved locally against the hive root, not round-tripped), and its absence is not an error — no key, no policy and no context, generation stays where it is. When the key exists one internal watch is armed on it, depth-unbounded, for every change of content at any depth — LCS delivers it a value set, a value deleted, a subkey created, a subkey deleted and a key deleted; a security-descriptor change is not delivered: Rules\, Interfaces\ and Networks\ beneath it are what NTFE reads; Profiles\ and Dns\ are netd's and resolvd's, and a write there fires the watch and costs a walk that publishes nothing.

Watch events arrive per key and uncoalesced. peios_ntfe_network_registry_changed() records the source and key, sets a pending flag, and mod_delayed_work()s a re-walk with a 50 ms debounce: a burst of writes (a transaction touching a rule and its values, an autoapply seeding a whole policy, netd syncing every interface's Status after a link event) yields one re-walk after the burst goes quiet. The walk itself runs in process context on system_wq, one at a time under a mutex, since the bootstrap refresh and the deferred work may overlap.

The walk #

peios_ntfe_network_refresh_from_key() snapshots the LCS runtime limits, sequence and layer view, enumerates the Network key's children for Rules, Interfaces and Networks, and runs two independent stages — the rules, then the context; a failure in the first does not skip the second, and the walk reports the first error. No Rules key leaves the previous generation standing, exactly as a walk that refused would.

The rules stage:

  1. reads the Rules key's own values for CurrentReportingLevel (REG_DWORD, REG_DWORD_BIG_ENDIAN or REG_QWORD; 1..6; absent = 1; anything else refuses);
  2. enumerates its children for the layer keys Packet, RawPacket and Flow (Interface is netd's — the interface layer is built and judged in userspace with the same pnp-core, and the kernel never reads it; any other name is ignored);
  3. for each present layer, opens a builder and walks the layer key's subkeys as rule roots. Each rule is one RSI_QUERY_VALUES round trip (its effective, layering-resolved values, delivered in the batch record format u32 name_len | name | u32 type | u32 data_len | data) followed by one RSI_ENUM_CHILDREN round trip for its exceptions, recursively, bounded by depth 12 and 4096 rules per layer: a root rule is depth 0, so a chain of 13 keys is the deepest read, and a rule deeper than that or a 4097th rule refuses the walk.

Registry types are lowered as the builder ABI expects: REG_SZ and REG_EXPAND_SZ to strings (NUL termination stripped), REG_DWORD and REG_DWORD_BIG_ENDIAN to integers, REG_QWORD to a signed 64-bit integer, REG_MULTI_SZ to a list of strings. Any other type in a rule refuses the walk: atomic transitions prefer a loud rejection over a silently half-read rule. So does an integer of the wrong length — a REG_DWORD or REG_DWORD_BIG_ENDIAN whose data is not 4 bytes, a REG_QWORD not 8 — in a rule or in CurrentReportingLevel.

Everything the stage feeds the builder — each layer and whether its key exists, rule name and depth, value name, type and bytes — also goes through an FNV-1a digest, and so does the reporting level's value (not its bytes: the same level re-written as another integer type digests the same). When the digest equals the one of the last walk that published (none before the first), the stage publishes nothing: the built forests are freed and the generation does not move. The active generation already is this policy — even when that policy is no forests at all — and republishing would only make every sentence stale for nothing. A walk fired by an inventory write therefore publishes no rules; it moves the generation only if the context stage finds the table changed (below). The writes of a transaction reach the watch together at its commit and, like any burst, coalesce into one walk.

The context stage #

The inventory is read into one struct peios_ntfe_context_table, at most 64 entries of interface name, network id, name and trust:

  1. every child of Networks\ is a record; its key name is the id (a UUID — a name of 40 bytes or more, which no id field can hold, is ignored with its record, once loudly), and one RSI_QUERY_VALUES round trip reads its Name and Trust (REG_SZ; absent or unreadable is empty, and the id is still a fact), up to 256 records;
  2. every child of Interfaces\ is an interface; its Status subkey is found by one RSI_ENUM_CHILDREN and read by one RSI_QUERY_VALUES for Name (the kernel interface name) and Network (the id netd identified on it). Both present make an entry, joined to the record of that id for its name and trust; either absent — no link, no offer yet, an IGNOREd or DOWN interface — makes none.

Nothing in the stage refuses a generation. A record that cannot be read is logged and skipped — an interface key whose subkeys cannot be listed, or whose Status cannot be read, carries no context; a network record whose values cannot be read keeps its id with no name and no trust; an interface beyond the 64th carries no context, a value longer than its field is truncated with one warning. If the list of Networks\ or Interfaces\ itself cannot be read, the stage publishes nothing and the previous table stands: a table built from half a list would strip every network after the failure point of its name and trust, and with them every rule that names them. That failure is the walk's error — it shows in last_ingest_error — and the rules stage's outcome is untouched by it. Otherwise the table goes to peios_ntfe_context_publish() (The snapshot): if it equals the active one entry for entry it is freed and nothing happens; otherwise it is rcu_assign_pointer()ed into place, the generation counter advances, the old table is freed after grace, and the kernel log says how many interfaces carry a context. The generation advance is the whole mechanism by which a context change reaches running flows: every sentence is now stale and is re-judged on its flow's next packet (The Flow layer), the same path a rule change takes.

Building and validating #

The builder (ntfe_rust_builder_*) accumulates RuleInput trees; build runs pnp_core::ingest::build_forest, which parses every condition key and action expression, orders each rule's conditions with the live-time ones last (Evaluation), resolves priority inheritance, lints layer-impossible facts (a FlowState or tag condition in a RawPacket forest; a per-packet fact — Length, TcpFlags, Fragment, Ttl, Dscp, EtherType, DstMac, FlowState — in a Flow forest; Related or Start.* anywhere but Flow — all legal, and built never to hold; the kernel drops lints, the authoring surface shows them), and collects the forest's name sets: every tag name mentioned in a TAG action, a PROMPT fallback, or a Tag.<n> condition, split into the names the forest writes and the first rule reading each; every stream a COUNT writes; every distinct counter view a Counter.<n>(...) condition reads, with the first rule and value that mentioned it. Views are deduplicated and conditions refer to them by index — that index is what the bridge uses when it fills counter_views (The snapshot).

Refusals, each carrying the offending rule's path (BuildError): unknown fact, unsupported operator, unparsable pattern, a counter view that does not parse (bad duration, unknown key fact, duplicate arguments, a window over the one-day horizon, or a multibyte character where the argument grammar requires ASCII), a non-list Actions, an unparsable action, a REJECT kind that is not Refused or Prohibited, a PROMPT chain nested deeper than MAX_PROMPT_CHAIN (4), refused as an unparsable action, an action the layer does not speak (JOIN, IGNORE or DOWN, the interface layer's verdicts, in a kernel layer, directly or as a PROMPT fallback), a Present condition on a fact that never exists at the rule's layer (every other operator over such a fact is only linted, below; Present looks through the absent-fact law, so X.Present = 0 there would always hold), a Priority that is not an integer, an Enabled that is not 0 or 1, a rule name that is empty or contains a path separator (a backstop: LCS refuses such a key name before the walk could read it) — and, over the name sets, two distinct tag names (or stream names) whose 64-bit hashes collide.

After all three layers build, ntfe_rust_forests_check() runs the checks that span forests, because the stores are machine-wide: tag and stream hashes must be distinct across every forest; every counter view must have a writer in some forest — a view over a stream no rule writes is statically dead (it can only ever read absent) and is refused with the rule and key that read it; and no forest may read a tag a higher forest writes (RawPacket < Packet < Flow) — tags flow strictly upward, and since rules are the only source of tag names the downward read is refused statically, with the reading rule and the name.

Related explanations #

  • Generation publication and recovery

Generation publication and recovery

Peios Kernel / Internals / NTFE

Publication #

peios_ntfe_policy_publish(packet, raw, flow, reporting_level) is process context under a mutex. It runs the cross-forest check, then materializes the counter store for the union of every forest's views (The stores) — so a store that cannot be built (allocation, more than eight windows on one table) refuses the generation before anything is swapped. Only then does it advance the generation counter, allocate the new struct peios_ntfe_policy (three opaque forest pointers plus the reporting level) and rcu_assign_pointer() it into place. Hook-path readers dereference it under rcu_read_lock() and never block; they see the old generation or the new one, never a mix. The old policy is released by call_rcu(), and its forests by ntfe_rust_forest_free() in the callback after grace.

Every walk records its outcome: last_ingest_error (0, or the positive errno of the last failed walk) and last_ingest_t_ns, both in the status. A refusal leaves the previous generation active and says so in the kernel log. contexts in the status is the number of interfaces in the active context table.

In the event stream #

NTFE writes its own lifecycle to KMES, origin class KMES_ORIGIN_NTFE (4), beside the reports of The stores. Every publication writes one ntfe.policy.published, after the swap; a refusal writes none. Its payload is one policy map: generation, the generation now in force; generation-previous, the generation of the policy it replaced, 0 for the first since boot; layers, the layers that have a forest, in the order raw-packet, packet, flow, and an empty list for a policy of no forests; and report-threshold and report-threshold-previous, the new and the replaced CurrentReportingLevel, the latter 1 when nothing was replaced. A walk whose digest is unchanged publishes nothing, and so writes nothing. A context-table change advances the generation without a policy and writes no ntfe.policy.published either, so the generations between two of these events are the earlier policy under a changed context.

A refused rules walk writes one ntfe.policy.rejected. Its policy map holds the generation still in force and previous-retained, always true. Its outcome map holds errno, the walk's negative errno, and reason. When the refusal is in, or names, one rule, a rule map follows. It holds layer when the refusal arose building one layer's forest, and action-error for a bad-action. It holds name, the rule's path relative to its layer key; a path longer than 255 bytes is cut at a character boundary, with name-truncated.

The errno is the walk's, unchanged. The reason is new: the bridge's ntfe_rust_builder_build_why() and ntfe_rust_forests_check_why() fill a struct peios_ntfe_build_why from pnp-core's BuildError. A builder refusal keeps its own name and its rule's path, such as unknown-fact, bad-action with its action error, bad-priority, or tag-downward-read from the cross-forest checks, which name the rule but no layer. The walk names the refusals it makes itself:

  • rule-too-deep and too-many-rules, with -E2BIG;
  • bad-value-type, bad-value-length and not-utf8, in the rule that holds the value;
  • bad-reporting-level, counter-store-refused and out-of-memory;
  • registry-read-failed for a source round trip that failed.

A walk that finds no Rules key writes the event too, with reason no-rules-key, no errno and no rule.

Every walk re-reads the policy, including the walks netd's inventory writes cause, so a broken policy is refused again and again until it is fixed. The event is written once per distinct refusal: a walk whose digest, errno and reason equal those of the last refusal written writes none. A walk the rules stage accepts, published or unchanged, clears that memory, so the next refusal is written whatever it is. A missing Rules key is therefore written once each time the key goes missing. The kernel log line is written for every refusal, as before, and now names the reason. Both events are built on the stack in process context, under the publication mutex or the walk mutex; neither is ever written from the packet path.

In force #

A registry write that has returned is delivered, not enforced: the walk that reads it runs after the debounce. Two status counters say which a writer is looking at. changes_noted is incremented by peios_ntfe_network_registry_changed() for every watch event, and LCS delivers its internal watches inside the write that caused them, after the commit and before the syscall returns, so a writer that reads the status after its write sees its own change counted. The deferred work reads changes_noted under the same lock that clears the pending flag, before it walks, and stores that value in changes_walked when the walk returns, whether it published or was refused.

So a writer is in force once changes_walked reaches the changes_noted it read after writing: the walk that satisfied it started after the write committed. A change that lands mid-walk raises changes_noted again and re-arms the work, so the pair stays unequal until a later walk covers it. A refused walk still advances changes_walked; the writer then reads last_ingest_error to learn that what it wrote is not what is enforced. The walk records its error before it stores changes_walked, and the status reads them in the other order, so a status that shows a change walked shows that walk's error or a later one's, never an older one. The bootstrap walk is not a noted change and moves neither counter. net policy wait is this loop.

Generation 0 #

Until the first successful ingestion there is no policy at all, and every layer is permissive: judged stays 0, permissive counts traversals, no events are emitted (there is no decision to attribute), and the status reports enforcing = 0. The init log line says it plainly. This is the ratified loud default — the alternative, a compiled-in policy the registry cannot see, was rejected.

A new generation does not touch the flows: every sentence written under the old one is stale by generation and is re-judged on its flow's next packet (The Flow layer). That is how a policy change — and a context change, which advances the same counter — reaches running connections without a walk of the conntrack table.

The stores

Peios Kernel / Internals / NTFE

Effects need somewhere to land. Three stores, each with a small C surface the bridge calls during evaluation, each confessing what it refuses into the engine status.

Identities #

Tag and stream names cross into the stores as 64-bit FNV-1a hashes (pnp_core::hash::name_hash). The stores never see a string on the packet path, and never a generation: a flow's tag table holds (hash, value) pairs, a counter table is keyed by its stream's hash. Two consequences: tags survive policy reloads by construction (the table knows nothing to invalidate), and a hash must be a deterministic identity, not a probabilistic one — which ingestion guarantees by refusing any generation whose distinct names collide (Ingestion and generations). Within a running policy a collision is impossible; across generations the residual is a 64-bit birthday bound over a handful of names, documented and not defended.

Flow tags #

A tag is a named unsigned integer on a conntrack entry. The store is the tags pointer of NTFE's conntrack extension — NF_CT_EXT_NTFE, struct peios_ntfe_ct (include/linux/peios_ntfe.h), added to every flow at creation (init_conntrack(), by the ntfe-conntrack-ext.patch), with the pointer NULL until the flow's first TAG. The extension block of a confirmed conntrack entry is immutable (upstream removed post-confirm resizing as an RCU-reader race), and NTFE's egress seat runs after confirmation, so the extension must exist before it is needed; a fixed extension on every flow is the cheapest way to guarantee that. Since the Flow slice the extension also holds the flow's start time and its two sentences (The Flow layer) — 88 bytes per flow, most of it the sentences — while untagged flows, nearly all of them, still pay nothing for a table.

The first TAG allocates (GFP_ATOMIC) a table of eight (hash, value, present) entries; a full table is replaced by one twice the size — copy, rcu_assign_pointer(), kfree_rcu() the old — up to the tripwire of 64 distinct tags per flow. Readers walk the table under RCU with no lock (the hook path already holds the read lock); writers serialize on the flow's own ct->lock. Clear tombstones an entry (present = 0) rather than compacting, so a concurrent reader never sees the table shift under it, and a later Set reuses the slot. Add saturates at U64_MAX. The entry's identity is published before the length that exposes it (smp_wmb() then WRITE_ONCE(len)), so a reader that sees the new length sees a complete entry.

When the flow dies, nf_conntrack_free() calls peios_ntfe_ct_destroy() (the same patch), which kfree_rcu()s the table — a reader that found the entry under RCU may still be walking it.

Confessions: tag_writes (ops applied), tag_untracked (a TAG on a packet with no flow — untracked traffic, or the ingress seat — is a no-op), tag_refused (the tripwire, an allocation failure, or a flow whose extension could not be allocated at creation). Clearing an absent tag is a no-op, not a refusal.

Counters #

COUNT(Name[, amount]) emits into a stream; every Counter.Name([window][, key]) a rule reads is a view. Nothing is declared: views are compile-time constants (rules are their only source), so at publication (Ingestion and generations) the store receives the complete view set of all three forests — Packet, RawPacket and Flow — and materializes exactly that — one table per distinct (stream hash, key-spec), each answering every window any view of that pair asks for, plus the cumulative total. A COUNT increments every table of its stream; the amplification is bounded by what policy authors wrote, the trusted side of the trust asymmetry.

A table is a 1024-bucket hash of cells (jhash over the cell key) under a per-table spinlock (_bh, since the publisher runs in process context). A cell key is built from the packet by the table's key-spec: address family, source and destination address (16 bytes each, v4 in the first four), interface index — only the facts the spec names, the rest zero. A packet lacking a keyed fact (an ARP frame for a SrcAddr-keyed table) has no cell: its COUNT no-ops into that table (count_key_absent) and its view reads absent — the absent-fact law on both sides.

A cell holds a cumulative total, the seconds of its last write, and one ring per table window: eight buckets, each stamped with the period it belongs to (now / bucket_secs, where bucket_secs = max(1, window / 8)). A write zeroes a bucket whose stamp is stale before adding; a read sums the buckets whose stamp is within the last eight periods. Advancement is lazy — there are no timers — and the window is an approximation up to one bucket wide, by design.

The keyspace of a keyed table is chosen by whoever sends packets, so tables are hard-capped at 4096 cells. At the cap the store first reaps cells idle for longer than the table's longest window (floor 60 s); if none are idle the new key is refused and confessed (count_refused). Never silent eviction.

The store outlives generations. Re-publication keeps tables whose window set did not change, creates new ones, migrates tables whose windows changed (each cell is re-allocated in the new ring layout; the total and any window both sets share carry over, new windows start empty and converge), and retires tables no forest views any more — list_del_rcu() then free after grace, cells included. Reads on the packet path walk the table list and the cell lists under RCU; the publisher holds a mutex.

PEIOS_NTFE_IOC_COUNTERS dumps every cell of every table for the viewer: stream name, key-spec, the key, the total, the last-write time, and the current value of each window. It is a best-effort snapshot, which is fine for counters that are approximate by design: the cells are gathered into a kernel batch under one RCU read section and copied out after it, and a store with more cells than a batch holds (4096) takes further passes, each resuming after the cells already written, so a cell created or retired between passes may be missed or seen twice.

Reports #

REPORT(level) at or above CurrentReportingLevel becomes one KMES event: origin class KMES_ORIGIN_NTFE (4), event type ntfe.verdict.reported, and a msgpack payload laid out as the event catalogue's ntfe fragment says: nested string-keyed maps, one per path segment. rule carries the attribution (name, the path, and hash, the FNV-1a-64 of the whole path), the report-level, and where the judgment stood (layer: raw-packet, packet or flow; seat). outcome carries what it said (verdict: pass, reject or drop; and reason, prohibited or refused, when it was a reject). The packet is network (direction, interface with its name and index, ether-type, family as the AF_* number, protocol, length), source and destination (each an address as text and a port), and flow (state). policy carries the generation. The time is the KMES header's; the payload does not repeat it. A packet key whose fact can be absent is present only when the packet has it: network.protocol, source and destination when it has an address family, their ports when it has ports, flow when the flow-state fact is present. network.direction, network.interface.index, network.ether-type, network.family and network.length are always emitted — an interface index of 0 and a family of AF_UNSPEC (0) are the catalogue's own values for none. network.interface.name is left out when no device was there to name; no key is ever written as an empty string.

The payload is built on the stack (512 bytes) because the packet path runs in softirq and pkm_kmes_emit_kernel() is a preempt-disabled per-CPU ring write with no allocation of its own. Every map's size is known before it is written, save rule's, whose one-byte header is settled once the name's fate is. Every value but rule.name is bounded, so rule goes in last and name last within it: a path too long for the room left is cut at a character boundary to fit, and rule.name-truncated (true, absent when the name is whole) says so. The event is always emitted, and rule.hash still names the whole path, so a reader resolves the rule against the policy. Flood control is the author's by design — the level gate — with KMES's own ring accounting as the backstop. reports_emitted counts what reached the ring.

Event ring and delivery

Peios Kernel / Internals / NTFE

Every real evaluation — a published forest judged the traversal, or a fail-closed drop — appends one struct peios_ntfe_event to a bounded ring. Permissive traversals emit nothing: there is no decision to attribute, and the status tells that story instead. A packet answered by its flow's cached sentence emits nothing either: there was no evaluation, and flow_cached counts it. The layouts are in NTFE ABI Reference; this page is what they mean.

The ring and its reader #

The ring holds 4096 events under a spinlock (irqsave: emission happens in softirq). A full ring overwrites the oldest event and counts the loss in events_dropped — the honesty rule: a slow reader loses data and is told so, in the status and by the gap in sequence numbers.

/dev/peios-ntfe is a misc device, mode 0600. Any number of files may be open on it, because the status and dump ioctls are asked by tools while a viewer holds the stream, but the ring has one drain: the first file to read() claims it until it closes, and another file's read() returns -EBUSY meanwhile. read() returns whole records only, up to 64 per call, and blocks on an empty ring unless O_NONBLOCK; poll() raises POLLIN when events wait. A reader that reconnects resumes from whatever the ring still holds, and catches the gap from the sequence numbers.

The viewer daemon reads it with a small wrinkle worth knowing about: its own HTTP responses to a viewer are judged traffic too, so every event it sends produces another event — a feedback loop. pnpd hides events about its own TCP port from what it serves and counts them (own_verdicts_hidden), which is the same treatment the wire tap gives its own frames.

Related explanations #

  • Event records and status semantics

The Flow layer

Peios Kernel / Internals / NTFE

The Flow layer (Rules\Flow, the rung-2 design on PEI-598) is the same rule atom, verbs and evaluation as the per-packet layers, applied to a different unit: the flow, what conntrack tracks. It exists because the per-packet evaluator has no early exit — collation and side-effects-always mean every packet walks the whole forest, so an Established → PASS rule saves nothing — and because flows carry facts (a start time, relatedness, one day an owner) and effect units (a connection, not a packet) that packets do not. The Packet layer becomes the cheap filter in front; the decisions move here and run once per connection.

One judgment per local endpoint #

peios_ntfe_flow_dispatch() (flow.c) is called at the IP seats: inbound, at LOCAL_IN, for every packet the Packet layer passed; outbound, at LOCAL_OUT, for every packet, before any Packet judgment — the Packet layer judges outbound traffic at egress, after it (Seats and dispatch). An untracked packet (snap->flow == NULL) has no flow to judge and is accepted, NF_ACCEPT: inbound the Packet verdict stands, outbound the Packet layer judges it next at egress. A tracked packet reads its flow's sentence:

  • a current sentence — its policy object and policy/context invalidation generation are both current, and its expiry (if any) has not passed — is applied without evaluation (flow_cached);
  • otherwise the Flow forest is evaluated against the snapshot (peios_ntfe_policy_snapshot_eval(), counted in judged and flow_judged), the outcome is written as the new sentence, an event is emitted (with REJUDGED when a stale sentence was replaced, flow_rejudged or flow_expired saying why), and the verdict is applied. A refusal goes out before the event, so the event can confess a degradation.

No Flow forest at all (generation 0, or no Flow key) is permissive, counted, and caches nothing.

Flow dispatch holds one RCU policy snapshot while checking layer presence, preparing identity facts and evaluating. The sentence retains that policy object's generation as an internal stamp alongside the existing invalidation generation, which also changes when network context changes. Both must match before either endpoint's cached verdict can be reused. A packet already evaluating an old policy may finish; its old verdict cannot remain current after a new policy is published. The extra policy stamp does not change the flow-dump ABI.

On a cache miss, Flow refreshes Network.* from the active context table for the packet's traversal interface after capturing the invalidation generation. It clears the old fields first, so removing a context makes those facts absent. Context publication swaps the table before advancing the generation; the reader's acquire of that generation precedes its context lookup. Thus a packet snapshot taken before publication cannot leave an old network verdict cached under the new generation. A context published after the captured generation makes the resulting sentence stale on the next traversal, even if that evaluation already saw the new facts. A current cached sentence needs no extra context lookup.

What the Flow forest judges is the flow view, not the packet's snapshot: a Flow fact is one identical for every packet of the flow, so ntfe_flow_view() builds it from the flow. A reply-direction packet's addresses and ports are swapped back to the original tuple (and its ICMP type replaced by the tuple's); the direction is the originator's, recorded at the first judgment along with the interface, the VLAN, the peer's MAC and the endpoints' identities (The identity facts), so a re-judgment on a reply sees exactly the facts the first judgment saw. (Found live before the fix: an inbound viewer flow re-judged on its reply packet as out, and matched outbound-ok.) A loopback flow's view takes the slot's direction. The refusal, when the verdict is one, answers the packet in hand; the event describes the flow as judged.

A normal flow has one local endpoint and one sentence, slot 0, written at the originator's seat on the first packet; the reply direction, and every later packet, reads it. Direction in the judgment is the originator's side. A loopback flow has two local endpoints and two sentences: the outbound one (slot 0) at LOCAL_OUT and the inbound one (slot 1) at LOCAL_IN, both on the same first packet, and every packet of it answers to the stricter of the two (DROP > REJECT(Refused) > REJECT(Prohibited) > PASS). The comparison is made before any refusal is sent: a REJECT overruled by the other end's DROP sends nothing, and one overruled by the other end's stricter REJECT sends that one's kind. Loopback-ness is the seat's device (IFF_LOOPBACK, snap->loopback); a stale other-endpoint sentence is not applied — it is that seat's to refresh when it next sees the flow.

The sentence #

struct peios_ntfe_sentence lives in NTFE's conntrack extension (include/linux/peios_ntfe.h), two per flow: the invalidation generation that judged (0 = empty), the generation of the policy object that judged, expires_at (epoch seconds, 0 = never), the FNV-1a-64 hash of the attributing rule's whole path (the outcome's attributed_hash: the event's attributed text is cut short, the hash never is; the same identity the tag and counter stores use for names, so the viewer resolves it against the policy), the verdict and the reject kind. Alongside: start_secs, stamped when conntrack created the entry (peios_ntfe_ct_ext_add()) — the Start.* facts — and, from the first judgment, the interface, the direction and whether the flow is loopback, for the dump.

NTFE shares conntrack extension storage with accounting and other kernel features. Its allocation sizes and offsets use 16-bit fields; the build-time capacity guard includes the NTFE payload and alignment padding for every allocation order. Adding another extension must not wrap the total length or overwrite an existing extension. These fields are kernel-internal and do not change the flow-dump ABI.

Writes take the flow's lock (ct->lock, _bh), zero the generation first, write the fields, and publish the generation last with a release store. Each slot also has a modification sequence, advanced at the start and end of every write, including a refresh under the same policy generation. The policy generation identifies the policy; it cannot detect every cache update.

Reads are lock-free on the hook path and in the flow dump. They make one attempt: an active writer or a changed modification sequence makes the sentence read as absent. Readers neither spin nor acquire the flow's lock. On a cache miss the flow is evaluated as usual. Two packets of a new flow racing on two CPUs may both evaluate; the second sentence write wins (both judged the identities the first resolution recorded, The identity facts), and the effects ran twice — the only place NTFE tolerates that, because the alternative is a lock on the fast path for a race that needs a flow's first two packets to arrive concurrently.

The cache holds the verdict only. Effects run at every evaluation of the flow and never per packet. DROP and REJECT sentences persist for the life of a flow conntrack has confirmed: a cached REJECT refuses every subsequent packet of it. A DROP or REJECT on a flow's first packet at a seat that stands before confirmation — LOCAL_IN for an inbound flow, LOCAL_OUT for an outbound one — leaves nothing to persist: nothing kills the entry, but its packet is dropped before conntrack confirms it (the refusal is filed as the entry's reply, which confirms nothing), so the unconfirmed entry dies with the packet, sentence and all. A retransmitted SYN is then a fresh flow, judged again — effects included — and refused again. So the cached refusal answers only on a confirmed flow: one re-judged mid-life, or a loopback flow's inbound end, judged at LOCAL_IN after POST_ROUTING confirmed the entry. A Refused reset to a confirmed TCP flow also moves it to conntrack's CLOSE state (nf_ct_set_closing()), whose short timeout ends it. A flow whose extension could not be allocated has nowhere to hold a sentence and is evaluated on every packet (flow_uncached).

Staleness #

A sentence is stale when its invalidation generation is not the current one (a policy published, or a network context published — Ingestion and generations — both advance the one counter), when the policy object that judged it is not the current policy object, or when t_secs >= expires_at. Both are checked lazily, on the flow's next packet — an idle flow past a policy change is killed when it next speaks, or conntrack times it out; there are no timers and no walk of the table at publication. Grandfathering was rejected: the registry must not lie about what is enforced, and a REJECT rule must be able to reject something already running. A refused packet of an established TCP flow tears down both ends at once (Seats and dispatch): the end that sent it is refused with the kind's story, and the packet, turned into a reset, is sent on to the other end. Before the teardown existed, a killed viewer stream froze at the local end while the silent host peer waited for its own next packet to meet the cached REJECT sentence — correct under the lazy law, and half a kill.

The expiry is the evaluation's expires_at (Evaluation): the earliest moment any live-time condition the judgment consulted would flip. A forest with no time conditions never expires a sentence; Start.* conditions never contribute, which is the point of them.

The flows dump #

PEIOS_NTFE_IOC_FLOWS walks conntrack's table the way ctnetlink does — local_bh_disable(), each bucket under its nf_conntrack_locks lock, original-direction entries of init_net that are neither expired nor dying  — and fills struct peios_ntfe_flow_rec per flow: conntrack's id, family, protocol, the original tuple (ports, or ICMP id and type/code), seen_reply/assured/related, the remaining lifetime, packet and byte counts (NTFE turns conntrack accounting on at init — the net.netfilter.nf_conntrack_acct sysctl, init_net.ct.sysctl_acct — since it is conntrack's consumer now), and the extension: start time, first-judgment interface and direction, loopback, both sentences, both ends' identities, and up to eight tags by hash with the flow's total tag count. Records are batched in kernel memory (32 to a batch) and copied to user between passes over the buckets, never under a lock; a bucket holding more flows than the batch has room for is walked again under its lock from where the batch filled, rather than losing the rest. The walk counts every live flow it saw so a short buffer is visible, and is best-effort against a table that changes under it.

What was decided against #

  • Backstop inheritance (the flow's verdict as the Packet layer's compiled-in default): unnecessary once Packet is the filter in front and passes tracked traffic by shipped configuration.
  • Two layers, Inbound and Outbound: direction-blind rules are common and shadowing gives the direction-specific exceptions; the posture is a visible root rule; per-seat direction pruning is a future evaluator optimisation, invisible to authors.
  • Effects on first judgment only: a kill by REJECT, REPORT(n) must report; the COUNT noise is per generation, not per packet.
  • Identity in the sentence. The sentence caches the verdict; the identities the judgment read are recorded beside it (The identity facts), not re-derived per packet.

The identity facts

Peios Kernel / Internals / NTFE

The identity facts (rung 3 on PEI-598) answer the question the address facts cannot: not where a flow goes but who on this machine is speaking or listening. They are Flow-layer facts by the same law as Related and Start.* — a flow has one answer for its whole life — and they are the first facts NTFE reads from somewhere other than the packet. KACS provides them; the engine resolves them once per flow.

What KACS stamps on a socket #

Every inet socket carries a governing identity, recorded by KACS in the socket's security state (Socket Identity): the caller's effective token — so a service thread impersonating a client attributes the socket to the client, as audit does — and the process facts of that moment: the process GUID, the thread-group id and the comm of the thread that made the stamp (a thread's own name, which need not be its process's). The stamp is taken at every act that commits the socket to a role: creation, bind, listen, connect, inheritance at accept, and KACS_SO_RESTAMP. The last stamp governs, which is how a listener handed to another program (socket activation, descriptor passing) is governed as that program's. A kernel socket is stamped as the kernel's, with no token.

The engine reads the stamp through one accessor, pkm_kacs_socket_owner() (<linux/peios_ntfe.h>), which hands it a counted reference to the token and a copy of the process facts. The facts outlive the process; the reference outlives the socket.

What stands at an end #

identity.c classifies each local end of a flow by whether anyone answers, not by whether a socket structure exists. The result is the Local fact (program, kernel, shared, none) and, for a program, the principal behind Local.*.

Outbound, at LOCAL_OUT: the sending socket's stamp. A stamped program socket is program; a kernel socket, or no socket at all (resets, ICMP errors, IGMP) is kernel.

Inbound, at LOCAL_IN, a transport lookup for the receiver of this very packet:

  • UDP to a multicast or broadcast destination is shared before any lookup: the stack delivers it to every socket bound to the port — one flow, many endpoints — and the per-program question belongs to the join, not to the packet. Local.* is absent.
  • TCP, UDP and UDP-Lite are looked up by tuple, the way the netfilter socket match does — listeners included, and through the same hash a SO_REUSEPORT group steers by, so the sentence names the socket that will actually receive. Early demux may already have found it, and its socket is used in place of the lookup — for UDP only once the datagram has passed the shared test above, since early demux also attaches the one socket a multicast datagram happens to match. An early result is used only if its socket still has a live reference that NTFE can pin. UDP early demux keeps the pointer valid under RCU but does not itself hold a reference; if the socket's last reference has gone, NTFE falls back to the ordinary tuple lookup without reviving the socket. A missing receiver then gives the same none result as an ordinary lookup miss. The temporary socket reference is released after reading the identity. Any other protocol is looked up among raw sockets bound to it.
  • A socket found is program (a request minisock stands for its listener; a TIME_WAIT minisock is nobody's: kernel).
  • Nothing found: kernel if the stack has a handler registered for the protocol — ICMP and ICMPv6 (neighbour discovery, router advertisements, MLD), IGMP, the tunnel and IPsec outers that are decapsulated and re-enter the ingress seat as their inner packet — else none, which the stack will answer with a reset or an unreachable.

The classification is a rule, not a list of protocols. Two consequences are documented rather than special-cased: SCTP, a socket transport whose table lives inside its module, reads kernel while the module is loaded; and a ping socket's echo reply pairs with the outbound request in conntrack and inherits the outbound program sentence, so the direct lookup is deferred.

The lookup runs once per flow, on the first judgment, and only when a Flow forest is published: a permissive machine pays nothing.

Loopback: both ends #

A loopback flow has two local ends and two sentences (The Flow layer). The outbound seat resolves both on the first packet — its own end from the socket, the other by running the receiver lookup early on the loopback-destined packet — and records them on the flow's extension. The inbound seat's judgment, on the same packet, reads both from there: Local.* is its own end and Remote.* the sender's. The inbound seat cannot see a loopback packet's sender itself (loopback transmission orphans the buffer), so a flow whose extension could not be allocated reads Remote as absent there, confessed. Off loopback Remote is always absent: nothing is provable about a peer yet.

Fixed for the flow's life #

The identities are recorded on the conntrack extension at the first judgment, per slot, beside the direction and the interface, and never replaced: a re-judgment after a policy change or a time edge sees the same principal, and a later restamp of the socket, a fork after accept, or a SO_REUSEPORT sibling taking over the port changes nothing for flows already judged. The extension holds one counted token reference per slot and releases it when conntrack frees the flow. Two CPUs racing on a new flow's first packets may both resolve; the first record stands — unlike the sentence, where the second write wins (The Flow layer) — and the loser releases its reference and judges the recorded identity instead of its own.

Across the bridge #

The flow view carries, per end, the kind, the process facts and a borrowed token pointer. The bridge (security/pkm/kacs/ntfe_runtime.rs) implements pnp-core's Principal trait over the token — user SID, enabled-group membership (deny-only groups are invisible to policy), integrity level, confinement SID and capabilities, the per-service SID found among the enabled groups, the process GUID as text (PCDS's string form — Data1, Data2 and Data3 read as little-endian numbers and written most significant digit first, Data4 bytes in order — lowercase and unbraced, 8-4-4-4-12; ingestion lowercases a Local.Process or Remote.Process pattern and strips braces from a braced one to match) — without copying the group list: a token may carry a thousand groups and the judgment runs in softirq context, so the snapshot borrows a view and asks membership questions of it. The view is lock-free: group SIDs are fixed at token creation and each group's attributes are an atomic.

The judgment compares SIDs and nothing else; what NTFE knows of a SID's meaning is only what pnp-core compiles into it — the service-SID derivation and a table of well-known names — used once, at ingestion, to turn a name a rule wrote into a SID. The engine holds no directory of principals and resolves no SID back to a name. Local.Service.Equal = resolvd is turned into the service's SID at ingestion by pnp-core, with the same derivation peinit and authd use to mint it (the SHA-1 of the uppercased UTF-16LE name under S-1-5-80); Local.User.Equal = LocalService by a table of well-known names. The viewer resolves the other way, from the service definitions in the registry.

What the stream says #

A Flow event and a flow record carry both ends: the kind, the process GUID, pid and comm, the user SID and the service SID (ABI 4, NTFE ABI Reference, NTFE ABI Notes). An end that could not be attributed — a socket with no KACS state, an inet socket nobody stamped, a loopback sender the inbound seat could not see — is confessed: identity_unresolved in the status, PEIOS_NTFE_EV_F_IDENTITY_UNRESOLVED on the event, and the flag on the flow record's slot.

At rest: the listeners dump #

The same stamp, read without a packet: PEIOS_NTFE_IOC_LISTENERS (listeners.c) walks the listening TCP hash and the bound UDP and UDP-Lite tables of the root namespace the way /proc/net/tcp and /proc/net/udp do — each bucket under its lock, records copied out between buckets — and reports every socket prepared to receive with the identity that governs it. It is the attack surface as a list, by whom, and it exercises the stamp before a single flow is judged.

What was decided against #

  • Identity in the per-packet layers. A packet carries no owner; the socket does. Local.* in a Packet rule is linted as never present, and Present on it refuses the generation.
  • Many sentences for a shared receiver. Inbound multicast is one flow with many endpoints; modelling N judgments would have made the join-time question a per-packet one. shared and a later gate on IP_ADD_MEMBERSHIP (C11) instead.
  • Copying the group list into the snapshot. Up to 1024 SIDs per token, in softirq: the Principal view answers membership instead.
  • Program.Trust and the image hash. PIP is under review, and unsigned binaries are not hashed at exec today; both wait.

Authoring Packet Rules

Peios Kernel / Internals / NTFE

These layouts illustrate individual patterns, not complete replacement policies. Read the existing forest and retain a local recovery path before changing live access. Registry paths below are relative to Machine\System\Network.

Apply a pattern safely #

  1. Identify the layer and the facts available at its seat. Include protocol and traffic scope in every gating rule.
  2. Choose a pattern below and adapt addresses, ports, names, and priorities. Check competing trees; a child is an exception only within its own tree.
  3. Apply the reviewed edit, then inspect the accepted kernel generation.
  4. Test the intended connection and inspect attribution and loss counters. A write or capture alone does not establish packet delivery.

Allow one inbound connection class #

Rules\Flow\inbound          Direction.Equal = in
                              Actions = REJECT
Rules\Flow\inbound\ssh-lan  Protocol.Equal = tcp, DstPort.Equal = 22
                              SrcAddr.Equal = 10.0.0.0/8
                              Actions = PASS

The child narrows the parent region. It does not bypass other layers or higher-priority trees. A rejection on an established TCP flow can terminate both endpoints; use DROP if the intended refusal is silent.

Count packets or bytes before gating a source #

Rules\Packet\dns-count  Protocol.Equal = udp, DstPort.Equal = 53
                          Actions = COUNT(dns)
Rules\Packet\dns-cap    Protocol.Equal = udp, DstPort.Equal = 53
                          Counter.dns(10s, SrcAddr).GreaterThan = 20
                          Actions = REJECT(Prohibited)

The counter rule abstains from a verdict. Matching reads the view before the current evaluation's count, and the window is approximate. Keep the protocol and port conditions on the gating rule: removing them broadens refusal to other traffic from that source.

Use COUNT(egress, Length) with an outbound packet rule for byte accounting. A threshold such as Counter.egress(1m, SrcAddr).GreaterThan = 104857600 then measures bytes, not packet count. To count connections instead, use a Flow rule with COUNT(conns); reevaluations can run that effect again.

Distinguish live time from connection start #

Rules\Flow\curfew  Direction.Equal = out
                     Start.Hour.Equal = 22-23, 0-5
                     Priority = 10
                     Actions = REJECT(Prohibited), REPORT(3)

This example restricts new outbound flows during those UTC hours. Replacing Start.Hour with Time.Hour also makes running flows subject to time-edge reevaluation. Time.* and Start.* are not interchangeable schedules.

Tag a flow and observe its reply #

Rules\Packet\tag-dns  Protocol.Equal = udp, DstPort.Equal = 53
                        Actions = TAG(dnsq, Add)
Rules\Packet\reply    Protocol.Equal = udp, SrcPort.Equal = 53
                        Tag.dnsq.GreaterThan = 0
                        Actions = REPORT(4)

A tag changes observation state, not access. Tags are flow-scoped, retain state across generations, and obey layer dependency restrictions.

Use network context deliberately #

Rules\Flow\no-ssh       Direction.Equal = in
                           Protocol.Equal = tcp, DstPort.Equal = 22
                           Actions = DROP
Rules\Flow\no-ssh\home  Network.Trust.Equal = home
                           Actions = PASS

home is an operator label on the identified network, not cryptographic proof of location. Missing context cannot satisfy that exception. Changing the context can cause a new judgment on an established flow's next packet. Interface/profile selection belongs to netd; it is not Wi-Fi association.

Peios Learn — documentation for Peios software.

Built with Trail.