# Kernel network policy for process sandboxes

With kernel network policy on, a process sandbox gets the egress policy a container gets with the
host firewall loaded, enforced in the kernel. This page is for operators and reviewers: where the
policy is on, what a sandbox can and can't reach, how the programs work, and how to read their
counters.

A process sandbox shares its host's network stack. Where the host lets `hermitboxd` attach eBPF
programs to a cgroup of its own, each process sandbox gets its own cgroup and a small set of
programs. They decide, in the kernel, every destination it dials. Where the host can't give it,
the guarantee is off and the process tier is exactly what [process-tier.md](https://docs.hermitbox.dev/v0.3.2/reference/process-tier.md)
describes.

## Where it is on

`hermitboxd probe --json` and `hermitbox doctor` report the `kernel-network-policy` capability. It
is proved, not read. `hermitboxd` makes a disposable child of its own cgroup v2 directory and loads
every program (the kernel's verifier is the safety proof). It attaches each, starts a process into
the cgroup, then removes everything. It is on for:

| Host | Cgroup | Pins |
| --- | --- | --- |
| `hermitboxd` as root, the server preset's `hermitboxd.service` included | a child of `hermitboxd`'s own cgroup | `/sys/fs/bpf/hermitbox` |
| an ordinary user with CAP_BPF and CAP_NET_ADMIN and a delegated cgroup (systemd `Delegate=yes`) | a child of the delegated cgroup | a `hermitbox` directory it owns on a BPF filesystem |

It is off, with the reason and what would turn it on, in any of these cases:

- Without cgroup v2.
- Without a writable cgroup (a default `docker run`, an undelegated user service).
- Without `CAP_BPF` and `CAP_NET_ADMIN` (any ordinary user they weren't granted to).
- Without a BPF filesystem `hermitboxd` can write.
- Without a netlink socket to hear of the host's address changes (a unit whose
  `RestrictAddressFamilies` leaves out `AF_NETLINK`).
- Without readable host address tables in `/proc/net`.
- Where the kernel's verifier refuses a program, with the verifier's words.

Nothing is approximated where it is off.

The root unit that the server and node presets install (`deploy/hermitboxd.service`) grants what it
needs and no more:

- CAP_BPF and CAP_NET_ADMIN, with CAP_SETUID and CAP_SETGID for the process tier's uid pool;
- netlink sockets for the address watch below;
- `Delegate=yes`;
- of `/sys`, only its own cgroup subtree and `/sys/fs/bpf/hermitbox` writable.

Process sandboxes live in cgroups below the unit's, so they stop when `hermitboxd`'s unit stops,
as VMs do with the VM worker; containers keep running. `hermitboxd` logs the proof at each start
(`kernel network policy`, with `on` and its evidence).

The server preset's own control plane requires private-network, private-pids, memory-limit and
cpu-limit of every sandbox. Under this unit the process tier gives memory-limit and cpu-limit
([process-tier.md](https://docs.hermitbox.dev/v0.3.2/reference/process-tier.md#limits)) and, in the namespaced mode, private-pids. For that,
the unit allows exactly the user, mount, PID, IPC and network namespaces its helper takes. It
keeps nothing mounted over `/proc`, since the kernel mounts a sandbox's own `/proc` in a user
namespace only where none is. So ProtectKernelTunables, ProtectKernelLogs and ProtectHostname
are off. Instead, `/sys` is read-only by ReadOnlyPaths, and syslog(2), sethostname(2) and
setdomainname(2) are refused by SystemCallFilter.

The unit doesn't give private-network to an Internet-enabled process sandbox, which shares the
host's network stack. So the preset places none there: a sandbox naming no image runs on a
container from control's default image instead
([isolation](https://docs.hermitbox.dev/v0.3.2/concepts/isolation.md#how-the-default-is-chosen)). A control plane a node joins
that places process sandboxes gets them policed and limited.

As root, granting it to a user means: the capabilities on its service
(`AmbientCapabilities=CAP_BPF CAP_NET_ADMIN`), `Delegate=yes`, and
`install -d -o <user> /sys/fs/bpf/hermitbox` with `chmod o+x /sys/fs/bpf`. `hermitboxd` clears its
ambient capabilities for every supervisor it starts, so a sandbox never holds them.

## What a sandbox gets

The same specification as a container's network decides:

| Specification | Reaches |
| --- | --- |
| `network: internet` (public internet on) | Every destination but this host, link-local (169.254.0.0/16, fe80::/10, where clouds serve metadata), AWS's IPv6 metadata address (`fd00:ec2::254`, though the rest of fc00::/7 stays private, its resolver `fd00:ec2::253` included), multicast, broadcast, and private addresses on the ports `hermitboxd` serves and its API's. DNS reaches the resolvers `/etc/resolv.conf` names. |
| `egress: {allow, deny}` (public internet off, hostname policy) | Only the named hosts, through gateways `hermitboxd` serves for that sandbox: TCP 80 and 443 and DNS on 53, from any address, are redirected to them; nothing else leaves. A gateway dials a name only when every address it resolves to is public, none is local to this host as the kernel routes it at that moment, and none is one the sandbox's `egressAddresses.deny` refuses on that port. |
| `egressAddresses: {allow, deny}` | Allow adds exactly the prefixes and ports named; deny takes them away. Deny wins. |
| `network: none` | Nothing, as before; the programs refuse it too. |

### Host addresses

Whatever the specification, a host address (loopback, any address of this host) reaches only a
socket the sandbox itself made. So its own `localhost` works, and another sandbox's ports, the
host's services, its agent's neighbours and `hermitboxd`'s API don't. A request's allow rule
can't name loopback, link-local, multicast or the unspecified ranges.

A host address's NAT64 twin (`64:ff9b::` and the IPv4 address) is refused, since a translator off
the host can send it back here. So is every prefix this host's routes broadcast to (a subnet's
last address, loopback's `127.255.255.255`): a datagram sent there reaches this host's own UDP
sockets too, from the link.

This host's addresses and broadcast prefixes are read when a sandbox's programs are attached. They
are read again each time the kernel says an address was added or removed, through rtnetlink's
IPv4 and IPv6 address groups and its IPv4 route group. Both are read from the local routing
table, which the kernel updates right after it tells of the address. `hermitboxd` is woken by that
message and at once compiles and writes every live sandbox's rules again, new ones in before old
ones out, so no lookup misses.

### What the packet hook checks

The packet egress hook checks the current kernel route independently. A host-local destination
uses the loopback device, including an address newly added that the watcher has not processed.
There it permits a datagram, or the SYN that opens a connection, only to:

- the sandbox's own destination sockets;
- its exact gateway listeners;
- configured DNS resolvers on their DNS port.

An explicit deny still wins for a sandbox destination.

The SYN is looked up with its whole four-tuple. So a reuse-port group that another owner shares
with the sandbox (as processes of one user can) can't hand the connection to that owner. A SYN
that meets TIME-WAIT goes to the listener the kernel picks with its source, which a lookup can't
reach past the TIME-WAIT socket. So the hook looks it up without the source, which finds the same
listener or another member of its reuse-port group.

A gateway listener is in no group, so it is let through. A sandbox may run as a UID of its own
(`hermitboxd` as root, the process UID pool). Then a group with its listener holds only its
sockets, so it is let through too. Under a shared UID (`hermitboxd` as an ordinary user), the owner of the
member the SYN reaches can't be proved, and the SYN is refused. A reconnect from the same port to
the sandbox's own listener then waits for TIME-WAIT to end, or picks another port. A connection's
later segments go to the peer its SYN reached.

Every active TCP connect marks its socket, including one reused after accepting and disconnecting,
so a new dial cannot take the accepted-response allowance.

For traffic leaving this host, the hook holds every packet, except a reply on an accepted TCP
connection, to the destination its header names. IPv4 source-route options and IPv6 routing
headers can make that destination differ from the address the connect hook saw. It must be one
the sandbox can dial, allowed or a configured resolver, and never this host's own.

The hook reads IP and TCP/UDP headers, including up to eight ordinary IPv6 Hop-by-Hop, Routing or
Destination Options headers. Malformed, fragment and longer chains fail closed, and so does an
encrypted one on loopback. Off the host an IPsec packet passes as before: the host's own policy
sealed it after the address hooks ran, and no sandbox socket can.

Process sandboxes can't attach a program to a reuse-port group: the agent's seccomp filter refuses
`SO_ATTACH_REUSEPORT_CBPF` and `_EBPF`. Such a program, not the hash these lookups follow, would
pick the group's member.

HTTP and TLS gateways also check their connected upstream's peer and current route before writing
any request bytes.

Sockets other than TCP and UDP over IPv4 and IPv6 (raw, ICMP echo, SCTP, UDP-Lite, MPTCP) are
refused at `socket()`.

### When the rules can't be kept

When the host's address tables can't be read, or a sandbox's new rules can't be written,
`hermitboxd` freezes (`cgroup.freeze`) and kills that sandbox's cgroup. It keeps the programs
attached until every member has exited. That fenced program set never becomes verified again:
another start removes the old empty cgroup and attaches a fresh set.

A missing IPv6 address table is accepted only when an IPv6 socket proves that the host has no such
address family. `hermitboxd` needs a netlink socket for the address watch, and is off without one,
with that reason.

### Reaching a sandbox from other machines

From off this host, a sandbox is reached as a container is. That is on the ports `hermitboxd`
published for it (its agent's and its spares, where the edge dials it), and nowhere else. So a server it binds to
`0.0.0.0` is reached from this host and through the edge, never directly from another machine.

What arrives from another machine is let in only:

- for TCP to a published port;
- for a TCP connection the sandbox dialled off the host (its answers; a socket that dialled and
  then listened gets none);
- for a UDP socket, from a peer, address and port, that socket itself was allowed to send to.

The rest is dropped, so the other machine's connection times out.

Each sandbox keeps its 4096 most recent datagram peers (about 360 KiB of kernel memory). An older
peer's datagrams are dropped until the socket sends to it again. An IPv6 datagram behind extension
headers is dropped too, since the program reads only the fixed IP and UDP headers.

### How the guarantee is reported

A sandbox's view reports `host-firewall: true` once its own programs are attached and verified. A
node announces `host-firewall`, `egress-hostnames` and `egress-addresses` for the process tier only
where the probe proved them.

A process sandbox can run without verified programs. It may have started before its host had the
capability (a restart of `hermitboxd` leaves it running), or its rules may no longer fit the
host's addresses. While any such sandbox runs, `host-firewall` is off for the whole tier, on the
node and in every process sandbox's view. `kernel-network-policy`'s evidence says how many there
are. Such a sandbox reaches the others' listeners over loopback.

A normal stop restores the guarantee only after the trusted supervisor has:

- closed command admission;
- joined its native-tool worker;
- shut down its runtime;
- killed and reaped every remaining descendant, including detached sessions and children whose
  exit signal is not SIGCHLD;
- signed a fresh retirement challenge.

A dedicated UID can instead prove cleanup through a complete, unfiltered process scan; unreadable
or ambiguous process visibility cannot prove that nothing remains.

An unexpectedly lost legacy supervisor can leave descendants that its shared UID no longer
identifies. That uncertainty keeps the tier guarantee off for the rest of the current boot, even
after its sandbox record is removed or `hermitboxd` restarts. An older process state directory without
the new history-origin record is treated the same way, because earlier versions could already have
deleted such a sandbox's record. A changed, verified kernel boot identity clears that history.
Without a boot identity the uncertainty remains.

A request for hostname or address policy on a host without the capability is refused, naming
`kernel-network-policy`. A placement that requires `host-firewall` is refused naming it.

### Launch records

Before every fork, including plain mode without BPF, `hermitboxd` saves a boot-scoped launch
intent. If it crashes before saving the PID, that intent retains the possible generation's
ownership. Only a record with no launch intent qualifies as never started. Live observation waits
through the intent, synchronous fork and PID checkpoint, so it cannot retire a launch in progress.

An incomplete plain-mode intent cannot use an empty dedicated UID as retirement proof: its child
might still be paused before dropping to that UID. The actual PID checkpoint ends that pending
phase; a proven new boot also retires it.

## How the programs work

One object (`bpf/network.bpf.c`, built by `bpf/build.sh` and embedded in `hermitboxd`) holds nine
programs, each with one job, and six maps (rules, config, owners, sockets, peers and counters):

| Program | Hook | Job |
| --- | --- | --- |
| `connect4`, `connect6` | `cgroup/connect4`, `connect6` | Allow, refuse (EPERM) or redirect a TCP or UDP connect |
| `sendmsg4`, `sendmsg6` | `cgroup/sendmsg4`, `sendmsg6` | The same for an unconnected datagram's address |
| `recvmsg4`, `recvmsg6` | `cgroup/recvmsg4`, `recvmsg6` | Put back the resolver's address on a redirected DNS answer |
| `sock_create` | `cgroup/sock_create` | Refuse non-TCP/UDP sockets; mark the rest as the sandbox's |
| `ingress` | `cgroup_skb/ingress` | Drop what arrives from off the host but answers (TCP connections dialled, UDP peers sent to) and published ports; count |
| `egress` | `cgroup_skb/egress` | Check where each datagram and SYN lands on this host, and what leaves it; count packets and bytes |

`hermitboxd` compiles the policy into an LPM trie of IPv6 prefixes. IPv4 is held as
`::ffff:a.b.c.d`, and NAT64's `64:ff9b::/96` takes the rules of the address it embeds. Each
prefix carries its own port ranges and those of every wider prefix, in the order they apply, and a
fallback. So a program does one lookup and takes the first matching range.

A verdict is one of:

- allow;
- deny;
- a configured resolver;
- *owned*: a host address, allowed only when `bpf_sk_lookup` finds a listener the sandbox's
  socket-storage map holds;
- a gateway: the destination is rewritten to the sandbox's gateway, after checking that
  `hermitboxd`'s listener is there.

The packet hook reads only network and transport headers, never payloads.

The ownership-only socket map uses the kernel's `BPF_F_CLONE`, so an accepted destination retains
its listener's exact sandbox or gateway ownership. Direction and redirected-DNS state live in a
separate, non-cloned map: a listener's earlier dial never marks a new accepted socket as an
initiated connection. A stale public rule can therefore still reach an owned wildcard listener on a
newly local address, including its established connection's payload. A host listener remains
refused.

Programs are attached through cgroup BPF links and pinned, with their maps, under
`<bpffs>/hermitbox/<key>/`, where `<key>` names the sandbox within one state directory. A restarted
`hermitboxd` first requires its private record's complete object SHA-256 to match the embedded
object. Then it finds the pins, checks each link is the one it attached, writes the rules again and
serves new gateways.

A failed host proof, address watch or adoption stops every supervisor with a recorded program set.
None of them can restart in plain mode while that proof is unavailable. Legacy supervisors without
a record keep their existing mode, with the tier guarantee off. When a sandbox's supervisor is
gone, `hermitboxd` fences and kills whatever is left in its cgroup and waits for it to empty. It then
removes the pins, which detaches the programs, and removes the cgroup. Missing or changed object
identities require that retirement and a fresh start with current programs.

The journal records the prepared policy before any fork can join it. A missing supervisor or an
incomplete earlier record cannot prove cleanup. Any unverified canonical cgroup, even empty or
unreadable, keeps the tier's guarantee off until retirement removes it. Failed cleanup keeps the
journal, so a later daemon cannot lose the cgroup's owner by deleting the record.

## Read the counters

`GET /v1/workloads/{id}/stats` reports the sandbox's `networkRxBytes` and `networkTxBytes` from
the `ingress` and `egress` programs, loopback traffic included. With `bpftool` as root, the map
`map-counters` under the sandbox's pin directory holds five per-CPU `{packets, bytes}` slots:
ingress, egress, refused destinations, refused sockets and refused ingress.

```sh
# Dump the sandbox's packet and byte counters.
bpftool map dump pinned /sys/fs/bpf/hermitbox/<key>/map-counters

# Dump its compiled rules.
bpftool map dump pinned /sys/fs/bpf/hermitbox/<key>/map-rules

# Show one of its attached links.
bpftool link show pinned /sys/fs/bpf/hermitbox/<key>/link-connect4
```

## Kernels

The object needs cgroup BPF links (5.7), socket storage in `sock_create` programs and socket
lookups in address hooks. All are present on every kernel the process tier supports (Landlock ABI
3, 6.2 and later). It reads only UAPI context fields and carries BTF, so one build loads on every
kernel.

## How this is tested

CI loads the object on the oldest and newest hosted kernels in its matrix, and fails if the
verifier rejects a program. `bpf/rejected.bpf.o` is the same source built to end with a program
the verifier refuses, and it goes to the probe. CI checks that the guarantee is off with the
verifier's words, that nothing of the set stays attached, and that a request for address policy is
refused naming the capability.

The kernel test deliberately keeps the old address map. It requires the first and all ten repeated
TCP and UDP attempts to reach no host listener, for IPv4, mapped IPv4 and IPv6. Owned IPv6
Destination Options traffic must still work.
