# NTFE

---

# Overview

_Peios Kernel / Internals / NTFE_

> NTFE is the Peios packet engine — where it stands in the kernel, what it replaced, how its C glue and Rust core divide the work, and the terms this chapter uses.

<a id="trm-6-1"></a>

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. <a id="cite-ntfe-engine.judges-from-registry-policy-itself"></a> No userspace process is in the enforcement path; the
viewer daemon (pnpd) observes and authors, it never decides. <a id="cite-ntfe-engine.no-userspace-in-enforcement-path"></a>

<a id="trm-6-1-1"></a>

## 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. <a id="cite-ntfe-engine.keeps-hooks-conntrack-defrag-reject"></a> 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](</kernel/internals/ntfe/the-snapshot.md#trm-6-3>)) is false on every flow the stack tracks. <a id="cite-ntfe-engine.helpers-off-related-never-true"></a> 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. <a id="cite-ntfe-engine.policy-frontends-configured-out"></a> `NF_NAT` is built but
dormant. <a id="cite-ntfe-engine.nf-nat-built-but-dormant"></a> The kernel config gate (`peios/verify-config.sh`)
asserts both halves so a merge cannot quietly bring a frontend back. <a id="cite-ntfe-engine.config-gate-asserts-both-halves"></a>

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. <a id="cite-ntfe-engine.pins-conntrack-hooks-at-init"></a>

<a id="trm-6-1-2"></a>

## 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`). <a id="cite-ntfe-engine.c-glue-owns-kernel-facing-work"></a>

**`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. <a id="cite-ntfe-engine.core-owns-policy-meaning"></a> It is `no_std`, allocates only through the fallible PKM
wrappers, and has no I/O. <a id="cite-ntfe-engine.core-no-std-fallible-alloc-no-io"></a> 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). <a id="cite-ntfe-engine.core-compiles-for-cargo-and-kernel"></a> Nothing about a rule's semantics exists in C. <a id="cite-ntfe-engine.no-rule-semantics-in-c"></a>

The bridge is the only place the two meet. <a id="cite-ntfe-engine.bridge-is-only-meeting-point"></a> 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. <a id="cite-ntfe-engine.effects-applied-after-collation"></a>

<a id="trm-6-1-3"></a>

## 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; <a id="cite-ntfe-engine.generation-advances-per-ingestion"></a> 0 means nothing was ever ingested and every layer is
  permissive, loudly. <a id="cite-ntfe-engine.generation-zero-is-permissive"></a>
- **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. <a id="cite-ntfe-engine.nothing-fails-silently"></a>
- **Owner** — the identity KACS stamps on an inet socket ([Socket Identity](</kernel/internals/kacs/network-objects/socket-identity.md#trm-3-12-2>)): 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](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)).

The chapter follows a packet: the seats it meets ([Seats and dispatch](</kernel/internals/ntfe/seats-and-dispatch.md#trm-6-2>)), the snapshot
taken of it ([The snapshot](</kernel/internals/ntfe/the-snapshot.md#trm-6-3>)), how the forest judges it ([Evaluation](</kernel/internals/ntfe/evaluation.md#trm-6-4>)), where that forest
came from ([Ingestion and generations](</kernel/internals/ntfe/policy-ingestion-and-validation.md#trm-6-5>)), the stores its effects land in ([The stores](</kernel/internals/ntfe/the-stores.md#trm-6-6>)), the event that
records it ([The event stream](</kernel/internals/ntfe/event-ring-and-delivery.md#trm-6-7>)), what happens when it is the first packet of a flow
([The Flow layer](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)), and who stands at its local end ([The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)). [NTFE ABI Reference](</kernel/userspace/native/ntfe/generated-device-abi.md#trm-6-a>) is the generated
ABI of `/dev/peios-ntfe`; [NTFE ABI Notes](</kernel/userspace/native/ntfe/device-operations-and-errors.md#trm-6-b>) is what the ABI tables cannot say.

<a id="trm-6-b-8"></a>

## 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. <a id="cite-ntfe-abi-notes.config-ntfe-dependencies"></a> `CONFIG_PEIOS_NTFE_KUNIT`
builds the kernel-resident tests (`pkm_kunit_ntfe`), defaulting to
`SECURITY_PKM_KUNIT`. <a id="cite-ntfe-abi-notes.config-kunit-default"></a> The production fragment (`build/config/pkm.fragment`)
enables NTFE and configures the nf_tables/xtables family out; <a id="cite-ntfe-abi-notes.production-fragment-ntfe-on-nftables-off"></a>
`peios/verify-config.sh` asserts both. <a id="cite-ntfe-abi-notes.verify-kernel-config-asserts-fragment"></a>

## Related explanations

- [Event records and status semantics](</kernel/userspace/native/ntfe/event-records-and-status-semantics.md>)
- [Device operations and errors](</kernel/userspace/native/ntfe/device-operations-and-errors.md>)

## Calling the subsystem

The [native NTFE interface reference](</kernel/userspace/native/ntfe/overview.md>) collects the caller contracts and generated ABI tables.

---

# Seats and dispatch

_Peios Kernel / Internals / NTFE_

> The netfilter hooks NTFE stands at, the dispatch law that gives every traversal exactly one proper seat per layer, and how verdicts — refusals included — are applied where they land.

<a id="trm-6-2"></a>

<a id="trm-6-2-1"></a>

## 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`; <a id="cite-ntfe-seat.device-seats-follow-netdev-notifier"></a> because `register_netdevice_notifier()` replays
  `NETDEV_REGISTER` for devices that already exist, boot-time interfaces
  get their seats too. <a id="cite-ntfe-seat.boot-time-interfaces-get-seats"></a> These seats see frames — the Ethernet header is
  present, VLAN tags are visible, and on the inbound side conntrack has
  not yet run. <a id="cite-ntfe-seat.device-seats-see-frames"></a>
- **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. <a id="cite-ntfe-seat.ip-inbound-at-local-in-filter-priority"></a>
- **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`. <a id="cite-ntfe-seat.ip-outbound-at-local-out-filter-priority"></a>

Only `init_net` is instrumented: Peios has no container or network
namespace story yet, and the notifier ignores devices in other
namespaces. <a id="cite-ntfe-seat.only-init-net-instrumented"></a> 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.

<a id="trm-6-2-2"></a>

## The dispatch law

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

> RawPacket matches all traffic at the device seats, unconditionally. <a id="cite-ntfe-seat.rawpacket-at-device-seats-unconditionally"></a>
> The Packet layer judges every traversal exactly once, at its proper
> seat — inbound IP at the IP hook, everything outbound at egress — <a id="cite-ntfe-seat.packet-judged-exactly-once-at-proper-seat"></a>
> falling back to the ingress seat iff the traversal will never reach its
> proper seat. <a id="cite-ntfe-seat.packet-falls-back-to-ingress-iff-unreachable"></a> The Flow layer judges every tracked flow once per local
> endpoint, at the IP seats, <a id="cite-ntfe-seat.flow-judged-once-per-local-endpoint"></a> and its sentence answers for every later
> packet of the flow. <a id="cite-ntfe-seat.sentence-answers-for-later-packets"></a>

"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). <a id="cite-ntfe-seat.reaches-ip-seat-from-ethertype-and-bridge-port"></a>

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

| Seat | Layers, in traversal order |
|---|---|
| Ingress, IP frame on a plain port | `RawPacket` only (the Packet layer is *deferred* to `LOCAL_IN`) <a id="cite-ntfe-seat.ingress-ip-plain-port-rawpacket-only"></a> |
| Ingress, non-IP frame or bridge port | `RawPacket`, then `Packet` (the *fallback* judgment) <a id="cite-ntfe-seat.ingress-non-ip-or-bridge-port-rawpacket-then-packet"></a> |
| `LOCAL_IN` | `Packet`, then the flow's sentence or `Flow` <a id="cite-ntfe-seat.local-in-packet-then-flow"></a> |
| `LOCAL_OUT` | the flow's sentence or `Flow` <a id="cite-ntfe-seat.local-out-flow-only"></a> |
| Egress | `Packet`, then `RawPacket` <a id="cite-ntfe-seat.egress-packet-then-rawpacket"></a> |

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. <a id="cite-ntfe-seat.traversal-order-is-wire-order"></a> Each
per-packet layer is evaluated once per traversal, <a id="cite-ntfe-seat.per-packet-layer-once-per-traversal"></a> and the first non-`PASS`
verdict ends the traversal. <a id="cite-ntfe-seat.first-non-pass-ends-traversal"></a> A layer with no published forest is
*permissive* and counted as such — at generation 0 that is every layer. <a id="cite-ntfe-seat.unpublished-layer-permissive-and-counted"></a>

At the IP seats, a packet goes on to the flow dispatch ([The Flow layer](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)) — 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 id="cite-ntfe-seat.untracked-packet-keeps-packet-verdict"></a> a tracked packet with a current sentence gets that
sentence, <a id="cite-ntfe-seat.tracked-packet-gets-current-sentence"></a> and one without is evaluated by the Flow forest and sentenced. <a id="cite-ntfe-seat.unsentenced-flow-evaluated-and-sentenced"></a>

<a id="trm-6-2-3"></a>

## Applying a verdict

`PASS` continues to the next layer, then `NF_ACCEPT`. <a id="cite-ntfe-seat.pass-continues-then-accept"></a> `DROP` is
`NF_DROP`. <a id="cite-ntfe-seat.drop-is-nf-drop"></a> `REJECT` is `NF_DROP` plus a refusal, phrased by the kind the
rule chose and the packet's protocol: <a id="cite-ntfe-seat.reject-is-drop-plus-refusal"></a>

| Kind | IPv4 | IPv6 |
|---|---|---|
| `Refused` (default) | TCP: RST; else ICMP port-unreachable | TCP: RST; else ICMPv6 port-unreachable <a id="cite-ntfe-seat.refused-kind-rst-or-port-unreachable"></a> |
| `Prohibited` | ICMP `ICMP_PKT_FILTERED` (type 3, code 13) | ICMPv6 `ICMPV6_ADM_PROHIBITED` (type 1, code 1) <a id="cite-ntfe-seat.prohibited-kind-admin-filtered"></a> |

Every seat can refuse IP traffic — the ingress seat only on an Ethernet
device. <a id="cite-ntfe-seat.every-seat-can-refuse-ip"></a> `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: <a id="cite-ntfe-seat.refusal-attached-to-flow-and-marked"></a>

- from the **ingress** seat, to the peer on the wire — `dev_hard_header()`
  with the offending frame's MACs swapped, then `dev_queue_xmit()`; <a id="cite-ntfe-seat.ingress-refusal-sent-to-wire-peer"></a>
  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); <a id="cite-ntfe-seat.ingress-refusal-needs-ethernet"></a>
- 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()`. <a id="cite-ntfe-seat.non-ingress-refusal-routed-through-local-out"></a> Inbound, that routes the answer out to
  the peer with our address as its source; <a id="cite-ntfe-seat.inbound-refusal-routed-to-peer"></a> 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; <a id="cite-ntfe-seat.inbound-link-local-answer-routed-on-ingress"></a> 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. <a id="cite-ntfe-seat.outbound-refusal-fails-local-socket-at-once"></a> The loopback device retains
  the route the packet was sent with, so the foreign source address
  never meets source validation. <a id="cite-ntfe-seat.outbound-refusal-skips-source-validation"></a>

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. <a id="cite-ntfe-seat.refusal-built-from-network-header"></a>

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). <a id="cite-ntfe-seat.established-tcp-reject-tears-down-far-end"></a> The refused
end gets the kind's story; the far end gets the only story TCP listens
to mid-connection. Counted in `teardowns_emitted`. <a id="cite-ntfe-seat.teardowns-counted"></a> New flows and UDP
have no far end; <a id="cite-ntfe-seat.no-teardown-for-new-flow-or-udp"></a> a reset is never answered with a reset; <a id="cite-ntfe-seat.no-teardown-of-a-reset"></a> the ingress
seat has no flow facts and never tears down. <a id="cite-ntfe-seat.ingress-never-tears-down"></a>

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 id="cite-ntfe-seat.reject-degrades-to-drop-when-nothing-to-send"></a> 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. <a id="cite-ntfe-seat.first-fragment-declined-by-checksum"></a> Refusals sent are counted in
`refusals_emitted`. <a id="cite-ntfe-seat.refusals-sent-counted"></a>

<a id="trm-6-2-4"></a>

## 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); <a id="cite-ntfe-seat.refusal-bit-survives-clone-and-copy"></a> every hook checks it first and returns `NF_ACCEPT` without a
snapshot, an evaluation or an event, counting `refusals_bypassed`. <a id="cite-ntfe-seat.refusals-bypass-every-hook"></a>
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.

<a id="trm-6-2-5"></a>

## 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. <a id="cite-ntfe-seat.evaluation-failure-drops-counts-and-reports"></a> 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. <a id="cite-ntfe-seat.unbuildable-snapshot-judged-on-seat-facts"></a>

---

# The snapshot

_Peios Kernel / Internals / NTFE_

> How one traversal's facts are extracted from the sk_buff into the fixed-size seat snapshot, what the validity bits mean, and what crosses into the Rust core.

<a id="trm-6-3"></a>

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. <a id="cite-ntfe-snapshot.built-once-per-seat-never-mutated"></a>
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. <a id="cite-ntfe-snapshot.writes-invisible-to-same-evaluation"></a>

<a id="trm-6-3-1"></a>

## 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. <a id="cite-ntfe-snapshot.has-bitmask-carries-presence"></a> Address facts use
`addr_family` (0, 4 or 6) as their validity; <a id="cite-ntfe-snapshot.addr-family-is-address-validity"></a> the protocol is valid iff a
family is. <a id="cite-ntfe-snapshot.protocol-valid-iff-family"></a> Flow state uses its own `ABSENT` value; <a id="cite-ntfe-snapshot.flow-state-has-own-absent-value"></a> `flow_related` is
valid iff `flow` is. <a id="cite-ntfe-snapshot.flow-related-valid-iff-flow"></a> The bridge turns each clear bit into `None` on the
Rust side, <a id="cite-ntfe-snapshot.clear-bit-lifts-to-none"></a> and the absent-fact law makes every condition over a `None`
false. <a id="cite-ntfe-snapshot.condition-over-none-is-false"></a>

<a id="trm-6-3-2"></a>

## 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), <a id="cite-ntfe-snapshot.loopback-flag-from-iff-loopback"></a>
the packet length as the stack sees it
(`skb->len` — not the wire length), <a id="cite-ntfe-snapshot.length-is-skb-len"></a> 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), <a id="cite-ntfe-snapshot.clock-is-utc-with-iso-day-of-week"></a> kept alongside as epoch seconds (`t_secs`) for the time-flip
arithmetic ([Evaluation](</kernel/internals/ntfe/evaluation.md#trm-6-4>)) and the sentence expiry check ([The Flow layer](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)). <a id="cite-ntfe-snapshot.clock-kept-as-epoch-seconds"></a>

Then the frame: the ethertype from `skb->protocol`. <a id="cite-ntfe-snapshot.ethertype-from-skb-protocol"></a> 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. <a id="cite-ntfe-snapshot.vlan-from-frame-tag-else-device"></a>
(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`; <a id="cite-ntfe-snapshot.mac-pair-on-ethernet-with-mac-header"></a> 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. <a id="cite-ntfe-snapshot.headerless-ip-seat-gets-device-source-mac"></a> The destination
is unknown until neighbour resolution, after the seat: absent. <a id="cite-ntfe-snapshot.headerless-ip-seat-dst-mac-absent"></a>

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 id="cite-ntfe-snapshot.ipv4-facts"></a> 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. <a id="cite-ntfe-snapshot.ipv4-non-first-fragment-has-no-l4"></a>
- **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 id="cite-ntfe-snapshot.ipv6-extension-walk-bounded-eight-hops"></a> a
  fragment header sets the fragment fact, <a id="cite-ntfe-snapshot.ipv6-fragment-header-sets-fragment"></a> and a *non-first* fragment
  ends the walk with no L4 facts (there are none to read). <a id="cite-ntfe-snapshot.ipv6-non-first-fragment-has-no-l4"></a> 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. <a id="cite-ntfe-snapshot.ipv6-protocol-is-walk-terminus"></a>

Then L4, by protocol: ports for TCP, UDP and SCTP; <a id="cite-ntfe-snapshot.ports-for-tcp-udp-sctp"></a> 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); <a id="cite-ntfe-snapshot.tcp-flags-encoding"></a> type and code for ICMP and
ICMPv6. <a id="cite-ntfe-snapshot.icmp-type-and-code"></a> Every header read goes through `skb_header_pointer()`, so a
packet whose headers are paged or truncated yields absent facts rather
than a fault. <a id="cite-ntfe-snapshot.truncated-headers-yield-absent-facts"></a>

<a id="trm-6-3-3"></a>

## Flow state and the flow

At the ingress seat conntrack has not run and the flow state is
`ABSENT`; <a id="cite-ntfe-snapshot.ingress-flow-state-absent"></a> 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`. <a id="cite-ntfe-snapshot.ctinfo-maps-to-flow-state"></a> The `invalid`
value is reserved: distinguishing an incoherent packet needs conntrack's
own verdict, which this seat does not receive. <a id="cite-ntfe-snapshot.invalid-flow-state-reserved"></a>

The snapshot also carries `flow`: the `struct nf_conn *` itself (never a
template), or NULL. <a id="cite-ntfe-snapshot.flow-is-conn-never-template"></a> 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. <a id="cite-ntfe-snapshot.flow-scopes-tags-and-sentence"></a> 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. <a id="cite-ntfe-snapshot.flow-pointer-valid-for-hook"></a>

With the flow come two facts that exist only on a flow: `flow_related`
(`ct->master != NULL` — the flow was expected by another) <a id="cite-ntfe-snapshot.flow-related-is-ct-master-set"></a> 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`). <a id="cite-ntfe-snapshot.flow-start-from-extension-start-secs"></a> 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](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)) uses it to turn the packet's tuple back into the flow's. <a id="cite-ntfe-snapshot.flow-reply-marks-reply-direction"></a>

<a id="trm-6-3-4"></a>

## 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). <a id="cite-ntfe-snapshot.rust-mirror-matches-c-struct"></a> `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. <a id="cite-ntfe-snapshot.bridge-fills-tags-and-counter-views"></a> Both are
resolved *before* evaluation, against the forest being evaluated, which
is why the forest carries its name sets ([Ingestion and generations](</kernel/internals/ntfe/policy-ingestion-and-validation.md#trm-6-5>)). <a id="cite-ntfe-snapshot.machinery-facts-resolved-before-evaluation"></a>

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](</kernel/internals/ntfe/policy-ingestion-and-validation.md#trm-6-5>)): 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); <a id="cite-ntfe-snapshot.rawpacket-forest-gets-no-tags"></a> an ingress snapshot has no flow, so no tags exist to
give; <a id="cite-ntfe-snapshot.ingress-snapshot-has-no-tags"></a> 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](</kernel/internals/ntfe/policy-ingestion-and-validation.md#trm-6-5>)). <a id="cite-ntfe-snapshot.flow-only-facts-for-flow-forest-alone"></a> The clock is
given to every layer, and so is the trace of consulted time conditions
([Evaluation](</kernel/internals/ntfe/evaluation.md#trm-6-4>)); <a id="cite-ntfe-snapshot.clock-and-time-trace-given-to-every-layer"></a> only the Flow seat acts on it. <a id="cite-ntfe-snapshot.only-flow-seat-acts-on-time-trace"></a>

<a id="trm-6-3-5"></a>

## 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](</kernel/internals/ntfe/policy-ingestion-and-validation.md#trm-6-5>)) and published under RCU — and copies the entry's three
strings in, setting `HAS_NETWORK`. <a id="cite-ntfe-snapshot.context-filled-from-active-table"></a> The bridge lifts the id whenever the
bit is set, <a id="cite-ntfe-snapshot.network-id-lifted-when-bit-set"></a> and the name and trust only when non-empty (a record the
operator has not labelled). <a id="cite-ntfe-snapshot.empty-network-name-and-trust-absent"></a> 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. <a id="cite-ntfe-snapshot.no-context-entry-no-network-facts"></a> The strings are bounded (40, 64 and 32
bytes with their NUL, `PEIOS_NTFE_NETWORK_*_LEN`); <a id="cite-ntfe-snapshot.network-strings-bounded"></a> 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. <a id="cite-ntfe-snapshot.long-network-value-truncated-and-logged-once"></a>
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](</kernel/internals/ntfe/policy-ingestion-and-validation.md#trm-6-5>)). <a id="cite-ntfe-snapshot.overlong-network-id-name-ignored"></a>

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](https://learn.peios.org/peios/reference/netd/the-interface-layer/building-a-generation/)):
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. <a id="cite-ntfe-snapshot.network-facts-match-interface-layer"></a>

Flow refreshes these facts on a cache miss after capturing its cache
invalidation generation ([The Flow layer](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)), 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.

<a id="trm-6-3-6"></a>

## 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](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)) 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. <a id="cite-ntfe-snapshot.identity-fields-set-from-flow-extension"></a> The bridge lifts a program end into a
`Principal` the core's `Local.*` and `Remote.*` conditions question
([The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)); <a id="cite-ntfe-snapshot.program-end-lifts-to-principal"></a> every other snapshot leaves the fields zero, which lifts to
absent. <a id="cite-ntfe-snapshot.identity-fields-zero-elsewhere-lift-absent"></a>

---

# Evaluation

_Peios Kernel / Internals / NTFE_

> The pnp-core algorithm — trigger set, abstention and speakers, collation, the backstop — and how the bridge carries a snapshot in and a verdict plus applied effects out.

<a id="trm-6-4"></a>

Evaluation is `pnp_core::eval::evaluate(forest, snapshot, ctx)`: pure,
allocation-fallible, and the same code under cargo and in the kernel. <a id="cite-ntfe-eval.evaluate-is-pure-and-shared"></a>
Its steps are the ratified design's six, in order. <a id="cite-ntfe-eval.six-steps-in-order"></a>

<a id="trm-6-4-1"></a>

## 1. Matching

A rule matches iff it is enabled and every one of its conditions holds
against the snapshot. <a id="cite-ntfe-eval.rule-matches-iff-enabled-and-all-conditions-hold"></a> Conditions are a conjunction; a value written as a
list is a disjunction *within* that one field. <a id="cite-ntfe-eval.list-value-is-disjunction-within-field"></a> A disabled rule never
matches, so its subtree is unreachable. <a id="cite-ntfe-eval.disabled-rule-subtree-unreachable"></a>

Conditions are evaluated in the order ingestion stored them, which puts
live-time conditions (`Time.*`) **last**, <a id="cite-ntfe-eval.live-time-conditions-evaluated-last"></a> and the conjunction stops at
the first false one. <a id="cite-ntfe-eval.conjunction-stops-at-first-false"></a> 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()`): <a id="cite-ntfe-eval.reached-clock-conditions-record-next-flip"></a>
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; <a id="cite-ntfe-eval.clock-flip-scans-one-cycle-ahead"></a>
day-of-month, month and year answer "next midnight", since exact flips
need calendar arithmetic nobody has asked for. <a id="cite-ntfe-eval.calendar-fields-flip-at-next-midnight"></a> A false condition is
consulted too: a higher-priority rule that missed only on the clock may
match later. <a id="cite-ntfe-eval.false-clock-condition-is-consulted"></a> A rule whose address or port conditions fail first never
consults its clock and contributes nothing. <a id="cite-ntfe-eval.unreached-clock-condition-not-consulted"></a> The earliest consulted flip
is the evaluation's `expires_at` — the Flow layer's sentence expiry
([The Flow layer](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)); <a id="cite-ntfe-eval.expires-at-is-earliest-consulted-flip"></a> the per-packet layers compute it and ignore it. <a id="cite-ntfe-eval.per-packet-layers-ignore-expires-at"></a>

<a id="trm-6-4-2"></a>

## 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. <a id="cite-ntfe-eval.matching-child-shadows-its-parent"></a> Shadowing exists only within a lineage — two trees never shadow
each other, and their order in the forest carries no meaning. <a id="cite-ntfe-eval.trees-never-shadow-each-other"></a> The walk
returns "matched" to the parent so the parent knows it was shadowed. <a id="cite-ntfe-eval.walk-reports-match-to-parent"></a>

<a id="trm-6-4-3"></a>

## 3. Resolving a triggered rule

Every triggered rule's action list is resolved once. <a id="cite-ntfe-eval.triggered-rule-resolved-once"></a> Verdict actions fold
to the strictest listed; <a id="cite-ntfe-eval.verdict-actions-fold-to-strictest"></a> `TAG` and `COUNT` push effects; <a id="cite-ntfe-eval.tag-and-count-push-effects"></a> `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); <a id="cite-ntfe-eval.report-folds-to-highest-level-and-gates"></a> `PROMPT`
pushes a prompt-issued effect and, with no handler transport in this
release, resolves its fallback in place <a id="cite-ntfe-eval.prompt-resolves-fallback-in-place"></a> (nesting bounded by
`MAX_PROMPT_CHAIN`, 4). <a id="cite-ntfe-eval.prompt-chain-bounded-at-four"></a> Side effects always execute — they are pushed
before anyone knows whether the rule's verdict will win. <a id="cite-ntfe-eval.side-effects-execute-regardless-of-verdict"></a>

<a id="trm-6-4-4"></a>

## 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), <a id="cite-ntfe-eval.prompt-fallback-verdict-is-not-direct"></a>
and that ancestor **speaks for the region**: its full action list
resolves, once. <a id="cite-ntfe-eval.abstainer-climbs-to-nearest-verdict-ancestor"></a> A speaker reached by several abstaining descendants in
one evaluation executes only the first time (`spoken` tracks resolved
speakers by identity). <a id="cite-ntfe-eval.speaker-executes-once-per-evaluation"></a> Intermediate abstaining ancestors execute
nothing. <a id="cite-ntfe-eval.intermediate-abstainers-execute-nothing"></a> If no ancestor bears a verdict, the branch contributes nothing
and other trees or the backstop answer. <a id="cite-ntfe-eval.verdictless-branch-contributes-nothing"></a>

The attribution of a speaker's verdict is the speaker's path, not the
abstaining descendant's. <a id="cite-ntfe-eval.speaker-verdict-attributed-to-speaker"></a>

<a id="trm-6-4-5"></a>

## 5. Collation

Every yielded verdict is a candidate `(verdict, priority, path)`. <a id="cite-ntfe-eval.every-verdict-is-a-candidate"></a> The
winner has the highest priority; at equal priority the strictest
verdict: `DROP` (3) > `REJECT(Refused)` (2) > `REJECT(Prohibited)` (1) >
`PASS` (0). <a id="cite-ntfe-eval.highest-priority-then-strictest-wins"></a> 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. <a id="cite-ntfe-eval.effective-priority-inherits-from-parent"></a>

<a id="trm-6-4-6"></a>

## 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. <a id="cite-ntfe-eval.no-candidate-drops-via-flagged-backstop"></a> The backstop is
compiled in and un-deletable; <a id="cite-ntfe-eval.backstop-is-undeletable"></a> every permissive statement in a policy is
therefore a visible rule.

<a id="trm-6-4-7"></a>

## 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`. <a id="cite-ntfe-eval.evaluation-carries-every-candidate-and-effect"></a> 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), <a id="cite-ntfe-eval.count-length-is-packet-length-or-zero"></a> `Effect::Report { rule, level }`,
`Effect::PromptIssued { rule, handler }`. <a id="cite-ntfe-eval.effects-carry-name-and-hash"></a>

<a id="trm-6-4-8"></a>

## The bridge

`ntfe_rust_evaluate(forest, snap, layer, reporting_level, out)` is what
`policy.c` calls under `rcu_read_lock()`. <a id="cite-ntfe-eval.bridge-runs-under-rcu-read-lock"></a> It:

1. lifts the C snapshot ([The snapshot](</kernel/internals/ntfe/the-snapshot.md#trm-6-3>)) 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), <a id="cite-ntfe-eval.rawpacket-forest-reads-no-tags"></a>
   `peios_ntfe_counter_read()` for every view — and gives a `Flow` forest
   its own facts, `Related` and `Start.*`; <a id="cite-ntfe-eval.bridge-resolves-machinery-facts-before-eval"></a>
2. evaluates with `EvalContext { reporting_level }`; <a id="cite-ntfe-eval.bridge-passes-reporting-level"></a>
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`; <a id="cite-ntfe-eval.bridge-writes-outcome"></a>
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. <a id="cite-ntfe-eval.effects-applied-after-verdict"></a>

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, <a id="cite-ntfe-eval.count-cannot-trip-own-threshold"></a> and a `REPORT` can name the verdict. <a id="cite-ntfe-eval.report-names-the-verdict"></a> Every
allocation in 1–2 is `GFP_ATOMIC` (`pnp-core`'s `pkm_alloc` in kernel
mode); <a id="cite-ntfe-eval.bridge-allocations-are-atomic"></a> a failure returns `-ENOMEM` and the hook fails closed ([Seats and dispatch](</kernel/internals/ntfe/seats-and-dispatch.md#trm-6-2>)). <a id="cite-ntfe-eval.allocation-failure-fails-closed"></a> The
store calls never sleep. <a id="cite-ntfe-eval.store-calls-never-sleep"></a>

---

# Policy ingestion and validation

_Peios Kernel / Internals / NTFE_

> Policy ingestion and validation: behaviour and implementation of the Peios kernel.

<a id="trm-6-5"></a>

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. <a id="cite-ntfe-ingest.refused-walk-keeps-previous-generation"></a> The same walk reads netd's inventory beside the rules into
the network context table ([The snapshot](</kernel/internals/ntfe/the-snapshot.md#trm-6-3>)), <a id="cite-ntfe-ingest.walk-reads-inventory-with-rules"></a> 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.

<a id="trm-6-5-1"></a>

## Discovery and change notification

At LCS bootstrap, NTFE's key is discovered fifth alongside the other
kernel-owned subtrees: <a id="cite-ntfe-ingest.key-discovered-at-bootstrap"></a> `pkm_lcs_walk_absolute_components()` resolves
`Machine\System\Network` (the leading `Machine` hive component is
resolved locally against the hive root, not round-tripped), <a id="cite-ntfe-ingest.machine-component-resolved-locally"></a> and its
absence is not an error — no key, no policy and no context, generation
stays where it is. <a id="cite-ntfe-ingest.absent-network-key-is-not-an-error"></a> 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: <a id="cite-ntfe-ingest.one-unbounded-watch-on-network-key"></a> `Rules\`, `Interfaces\` and
`Networks\` beneath it are what NTFE reads; <a id="cite-ntfe-ingest.ntfe-reads-rules-interfaces-networks"></a> `Profiles\` and `Dns\` are
netd's and resolvd's, and a write there fires the watch and costs a
walk that publishes nothing. <a id="cite-ntfe-ingest.foreign-subtree-write-publishes-nothing"></a>

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 id="cite-ntfe-ingest.rewalk-debounced-50ms"></a> 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. <a id="cite-ntfe-ingest.burst-yields-one-rewalk"></a> 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. <a id="cite-ntfe-ingest.walks-serialized-under-mutex"></a>

<a id="trm-6-5-2"></a>

## 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 id="cite-ntfe-ingest.rules-stage-then-context-stage"></a> a failure in the first does not skip the
second, and the walk reports the first error. <a id="cite-ntfe-ingest.rules-failure-does-not-skip-context"></a> No `Rules` key leaves the
previous generation standing, exactly as a walk that refused would. <a id="cite-ntfe-ingest.absent-rules-key-keeps-generation"></a>

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); <a id="cite-ntfe-ingest.reporting-level-type-and-range"></a>
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); <a id="cite-ntfe-ingest.kernel-reads-three-layer-keys-only"></a>
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, <a id="cite-ntfe-ingest.rule-read-is-two-round-trips"></a> 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. <a id="cite-ntfe-ingest.walk-bounded-depth-12-and-4096-rules"></a>

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. <a id="cite-ntfe-ingest.registry-type-lowering"></a> Any other type in a rule
refuses the walk: <a id="cite-ntfe-ingest.other-value-type-refuses-walk"></a> 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`. <a id="cite-ntfe-ingest.wrong-length-integer-refuses-walk"></a>

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). <a id="cite-ntfe-ingest.rules-input-digested"></a> 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. <a id="cite-ntfe-ingest.unchanged-digest-publishes-nothing"></a> 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. <a id="cite-ntfe-ingest.inventory-write-changes-no-generation"></a>

<a id="trm-6-5-2-1"></a>

### 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: <a id="cite-ntfe-ingest.context-table-at-most-64-entries"></a>

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), <a id="cite-ntfe-ingest.overlong-network-id-ignored-once-loudly"></a> 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), <a id="cite-ntfe-ingest.unreadable-name-or-trust-is-empty"></a> up to 256 records; <a id="cite-ntfe-ingest.network-records-up-to-256"></a>
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). <a id="cite-ntfe-ingest.interface-status-read"></a> Both present make an entry, joined to the record
   of that id for its name and trust; <a id="cite-ntfe-ingest.interface-entry-joins-network-record"></a> either absent — no link, no
   offer yet, an `IGNORE`d or `DOWN` interface — makes none. <a id="cite-ntfe-ingest.incomplete-status-makes-no-entry"></a>

Nothing in the stage refuses a generation. <a id="cite-ntfe-ingest.context-stage-never-refuses"></a> 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; <a id="cite-ntfe-ingest.unreadable-record-skipped"></a>
an interface beyond the 64th carries no context, <a id="cite-ntfe-ingest.interface-beyond-64th-has-no-context"></a> a value
longer than its field is truncated with one warning. <a id="cite-ntfe-ingest.overlong-context-value-truncated"></a> 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. <a id="cite-ntfe-ingest.unreadable-list-keeps-previous-table"></a> Otherwise the table goes to `peios_ntfe_context_publish()` ([The snapshot](</kernel/internals/ntfe/the-snapshot.md#trm-6-3>)): if it equals the active
one entry for entry it is freed and nothing happens; <a id="cite-ntfe-ingest.equal-context-table-publishes-nothing"></a> 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. <a id="cite-ntfe-ingest.changed-context-table-advances-generation"></a> 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](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)), the same path a rule change takes. <a id="cite-ntfe-ingest.context-change-rejudges-flows-on-next-packet"></a>

<a id="trm-6-5-3"></a>

## 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](</kernel/internals/ntfe/evaluation.md#trm-6-4>)), <a id="cite-ntfe-ingest.build-orders-live-time-conditions-last"></a> resolves priority inheritance, <a id="cite-ntfe-ingest.build-resolves-priority-inheritance"></a> 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), <a id="cite-ntfe-ingest.layer-impossible-facts-lint-not-refuse"></a> 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. <a id="cite-ntfe-ingest.build-collects-name-sets"></a> Views are deduplicated and
conditions refer to them by index — that index is what the bridge uses
when it fills `counter_views` ([The snapshot](</kernel/internals/ntfe/the-snapshot.md#trm-6-3>)). <a id="cite-ntfe-ingest.views-deduplicated-and-indexed"></a>

Refusals, each carrying the offending rule's path (`BuildError`):
unknown fact, <a id="cite-ntfe-ingest.refuse-unknown-fact"></a> unsupported operator, <a id="cite-ntfe-ingest.refuse-unsupported-operator"></a> unparsable pattern, <a id="cite-ntfe-ingest.refuse-unparsable-pattern"></a> 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 id="cite-ntfe-ingest.refuse-unparsable-counter-view"></a>
a non-list `Actions`,
<a id="cite-ntfe-ingest.refuse-non-list-actions"></a> an
unparsable action, <a id="cite-ntfe-ingest.refuse-unparsable-action"></a> a `REJECT` kind that is not `Refused` or
`Prohibited`, <a id="cite-ntfe-ingest.refuse-unknown-reject-kind"></a> a `PROMPT` chain nested deeper than `MAX_PROMPT_CHAIN`
(4), refused as an unparsable action, <a id="cite-ntfe-ingest.refuse-prompt-chain-too-deep"></a> 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 id="cite-ntfe-ingest.refuse-action-not-at-layer"></a> 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 id="cite-ntfe-ingest.refuse-present-never-at-layer"></a> a `Priority` that is not an integer, <a id="cite-ntfe-ingest.refuse-non-integer-priority"></a> an `Enabled` that is
not 0 or 1, <a id="cite-ntfe-ingest.refuse-enabled-not-0-or-1"></a> a rule name that is empty or contains a path separator <a id="cite-ntfe-ingest.refuse-rule-name-with-path-separator"></a>
(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. <a id="cite-ntfe-ingest.refuse-name-hash-collision"></a>

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; <a id="cite-ntfe-ingest.hashes-distinct-across-forests"></a> 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; <a id="cite-ntfe-ingest.refuse-view-without-writer"></a> 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. <a id="cite-ntfe-ingest.refuse-downward-tag-read"></a>

## Related explanations

- [Generation publication and recovery](</kernel/internals/ntfe/generation-publication-and-recovery.md>)

---

# Generation publication and recovery

_Peios Kernel / Internals / NTFE_

> Generation publication and recovery: behaviour and implementation of the Peios kernel.

<a id="trm-6-5-4"></a>

## Publication

`peios_ntfe_policy_publish(packet, raw, flow, reporting_level)` is
process context under a mutex. <a id="cite-ntfe-ingest.publish-serialized-under-mutex"></a> It runs the cross-forest check, then
materializes the counter store for the union of every forest's views
([The stores](</kernel/internals/ntfe/the-stores.md#trm-6-6>)) — so a store that cannot be built (allocation, more than eight
windows on one table) refuses the generation before anything is
swapped. <a id="cite-ntfe-ingest.unbuildable-counter-store-refuses-generation"></a> 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. <a id="cite-ntfe-ingest.generation-advances-only-after-checks"></a> Hook-path
readers dereference it under `rcu_read_lock()` and never block; <a id="cite-ntfe-ingest.hook-readers-never-block"></a> they see
the old generation or the new one, never a mix. <a id="cite-ntfe-ingest.readers-never-see-mixed-generation"></a> The old policy is
released by `call_rcu()`, and its forests by `ntfe_rust_forest_free()` in
the callback after grace. <a id="cite-ntfe-ingest.old-policy-freed-after-grace"></a>

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 id="cite-ntfe-ingest.walk-outcome-in-status"></a> A refusal leaves the previous generation active and says so in
the kernel log. <a id="cite-ntfe-ingest.refusal-logged-and-previous-stays-active"></a> `contexts` in the status is the number of interfaces in
the active context table. <a id="cite-ntfe-ingest.status-contexts-counts-interfaces"></a>

<a id="trm-6-5-4-1"></a>

### In the event stream

NTFE writes its own lifecycle to KMES, origin class `KMES_ORIGIN_NTFE`
(4), beside the reports of [The stores](</kernel/internals/ntfe/the-stores.md#trm-6-6>). Every publication writes one
`ntfe.policy.published`, after the swap; a refusal writes none. <a id="cite-ntfe-ingest.publish-emits-policy-published"></a>
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 id="cite-ntfe-ingest.published-event-payload"></a> A walk
whose digest is unchanged publishes nothing, and so writes nothing. <a id="cite-ntfe-ingest.unchanged-walk-writes-no-published-event"></a>
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`. <a id="cite-ntfe-ingest.refusal-emits-policy-rejected"></a>
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`. <a id="cite-ntfe-ingest.rejected-event-payload"></a>

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. <a id="cite-ntfe-ingest.build-refusal-reason-crosses-bridge"></a> 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 id="cite-ntfe-ingest.walk-refusal-reasons"></a>

A walk that finds no `Rules` key writes the event too, with reason
`no-rules-key`, no `errno` and no rule. <a id="cite-ntfe-ingest.absent-rules-key-emits-rejected"></a>

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. <a id="cite-ntfe-ingest.repeated-refusal-written-once"></a>
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.

<a id="trm-6-5-4-2"></a>

### In force

A registry write that has returned is delivered, not enforced: the walk
that reads it runs after the debounce. <a id="cite-ntfe-ingest.returned-write-not-yet-enforced"></a> Two status counters say which a
writer is looking at. `changes_noted` is incremented by
`peios_ntfe_network_registry_changed()` for every watch event, <a id="cite-ntfe-ingest.changes-noted-counts-watch-events"></a> 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. <a id="cite-ntfe-ingest.writer-sees-own-change-noted"></a> 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. <a id="cite-ntfe-ingest.changes-walked-set-from-pre-walk-noted"></a>

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 id="cite-ntfe-ingest.in-force-when-walked-reaches-noted"></a> 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 id="cite-ntfe-ingest.mid-walk-change-rearms-work"></a> A refused walk still advances `changes_walked`; <a id="cite-ntfe-ingest.refused-walk-advances-changes-walked"></a> 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. <a id="cite-ntfe-ingest.bootstrap-walk-moves-neither-counter"></a> `net policy wait` is this loop.

<a id="trm-6-5-5"></a>

## Generation 0

Until the first successful ingestion there is no policy at all, and
every layer is permissive: <a id="cite-ntfe-ingest.generation-zero-is-permissive"></a> `judged` stays 0, `permissive` counts
traversals, no events are emitted (there is no decision to attribute),
and the status reports `enforcing = 0`. <a id="cite-ntfe-ingest.generation-zero-status-and-no-events"></a> 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](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)). <a id="cite-ntfe-ingest.new-generation-stales-sentences-without-flow-walk"></a> 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_

> The three machinery stores behind NTFE's effects — flow tags on a conntrack extension, counter tables materialized from the forest's views, and REPORT emission into KMES — with their bounds and confessions.

<a id="trm-6-6"></a>

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.

<a id="trm-6-6-1"></a>

## Identities

Tag and stream names cross into the stores as 64-bit **FNV-1a hashes**
(`pnp_core::hash::name_hash`). <a id="cite-ntfe-store.names-cross-as-fnv1a-hashes"></a> 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. <a id="cite-ntfe-store.stores-hold-no-strings-or-generations"></a> Two
consequences: tags survive policy reloads by construction (the table
knows nothing to invalidate), <a id="cite-ntfe-store.tags-survive-policy-reload"></a> 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](</kernel/internals/ntfe/policy-ingestion-and-validation.md#trm-6-5>)). <a id="cite-ntfe-store.colliding-names-refuse-generation"></a> 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.

<a id="trm-6-6-2"></a>

## 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`), <a id="cite-ntfe-store.ct-extension-added-at-flow-creation"></a> with
the pointer NULL until the flow's first `TAG`. <a id="cite-ntfe-store.tag-table-null-until-first-tag"></a> 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](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)) — 88 bytes per flow, most of it the sentences — <a id="cite-ntfe-store.ct-extension-holds-start-and-sentences"></a> 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 id="cite-ntfe-store.first-tag-allocates-eight-entries"></a> a full table is replaced by one twice the size —
copy, `rcu_assign_pointer()`, `kfree_rcu()` the old — <a id="cite-ntfe-store.full-tag-table-doubles"></a> up to the tripwire
of 64 distinct tags per flow. <a id="cite-ntfe-store.tag-tripwire-64-per-flow"></a> Readers walk the table under RCU with no
lock (the hook path already holds the read lock); <a id="cite-ntfe-store.tag-readers-lockless-under-rcu"></a> writers serialize on
the flow's own `ct->lock`. <a id="cite-ntfe-store.tag-writers-serialize-on-ct-lock"></a> `Clear` tombstones an entry (`present = 0`)
rather than compacting, so a concurrent reader never sees the table
shift under it, <a id="cite-ntfe-store.clear-tombstones-without-compacting"></a> and a later `Set` reuses the slot. <a id="cite-ntfe-store.set-reuses-tombstoned-slot"></a> `Add` saturates at
`U64_MAX`. <a id="cite-ntfe-store.tag-add-saturates"></a> 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. <a id="cite-ntfe-store.tag-entry-published-before-length"></a>

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. <a id="cite-ntfe-store.tag-table-freed-after-grace-on-flow-death"></a>

Confessions: `tag_writes` (ops applied), <a id="cite-ntfe-store.tag-writes-counts-applied-ops"></a> `tag_untracked` (a `TAG` on a
packet with no flow — untracked traffic, or the ingress seat — is a
no-op), <a id="cite-ntfe-store.tag-without-flow-is-untracked-no-op"></a> `tag_refused` (the tripwire, an allocation failure, or a flow
whose extension could not be allocated at creation). <a id="cite-ntfe-store.tag-refused-confessions"></a> Clearing an absent
tag is a no-op, not a refusal. <a id="cite-ntfe-store.clearing-absent-tag-is-no-op"></a>

<a id="trm-6-6-3"></a>

## 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](</kernel/internals/ntfe/policy-ingestion-and-validation.md#trm-6-5>)) 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 id="cite-ntfe-store.one-table-per-stream-and-key-spec"></a> A `COUNT`
increments every table of its stream; <a id="cite-ntfe-store.count-increments-every-table-of-stream"></a> 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 id="cite-ntfe-store.table-is-1024-bucket-hash-under-bh-lock"></a> 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 id="cite-ntfe-store.cell-key-holds-only-named-facts"></a> 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`) <a id="cite-ntfe-store.count-without-key-fact-no-ops"></a> and its view reads absent — the absent-fact law on
both sides. <a id="cite-ntfe-store.view-without-key-fact-reads-absent"></a>

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 id="cite-ntfe-store.ring-is-eight-period-stamped-buckets"></a> A write zeroes a bucket whose stamp is stale
before adding; <a id="cite-ntfe-store.write-zeroes-stale-bucket"></a> a read sums the buckets whose stamp is within the last
eight periods. <a id="cite-ntfe-store.read-sums-last-eight-periods"></a> Advancement is lazy — there are no timers — and the
window is an approximation up to one bucket wide, by design. <a id="cite-ntfe-store.window-approximate-to-one-bucket"></a>

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

The store outlives generations. <a id="cite-ntfe-store.counter-store-outlives-generations"></a> Re-publication keeps tables whose window
set did not change, <a id="cite-ntfe-store.republish-keeps-unchanged-tables"></a> creates new ones, <a id="cite-ntfe-store.republish-creates-new-tables"></a> **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), <a id="cite-ntfe-store.republish-migrates-changed-tables"></a> and retires tables no forest views any more — `list_del_rcu()`
then free after grace, cells included. <a id="cite-ntfe-store.republish-retires-unviewed-tables"></a> Reads on the packet path walk the
table list and the cell lists under RCU; <a id="cite-ntfe-store.counter-reads-under-rcu"></a> 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. <a id="cite-ntfe-store.counters-ioctl-dumps-every-cell"></a> 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. <a id="cite-ntfe-store.counters-dump-is-best-effort"></a>

<a id="trm-6-6-4"></a>

## Reports

`REPORT(level)` at or above `CurrentReportingLevel` becomes one KMES event:
origin class `KMES_ORIGIN_NTFE` (4), event type `ntfe.verdict.reported`, <a id="cite-ntfe-store.report-becomes-one-kmes-event"></a> 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 id="cite-ntfe-store.report-payload-keys"></a> 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. <a id="cite-ntfe-store.report-omits-absent-packet-keys"></a>

The payload is built on the stack (512 bytes) <a id="cite-ntfe-store.report-payload-built-on-stack"></a> 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. <a id="cite-ntfe-store.report-long-rule-cut-and-said"></a> 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. <a id="cite-ntfe-store.reports-emitted-counts-ring-arrivals"></a>

---

# Event ring and delivery

_Peios Kernel / Internals / NTFE_

> Event ring and delivery: behaviour and implementation of the Peios kernel.

<a id="trm-6-7"></a>

Every real evaluation — a published forest judged the traversal, or a
fail-closed drop — appends one `struct peios_ntfe_event` to a bounded
ring. <a id="cite-ntfe-stream.each-evaluation-appends-one-event"></a> Permissive traversals emit nothing: there is no decision to
attribute, and the status tells that story instead. <a id="cite-ntfe-stream.permissive-emits-no-event"></a> A packet answered by
its flow's cached sentence emits nothing either: there was no
evaluation, and `flow_cached` counts it. <a id="cite-ntfe-stream.cached-sentence-emits-no-event"></a> The layouts are in [NTFE ABI Reference](</kernel/userspace/native/ntfe/generated-device-abi.md#trm-6-a>); this
page is what they mean.

<a id="trm-6-7-2"></a>

## The ring and its reader

The ring holds 4096 events under a spinlock (`irqsave`: emission happens
in softirq). <a id="cite-ntfe-stream.ring-4096-events-irqsave-lock"></a> 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. <a id="cite-ntfe-stream.full-ring-overwrites-oldest"></a>

`/dev/peios-ntfe` is a misc device, mode 0600. <a id="cite-ntfe-stream.device-misc-mode-0600"></a> 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, <a id="cite-ntfe-stream.device-many-openers"></a> but the ring has one drain: the first
file to `read()` claims it until it closes, and another file's `read()`
returns `-EBUSY` meanwhile. <a id="cite-ntfe-stream.first-reader-claims-ring-others-ebusy"></a> `read()` returns whole
records only, up to 64 per call, <a id="cite-ntfe-stream.read-whole-records-up-to-64"></a> and blocks on an empty ring unless
`O_NONBLOCK`; <a id="cite-ntfe-stream.read-blocks-unless-nonblock"></a> `poll()` raises `POLLIN` when events wait. <a id="cite-ntfe-stream.poll-pollin-when-events-wait"></a> A reader that
reconnects resumes from whatever the ring still holds, and catches the
gap from the sequence numbers. <a id="cite-ntfe-stream.reconnect-resumes-from-ring"></a>

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. <a id="cite-ntfe-stream.viewer-hides-own-port-events"></a>

## Related explanations

- [Event records and status semantics](</kernel/userspace/native/ntfe/event-records-and-status-semantics.md>)

---

# The Flow layer

_Peios Kernel / Internals / NTFE_

> The second rung — one judgment per local endpoint of a flow, cached on the conntrack entry as a sentence, re-judged when the policy or the clock makes it stale, and dumped for the viewer.

<a id="trm-6-8"></a>

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. <a id="cite-ntfe-flow.decisions-run-once-per-connection"></a>

<a id="trm-6-8-1"></a>

## 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](</kernel/internals/ntfe/seats-and-dispatch.md#trm-6-2>)). <a id="cite-ntfe-flow.dispatch-after-packet-pass"></a>
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 id="cite-ntfe-flow.untracked-packet-keeps-packet-verdict"></a> 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`); <a id="cite-ntfe-flow.current-sentence-applied-without-evaluation"></a>
- 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 id="cite-ntfe-flow.stale-sentence-evaluated-and-rewritten"></a> A refusal goes out before the event, so the event can confess
  a degradation. <a id="cite-ntfe-flow.refusal-sent-before-event"></a>

No Flow forest at all (generation 0, or no `Flow` key) is permissive,
counted, and caches nothing. <a id="cite-ntfe-flow.no-forest-permissive-uncached"></a>

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 id="cite-ntfe-flow.judges-flow-view-not-packet"></a> A reply-direction packet's
addresses and ports are swapped back to the original tuple (and its
ICMP type replaced by the tuple's); <a id="cite-ntfe-flow.reply-view-uses-original-tuple"></a> 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](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)), so a re-judgment on a
reply sees exactly the facts the first judgment saw. <a id="cite-ntfe-flow.rejudgment-sees-first-judgment-facts"></a> (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. <a id="cite-ntfe-flow.loopback-view-takes-slot-direction"></a> The refusal, when the
verdict is one, answers the packet in hand; <a id="cite-ntfe-flow.refusal-answers-packet-in-hand"></a> the event describes the flow
as judged. <a id="cite-ntfe-flow.event-describes-flow-as-judged"></a>

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. <a id="cite-ntfe-flow.normal-flow-one-sentence-slot-0"></a> `Direction` in the judgment is the
originator's side. <a id="cite-ntfe-flow.direction-is-originator-side"></a> 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, <a id="cite-ntfe-flow.loopback-two-sentences-same-first-packet"></a> and every packet
of it answers to the *stricter* of the two (DROP > REJECT(Refused) >
REJECT(Prohibited) > PASS). <a id="cite-ntfe-flow.loopback-stricter-sentence-applies"></a> 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. <a id="cite-ntfe-flow.loopback-stricter-decided-before-refusal"></a> Loopback-ness is the seat's device
(`IFF_LOOPBACK`, `snap->loopback`); <a id="cite-ntfe-flow.loopback-by-seat-device"></a> a stale other-endpoint sentence is
not applied — it is that seat's to refresh when it next sees the flow. <a id="cite-ntfe-flow.stale-other-slot-not-applied"></a>

<a id="trm-6-8-2"></a>

## 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. <a id="cite-ntfe-flow.sentence-fields"></a> Alongside: `start_secs`, stamped when
conntrack created the entry (`peios_ntfe_ct_ext_add()`) — the `Start.*`
facts — <a id="cite-ntfe-flow.start-secs-stamped-at-ct-creation"></a> and, from the first judgment, the interface, the direction and
whether the flow is loopback, for the dump. <a id="cite-ntfe-flow.extension-records-first-judgment-facts"></a>

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. <a id="cite-ntfe-flow.sentence-write-publishes-generation-last"></a> 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. <a id="cite-ntfe-flow.torn-sentence-reads-absent"></a> 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](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)), 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. <a id="cite-ntfe-flow.first-packet-race-second-write-wins"></a>

The cache holds the verdict only. <a id="cite-ntfe-flow.cache-holds-verdict-only"></a> Effects run at every evaluation of the
flow and never per packet. <a id="cite-ntfe-flow.effects-per-evaluation-not-per-packet"></a> `DROP` and `REJECT` sentences persist for the
life of a flow conntrack has confirmed: a cached `REJECT` refuses every
subsequent packet of it. <a id="cite-ntfe-flow.drop-reject-sentences-persist"></a> 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. <a id="cite-ntfe-flow.new-flow-drop-reject-kills-entry"></a> 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 id="cite-ntfe-flow.refused-tcp-flow-set-closing"></a> A flow whose extension could not be allocated has nowhere to hold
a sentence and is evaluated on every packet (`flow_uncached`). <a id="cite-ntfe-flow.no-extension-evaluated-per-packet"></a>

<a id="trm-6-8-3"></a>

## 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](</kernel/internals/ntfe/policy-ingestion-and-validation.md#trm-6-5>) — both
advance the one counter), when the policy object that judged it is not
the current policy object, or when `t_secs >= expires_at`. <a id="cite-ntfe-flow.stale-by-generation-or-expiry"></a> 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. <a id="cite-ntfe-flow.staleness-checked-lazily"></a> 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](</kernel/internals/ntfe/seats-and-dispatch.md#trm-6-2>)): 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. <a id="cite-ntfe-flow.refused-established-tcp-teardown-both-ends"></a> 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](</kernel/internals/ntfe/evaluation.md#trm-6-4>)): the earliest moment
any live-time condition the judgment *consulted* would flip. <a id="cite-ntfe-flow.expiry-earliest-consulted-flip"></a> A forest
with no time conditions never expires a sentence; <a id="cite-ntfe-flow.no-time-conditions-never-expires"></a> `Start.*` conditions
never contribute, which is the point of them. <a id="cite-ntfe-flow.start-conditions-never-contribute-expiry"></a>

<a id="trm-6-8-4"></a>

## 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 <a id="cite-ntfe-flow.dump-walks-live-original-entries"></a> — 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), <a id="cite-ntfe-flow.init-enables-conntrack-acct"></a> 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. <a id="cite-ntfe-flow.dump-record-contents"></a>
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. <a id="cite-ntfe-flow.dump-copies-out-between-buckets"></a> 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. <a id="cite-ntfe-flow.dump-counts-every-live-flow"></a>

<a id="trm-6-8-5"></a>

## 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](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)), not
  re-derived per packet.

---

# The identity facts

_Peios Kernel / Internals / NTFE_

> The third rung — who stands at each local end of a flow, read once from the socket KACS stamped, fixed for the flow's life, and judged as the Flow layer's Local and Remote facts.

<a id="trm-6-9"></a>

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.

<a id="trm-6-9-1"></a>

## What KACS stamps on a socket

Every inet socket carries a **governing identity**, recorded by KACS in
the socket's security state ([Socket Identity](</kernel/internals/kacs/network-objects/socket-identity.md#trm-3-12-2>)): 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). <a id="cite-ntfe-identity.socket-stamp-effective-token-and-process-facts"></a> 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`. <a id="cite-ntfe-identity.stamp-taken-at-role-acts"></a> The
last stamp governs, which is how a listener handed to another program
(socket activation, descriptor passing) is governed as that program's. <a id="cite-ntfe-identity.last-stamp-governs"></a>
A kernel socket is stamped as the kernel's, with no token. <a id="cite-ntfe-identity.kernel-socket-stamped-without-token"></a>

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. <a id="cite-ntfe-identity.owner-accessor-counted-ref-and-copy"></a> The
facts outlive the process; the reference outlives the socket. <a id="cite-ntfe-identity.facts-outlive-process-and-socket"></a>

<a id="trm-6-9-2"></a>

## 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.*`. <a id="cite-ntfe-identity.local-fact-kinds"></a>

**Outbound**, at `LOCAL_OUT`: the sending socket's stamp. A stamped
program socket is `program`; <a id="cite-ntfe-identity.outbound-stamped-socket-program"></a> a kernel socket, or no socket at all
(resets, ICMP errors, IGMP) is `kernel`. <a id="cite-ntfe-identity.outbound-kernel-or-no-socket-kernel"></a>

**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. <a id="cite-ntfe-identity.inbound-multicast-broadcast-udp-shared"></a>
- 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. <a id="cite-ntfe-identity.inbound-transport-lookup-by-tuple"></a> 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. <a id="cite-ntfe-identity.early-receiver-pin-or-lookup"></a>
  Any other protocol is looked up among raw sockets bound to it. <a id="cite-ntfe-identity.inbound-other-protocol-raw-lookup"></a>
- A socket found is `program` (a request minisock stands for its
  listener; a `TIME_WAIT` minisock is nobody's: `kernel`). <a id="cite-ntfe-identity.inbound-found-socket-program"></a>
- 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. <a id="cite-ntfe-identity.inbound-nothing-found-kernel-or-none"></a>

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; <a id="cite-ntfe-identity.sctp-reads-kernel"></a> 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. <a id="cite-ntfe-identity.ping-reply-inherits-outbound-sentence"></a>

The lookup runs **once per flow**, on the first judgment, and only when
a `Flow` forest is published: a permissive machine pays nothing. <a id="cite-ntfe-identity.lookup-once-per-flow-only-with-flow-forest"></a>

<a id="trm-6-9-3"></a>

## Loopback: both ends

A loopback flow has two local ends and two sentences ([The Flow layer](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)). 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. <a id="cite-ntfe-identity.loopback-outbound-seat-resolves-both-ends"></a>
The inbound seat's judgment, on the same packet, reads both from there:
`Local.*` is its own end and `Remote.*` the sender's. <a id="cite-ntfe-identity.loopback-inbound-local-own-remote-sender"></a> 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. <a id="cite-ntfe-identity.loopback-no-extension-remote-absent-confessed"></a> Off loopback `Remote` is
always absent: nothing is provable about a peer yet. <a id="cite-ntfe-identity.remote-absent-off-loopback"></a>

<a id="trm-6-9-4"></a>

## 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. <a id="cite-ntfe-identity.fixed-at-first-judgment"></a> The extension holds one counted token
reference per slot and releases it when conntrack frees the flow. <a id="cite-ntfe-identity.token-ref-per-slot-released-on-free"></a> 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](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)) — and the loser releases its reference and judges the recorded
identity instead of its own. <a id="cite-ntfe-identity.resolve-race-first-record-stands"></a>

<a id="trm-6-9-5"></a>

## Across the bridge

The flow view carries, per end, the kind, the process facts and a
borrowed token pointer. <a id="cite-ntfe-identity.flow-view-carries-borrowed-token"></a> 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), <a id="cite-ntfe-identity.deny-only-groups-invisible"></a> 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. <a id="cite-ntfe-identity.principal-view-without-copying-groups"></a> The view is lock-free: group SIDs are fixed at token
creation and each group's attributes are an atomic. <a id="cite-ntfe-identity.principal-view-lock-free"></a>

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. <a id="cite-ntfe-identity.no-sid-meaning-in-kernel"></a> `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`); <a id="cite-ntfe-identity.service-name-to-sid-at-ingestion"></a> `Local.User.Equal =
LocalService` by a table of well-known names. <a id="cite-ntfe-identity.well-known-user-names-by-table"></a> The viewer resolves the
other way, from the service definitions in the registry. <a id="cite-ntfe-identity.viewer-resolves-sids-from-registry"></a>

<a id="trm-6-9-6"></a>

## 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](</kernel/userspace/native/ntfe/generated-device-abi.md#trm-6-a>),
[NTFE ABI Notes](</kernel/userspace/native/ntfe/device-operations-and-errors.md#trm-6-b>)). <a id="cite-ntfe-identity.event-and-record-carry-both-ends"></a> 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. <a id="cite-ntfe-identity.unattributed-end-confessed"></a>

<a id="trm-6-9-7"></a>

## 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. <a id="cite-ntfe-identity.listeners-dump-reports-receivers-with-identity"></a> It is the attack surface as a list, by whom,
and it exercises the stamp before a single flow is judged.

<a id="trm-6-9-8"></a>

## 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, <a id="cite-ntfe-identity.local-in-packet-rule-linted-never-present"></a>
  and `Present` on it refuses the generation. <a id="cite-ntfe-identity.present-local-in-packet-rule-refuses-generation"></a>
- **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_

> Adapt exception, counting, and time-based policy patterns while checking the complete rule forest.

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

```text
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

```text
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

```text
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

```text
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

```text
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.
