# RADIUS

> The portable authentication protocol core, integration boundary, and development qualification.

---

# 1 Architecture

_Peios / Reference / RADIUS_

> Packet integrity, encrypted credential exchange, and explicit network admission in the portable RADIUS core.

The `radius` repository contains the portable RADIUS authentication core,
the native `radiusd` daemon, the `radius` administration program, and a
host-side qualification fixture.
The native integration uses existing Peios services and kernel APIs;
packaging and real AP qualification are separate milestones.

## 1.1 Responsibilities

The core implements UDP RADIUS authentication, EAP-TTLSv0/PAP and
PEAPv0/EAP-MSCHAPv2. Rustls handles TLS; ring supplies its cryptographic
primitives. RADIUS uses MD5 and HMAC-MD5 only where required by its wire
format, through existing cryptographic libraries.

The caller owns sockets, trusted-client selection, network mapping,
configuration, identity verification, and network admission. It supplies
the actual packet source and a `Binding` consisting of client identity,
trust generation, and network identity. Asserted NAS attributes do not
establish this binding.

The core has no registry, account database, OS token, or impersonation
authority. The loopback-only `radius-test-server` is a fixture with one
test identity. It is not a production backend or an installable service.

## 1.2 Conversation

```mermaid
flowchart TD
    A[Integrity-checked request] --> B[Bound EAP and TLS conversation]
    B --> C[Inner password or source-bound MSCHAPv2 proof]
    C --> D[Credential exchange with integration]
    D --> E[Verify identity and retain full subject]
    E --> F[Check current network admission]
    F -->|Granted| G[Success and Wi-Fi key delivery]
    F -->|Denied or failed| H[Failure without keys]
```

An outer identity such as `anonymous` introduces the EAP exchange. The
inner username and credential proof drive verification. The outer name grants
no user authority and need not match the inner name.

`Engine::receive` returns a reply, a one-shot verification event or a
drop. Credentials are owned by that event; its password buffer is
erased on drop, and debug output is redacted. PEAP also returns a typed
MSCHAPv2 response event after the source-issued challenge. The Peios adapter
uses authd Authenticate and retains its verified identity, source groups
and permitted claims on that same attempt. It then evaluates the
network's Connect descriptor using the advisory access-check API.
It then selects a complete access profile through PNP's shared tree machinery.
Profile selection cannot bypass the Connect check or accounting allowances.
See [Access Assignment](/peios/reference/radius/access-assignment.md).

Only an explicit `Engine::finish` admission result can deliver success
and keys. It rechecks the deadline, source/client/network binding, and
shared secret. A changed trust definition requires a fresh exchange.
The current policy generation accompanies completion, keeping the reply
cache consistent with the decision actually made. The caller is trusted
to evaluate that current policy; a generation number is not proof of a
grant.

The core does not perform a later username lookup to reconstruct a
subject. Backend failure and insufficient identity context do not grant
network access. The protocol core receives the admission outcome and
does not depend on authd, registry or KACS types.

## 1.3 Protocol and TLS scope

Every request requires a valid Message-Authenticator. Malformed and
unauthenticated datagrams are discarded without replies. Reply integrity
includes both the Message-Authenticator and Response Authenticator.
The original authenticated request determines key wrapping for its reply.

TTLSv0/PAP supports both TLS 1.2 and TLS 1.3, with
version-specific key derivation. TLS 1.2 uses the TTLS exporter label
without context; TLS 1.3 uses the EAP key-material exporter with the TTLS
type as context. Both request 128 bytes before splitting the result.

PEAPv0/EAP-MSCHAPv2 uses TLS 1.2 in this initial compatibility slice,
with the `client EAP encryption` exporter label. The core relays a
source-issued challenge and the client's response, without receiving
the password or reusable NT hash. It sends the exchange-specific server
proof only after authentication and admission succeed. Final success
and Wi-Fi key delivery wait for the MSCHAPv2 success acknowledgment and
the tunneled Result TLV acknowledgment, followed by another current
network-admission check. Cryptographic credential checking belongs to
authd's principal source. PEAP cryptobinding extensions and TLS 1.3 for
PEAP are not implemented in this slice.

Each network has an ordered allowed-method list. Negotiation can select
an allowed, untried alternative before TLS begins; a credential failure
does not cause method fallback. Named authentication profiles explicitly
choose the allowed methods and their order. EAP-TLS and method-specific
admission rules remain future work.

Full authentication is required each time. Session storage, ticket
resumption, and early data are disabled. Ordinary TLS server defaults
are therefore unsuitable without the core's explicit configuration.
No client certificate is required, but the client validates the server's
certificate chain and expected identity before disclosing credentials.

Proxy-State, direct outer password methods, additional EAP
methods, and application SSO are outside this slice.

The separate accounting crate owns durable session reports and allowances;
see [Accounting](/peios/reference/radius/accounting.md).

## 1.4 Resource and retransmission bounds

| Resource | Default or bound |
|---|---|
| RADIUS declared packet length | At most 4096 bytes |
| Reassembled TLS message | At most 65536 bytes |
| Buffered inner AVPs | At most 4096 bytes |
| Inner username | 1 to 253 bytes |
| Inner password before padding removal | At most 1024 bytes |
| Configured shared secret | 16 to 1024 bytes |
| Idle conversation timeout | 30 seconds |
| Overall conversation deadline | Two minutes |
| Active conversations | 256 globally; 32 per client |
| Cached replies | 1024 for 15 seconds |
| Outgoing TLS fragment payload | 1000 bytes |

The caller supplies monotonic time and periodically calls `expire`,
including while no packets arrive. Pending backend work shares the same
conversation deadlines. `update_limits` changes future attempts' limits
without moving existing deadlines. Lower allocation limits prevent new
allocations without evicting current attempts.

Exact retransmissions receive cached bytes. The cache includes the
authenticated packet contents, source endpoint, trusted binding and
policy generation for terminal decisions. Challenges grant no access and
can be replayed across policy edits while their trusted binding matches.
An in-progress verification is not restarted by a
duplicate packet. A changed packet is not mistaken for a cached request.

These records last through sign-in, not through an hours-long Wi-Fi
connection. Already admitted connection lifetime and periodic
reauthentication belong to the AP. Successful native admissions request
reauthentication with Session-Timeout and Termination-Action, defaulting
to one hour. Actual AP/client enforcement still requires qualification.

## 1.5 References

- [RADIUS](https://www.rfc-editor.org/rfc/rfc2865.html).
- [RADIUS support for EAP](https://www.rfc-editor.org/rfc/rfc3579.html).
- [EAP-TTLS](https://www.rfc-editor.org/rfc/rfc5281.html).
- [TLS-based EAP methods with TLS 1.3](https://www.rfc-editor.org/rfc/rfc9427.html).
- [Microsoft key attributes](https://www.rfc-editor.org/rfc/rfc2548.html).

---

# 2 Qualification

_Peios / Reference / RADIUS_

> Running the independent supplicant gate and understanding what its results establish.

The interoperability gate tests the protocol core against an independent
OpenSSL-backed supplicant over loopback. It checks the encrypted exchange
and actual exported Wi-Fi key agreement independently of Peios services.

## 2.1 Running the gate

From the repository root, build the fixture and test tool:

```sh
cargo build --workspace --locked
python3 tools/build-eapol-test.py --out target/test-tools/eapol_test
```

The tool builder requires a C compiler, Make, OpenSSL development files
and network access to the pinned upstream archive. It builds only the
test executable and removes its temporary source tree. An existing
qualified `eapol_test` can be supplied instead.

Run the required gate:

```sh
python3 tests/interop.py --server target/debug/radius-test-server --eapol-test target/test-tools/eapol_test
```

The runner fails if required tools are missing. Successful cases check
both EAP success and MPPE key agreement. It forces TLS 1.2 and TLS 1.3
separately, uses a large certificate chain and small fragments, checks
anonymous and differing outer names, and rejects wrong credentials,
denied admission, untrusted issuers and wrong server names. A loopback
relay duplicates requests and suppresses a reply. Direct packet checks
also verify reply authenticators and discard tampered requests.

The fixture listener rejects non-loopback addresses. Temporary test
credentials and certificates are removed on completion; captured
supplicant output is not printed because it can contain key material.
The fixture uses explicit test credentials and never contacts authd.

## 2.2 Component checks

```sh
pekit test --strict -j 2 unit integration management policy authorization accounting clippy doctests
pekit build --strict -j 2 test_server radiusd radius_cli radius
pekit test --strict -j 2 native native_management administration native_clippy native_management_clippy administration_clippy
```

These are raw component targets. They do not package files or build a
kernel or image. `radius_cli` builds terminal administration with native
support; `radius` also includes the GXWI window. The native targets supply
matching pinned SDK, authentication and desktop libraries. Cargo and Pekit
must select the same source revision for each imported component; do not
bypass a reported mismatch. Before dependency commits are published, local
qualification needs those exact commits in the build cache.

The host Cargo equivalents are documented in the repository README. Native
host tests do not replace guest qualification: tests marked as requiring a
disposable Peios guest remain ignored on the host. The Rust checks exercise
malformed and truncated packets, duplicate attributes, conversation quotas,
idle and overall deadlines,
binding changes, one-shot admission and rejection without key delivery.

The `authorization` target checks typed settings, independent standard and
vendor wire vectors, exact unit conversion, protected attributes, reset
requirements and complete reply bounds. Native coordinator and loopback CoA
checks cover complete assignments, cache integrity, quota gating, real UDP
requests and acknowledged baselines. These establish server behavior; actual
equipment needs separate shaping, filter, gateway, and management tests.

## 2.3 Native session controls

In a fresh, isolated guest, run `tests/native/setup.sh`, then
`tests/native/session-controls.sh` and `tests/native/automatic-controls.sh`.
Supply the compiled `native-session-controls` example, the native-policy test
binary, and the independent supplicant in `/mnt/dev/bin`, with the fixture
credentials under `/mnt/dev/credentials`. These scripts require
`PEIOS_DISPOSABLE_RADIUS_TEST=yes` and `RADIUS_DEV_RUNTIME=1`. They change
accounts, policy, service definitions, and the ledger; use no deployed state
or LAN interface.

The checks exercise actual caller tokens, separate action and fallback
permissions, protected credential metadata, password revision changes,
maintenance stability, exact-session CoA and Disconnect, forged replies,
durable request IDs, restart, rebuild, and real PEAP/TTLS authentication.
Automatic cases use direct Registry VLAN edits, account disablement, password
replacement with an explicit Disconnect fallback, and opt-in CoA updates.
The generic profile does not claim fresh reauthentication support.

`tests/native/richer-profiles.sh` checks saved setting types, equipment
mapping, Explain, exact 64-bit values, unsupported ranges, invalid direct
Registry edits, removal, restart, TLS 1.2/1.3 authentication, key agreement,
and actual-caller permission checks. Run it after `setup.sh` in an isolated
guest, or after the session-control scripts to include the accounting ledger.
It qualifies server behavior with a loopback supplicant; no fixture emulates
traffic shaping or gateway enforcement.

A migration fixture can seed accounts with a previously qualified format-6
lpsd before switching to the new runtime. Set
`RADIUS_QUALIFY_LEGACY_STORE=1` only for that arrangement. Fresh-store checks
do not exercise the old-store upgrade.

## 2.4 Component load and recovery

The developer-only qualification program measures bounded synthetic loads,
checks overload recovery, and injects storage failures in child processes.
See [Component Load and Recovery](/peios/reference/radius/component-load-and-recovery.md)
for commands, measurements, and the incomplete instrumented fuzzing gate.

## 2.5 Limits of the evidence

Passing this gate establishes host-side protocol behavior for the tested
tool and cases. Native qualification is described in
[Native Integration](/peios/reference/radius/native-integration.md). Neither gate establishes
real AP reauthentication or device onboarding. Those require actual
equipment. A passing suite is not a complete security audit.

---

# 3 Native Integration

_Peios / Reference / RADIUS_

> Service identity, Registry configuration, failure behavior, and disposable-guest qualification of radiusd.

`radiusd` is the native adapter around the portable protocol core. It
runs as its own `Identity=Service` account, verifies passwords through
authd, and checks the current network's Connect security descriptor.
It creates no user token or local logon session.

## 3.1 Build and service identity

Build the raw executable, without packaging or rebuilding the kernel:

```sh
pekit build --strict -j 2 radiusd radius_cli radius
```

`radius_cli` includes native terminal administration; `radius` includes the
same commands and the optional GXWI window. These raw component targets do
not invoke final PPK packaging in `pkgs/`.

The native Cargo feature links the matching public `libauth.so.1` and
`libpeios.so.0`. The Pekit target supplies those libraries and SDK
headers from pinned canonical source revisions. A development guest
must load these matching libraries rather than older image copies.

The daemon, command-line client and GXWI window use one Peios Rust bindings
0.5 dependency graph, aligned with the distribution's SDK and service pins.
Build these clients with their pinned dependencies and matching libraries.

Fresh state-directory provisioning requires a kernel with KACS control
handles: native opens that request no data rights. The administrator creates
each directory carrying its security descriptor. Older kernels reject this
open with `EINVAL`; provisioning does not fall back to creating an unprotected
directory and setting its descriptor afterward. Existing directories keep
their descriptors.

The current bindings require authd's PGSS version 6 protocol and libauth
ABI 6. The shared-library filename remains `libauth.so.1`, so successful
loader resolution alone does not establish compatibility; the bindings
check the ABI when creating a client. Upgrade the daemon, matching library,
peinit service-token client, and other authentication clients together.
An older GXWI server or SSH bridge cannot authenticate against the new
authd merely because radiusd has been rebuilt. RADIUS continues to request
only password or MSCHAPv2 verification; this update adds no NTLM method.

The service must be named `radiusd` and use `Identity=Service`. It
checks its actual token user SID at startup. Trusted authd policy gives
this account the `peios.auth.authenticate` capability. It receives no
`peios.auth.logon` capability and needs no token-creation or impersonation
privileges. `SeChangeNotifyPrivilege` permits ordinary path traversal;
`SeAuditPrivilege` permits operational event emission. The normal UDP
port-reservation descriptor grants its service SID PORT_BIND for each
configured listening port. Use peinit's Notify readiness mode.

The radius package provides these as Registry seeds, in `registry.d`:
`radiusd-service.reg` defines the service, `radiusd-policy.reg` grants its
account the capability and the two privileges, and `radiusd-port.reg`
reserves UDP ports 1812 and 1813 for it. The definition has no Triggers, so
installing the package starts nothing. `radius service boot on` adds a boot
trigger once the configuration is initialized.

Packet admission is separate from the port reservation. When packet filtering
is enabled, allow inbound UDP for each configured RADIUS listener. GXWI's
inbound TCP rule does not also admit RADIUS authentication traffic.

The default AuthenticationSecurity descriptor grants this service
ReadGroups and ReadClaim across the namespace. Authenticate remains a
separate capability grant. Administrators can use ordinary claim object
ACEs to restrict sensitive claims. An explicit AuthenticationSecurity
value replaces the default and is never silently broadened.

## 3.2 Configuration and admission

The component's `radiusd.regman` describes every value under
`Machine\Software\Radius`. Settings define literal UDP listeners and
bounded conversation resources. Clients define source-address prefixes,
protected secret-file references, and allowed access-policy GUIDs. Access
policies define exact SSIDs, Connect security descriptors, periodic
reauthentication, and an authentication-profile reference. Profiles select
ordered methods and a named server identity. Server identities reference an
ordered DER certificate chain and matching protected DER private key.
All records have stable GUID keys and independent display names. Schema
version 3 adds access profiles and nested assignment rules. Existing schema
2 deployments require the explicit migration described in Administration.

Most-specific source prefixes select the trusted client. There is no
fallback to another secret. The integrity-checked Called-Station-Id must
contain a valid MAC prefix and exact SSID; NAS identifiers and MAC
addresses do not establish user identity. Continuations retain their
original client, source, and network binding. A changed secret, source
trust definition, SSID, or listener set invalidates affected work.

Each profile's required `AuthenticationMethods` is an ordered allowed-method
list containing `ttls-pap`, `peap-mschapv2`, or both. All methods share the
access policy's Connect descriptor. Changing a method list invalidates
affected unfinished exchanges and cached replies. Enabling NT storage does
not change the configured methods.

An intentionally disabled client, policy, or profile denies affected
admissions without falling back to other clients or profiles. Otherwise
valid disabled records do not invalidate unrelated policy. These changes do
not disconnect established stations immediately. Missing references remain
invalid even on disabled records.

One nonblocking authd operation belongs to each credential attempt. PAP
uses one typed Password prompt and requires confirmed Password verification.
PEAP requests MSCHAPv2, relays one source-issued challenge and typed
response, and requires confirmed MSCHAPv2 verification with the protocol's
server proof. radiusd receives no reusable NT hash. Unsupported or repeated
prompts, unavailable sources, and incomplete verification cannot grant access.
A configurable concurrency limit rejects excess verification work without
an unbounded queue. NT storage and opportunistic password-side backfilling
are documented with the local principal source, not configured by radiusd.

Admission uses the verified SID, source groups, permitted typed claims,
and explicit claim coverage. It does not reconstruct identity from a
later username lookup or invent local-session group memberships.
For example, grant Connect to a source's household group SID. An
Everyone ACE matches only when that membership is supplied; the adapter
does not add it. Hidden claims remain unknown. Missing context, device,
or local execution requirements deny admission. The stateless kernel query
conveys no token authority. An older kernel fails admission with
`kernel-api-unavailable`; other query errors use `access-check-error`,
independently of wrong credentials and an ordinary policy denial. There is no
userspace evaluator fallback.

Each check supplies the stable Registry network ID and SSID display label in
an `AuditContext` of kind `network`. Invalid UTF-8 in the label is replaced
with U+FFFD; policy binding still uses the original SSID bytes. The fields are
defined as asserted values in radiusd's event catalog fragment. Matching SACL
audit ACEs produce `kacs.audit.subject.checked`
when radiusd holds enabled `SeAuditPrivilege`. The event identifies radiusd's
real caller identity separately from the supplied, hypothetical user SID.
Audit preparation errors fail admission. radiusd's own admission events remain
separate and describe the real service decision.

Current policy is checked immediately before success and key delivery.
Access-Accept carries signed Session-Timeout and Termination-Action
attributes. The default requests reauthentication after one hour.
It does not immediately disconnect existing Wi-Fi stations, and AP
enforcement must be qualified separately.

## 3.3 Reload and reporting

A bounded worker handles blocking Registry and protected-file reads.
The packet loop continues processing bounded handshakes and expiry.
Observed pending, invalid, unreadable, or unwatched configuration pauses
new admissions and cached success replies. Pending verification results
can wait only within their original deadlines. Recovery validates the
assembled configuration before resuming. Certificate replacement cancels
affected unfinished exchanges and cached replies. Cosmetic name changes
preserve authentication bindings.

Notify readiness means the local status endpoint is ready. An invalid
initial configuration leaves that endpoint available for diagnosis and
repair while authentication is paused. It does not imply active listeners.
The administration program shows saved and effective configuration
separately; it also distinguishes a stopped service from an unreachable or
unauthorized status endpoint. See
[Administration](/peios/reference/radius/administration.md).

The loader copies Registry configuration through one short read-only
transaction, including key resolution, enumeration, values, and layer
selection.
It releases the snapshot before opening credential files. Capture races
discard the complete candidate and retry a fresh read within a 250 ms
retry budget. That budget limits additional attempts; it does not interrupt a
Registry call already in progress. Other read errors return immediately.
If capture still fails, the worker retries on its normal reload cycle and
keeps admission paused while configuration is invalid. Writes are not retried
by this read helper.
Watches and fingerprints detect changes but do not establish read consistency.
Prepare protected immutable credential files, then transactionally switch
references. Keep old files until safely unused; a Registry transaction does
not snapshot filesystem contents.

`radiusd.evman` defines operational exchange and configuration events.
The inner supplied username is explicitly unverified input; canonical
name and SID appear only after verification. Events contain no
passwords, AP secrets, private keys, or full claim values. Exact
retransmissions do not repeat outcomes. Invalid datagrams are counted
in bounded, rate-limited diagnostics. Event emission failure is reported
without changing a valid admission; successful emission does not prove
durable collection. These events do not replace kernel SACL auditing.

## 3.4 Disposable guest qualification

The scripts under `tests/native` alter accounts, service definitions,
machine authentication policy, and a port table. Run them only in a
fresh disposable guest, with `PEIOS_DISPOSABLE_RADIUS_TEST=yes`.
They must never run on a developer's normal system.

Use an existing console image and raw component binaries. Mount a
read-only development share as `/mnt/dev`, using the guest's supported
9p synthetic ephemeral policy. Copy the matching raw peinit2, svctl,
authd, lpsd, lps, radiusd, libpeios, and libauth into `/lcl`. Start the
raw peinit2 as PID 1 from an initial shell. Set service library search
paths explicitly: peinit constructs service environments rather than
inheriting the launching shell's environment.

The share contains `native` with the qualification shell scripts; `bin` with
the independent `eapol_test` and matching OpenSSL runtime dependencies;
and `credentials` with generated root.pem, server.der, intermediate.der,
key.der, secret, and rotated-secret files. The existing interoperability
certificate helper creates suitable development-only certificates.
Secrets are development fixtures, never production credentials.
For PEAP qualification, enable EAP-PEAP and EAP-MSCHAPV2 in the independent
supplicant. The supplied builder enables both. An OpenSSL 3 build can also
need its matching legacy provider for the supplicant's MD4 operation;
place `legacy.so` beside the test executable. radiusd does not use that
provider.

```sh
export PEIOS_DISPOSABLE_RADIUS_TEST=yes
bash /mnt/dev/native/setup.sh
bash /mnt/dev/native/qualify.sh
bash /mnt/dev/native/mschapv2.sh
bash /mnt/dev/native/administration.sh
bash /mnt/dev/native/initialize.sh
bash /mnt/dev/native/assignment.sh
bash /mnt/dev/native/migrate-policy.sh
```

The independent supplicant runs inside the guest against loopback UDP.
The native service identity, Registry, authd/lpsd verification, supplied
subject admission, and key export are real. Wi-Fi equipment and its
radio link are simulated. The scripts check both TLS versions, matching
MPPE keys, account and policy denials, restricted-claim uncertainty,
invalid-configuration recovery, secret rotation, and source failure.
They capture supplicant output privately because it can contain keys.
The MSCHAPv2 sequence also checks method negotiation, both NT controls,
opportunistic backfilling, password changes, and password eligibility.
Administration qualification additionally requires `bin/radius`, matching
`libgxwi.so.1`, and the native-authority example in the development share.
It checks shared profiles, references, renames, disabled isolation, invalid
startup recovery, credential staging, stopped-daemon edits, and real-token
status, Registry, and secret-file authorization. Certificate import checks
also need the corresponding PEM chain and private key in the fixture share.
The initialization script temporarily replaces and restores the disposable
fixture's Registry subtree and credential directory. It verifies fresh setup,
existing-configuration refusal, and enabled-administrator writes without
granting the test token extra privileges.
Set `RADIUS_DEV_RUNTIME=1` when using the replaceable raw-binary layout
at `/lcl/radius-dev/current` rather than copying binaries into `/lcl`.

The optional `native-events` Cargo example reads the two fixture CPU
rings as the guest administrator. Start it before `qualify.sh`, wait
for `/run/radiusd/events.ready`, and create
`/run/radiusd/qualification.done` afterward. Its zero exit status and
PASS marker verify typed, cataloged payload fields and absence of
unexpected credential or claim fields. It is a qualification tool,
not part of the daemon or a required service privilege.

Portable coordinator tests separately cover concurrent verification
bounds, exact replay, policy changes, preserved deadlines, binding
invalidation, and cancellation. Native SDK tests cover typed claims,
known absence, and missing device or audit context.

## 3.5 Diagnostic reader qualification

Stage eventd and evctl in the replaceable runtime, plus the
`native-diagnostics` Cargo example in the share's `bin` directory. In a fresh
disposable guest, `tests/native/diagnostics.sh` provisions the fixture and
checks actual attempt history, exact authd operation links, caller identity,
delegated event reads, and denial of personal fields. It also checks that
authentication continues through an eventd outage and tight emission bounds.

The script defaults to eventd's Service identity. The explicit override
`RADIUS_DIAGNOSTICS_EVENTD_IDENTITY=SYSTEM` isolates query checks when normal
service ingestion is unavailable. A pass with that override does not qualify
the Service deployment. The fixture must not be applied to a deployed machine.

The CLI and GXWI require a working, separately provisioned eventd deployment
for diagnostic history. RADIUS authentication remains independent of it.

Passing these checks is development evidence, not a production release
or a complete security audit. Real UniFi/iPhone TTLS/PAP connectivity and
a profile-free iPhone join through PEAP have succeeded in development
trials. Roaming and AP reauthentication enforcement need their own
qualification. The supplied-subject evaluator runs in the kernel;
the loader uses the public Registry read-snapshot API before further feature
expansion.

---

# 4 Persistent Development VM

_Peios / Reference / RADIUS_

> Persistent machine state and replaceable raw binaries for offline RADIUS development.

The helper under `tools/dev-vm` runs a virtual machine (VM) with
persistent machine state. Raw component binaries remain separately
replaceable. The helper runs no package or kernel builds. Offline boot is
the default; optional LAN boot attaches a temporary network interface to
an existing host bridge.

## 4.1 Boot and storage

`vm.py prepare` extracts the kernel and initramfs from an existing console
ISO. It appends a development hook to the initramfs; the source ISO stays
unchanged. The image must provide the version-2 `rootfs-ready` hook
sequence and the ordinary live-root strategy.

The extra hook mounts a read-only development share. Before starting
peinit, the bootstrap mounts the required ext4 state disk and binds its
directories onto `/var/state` and `/lcl/etc`. The registry hives, local
account store, random seed, machine ID, certificates, secrets, and local
policy therefore survive shutdown. `/run` remains temporary.

Disk creation and first machine initialization are separate explicit
operations. Normal boots never format or seed a disk. Missing, unreadable,
uninitialized, or incomplete required state stops startup before the
registry starts. Bootstrap failure leaves PID 1 waiting with a diagnostic;
it does not start another machine identity.

The host helper serializes runs of one VM and checks the prepared boot
assets. Keep the VM directory private: its state image contains credential
material. Back up the image only after a clean shutdown.

## 4.2 Preparing a VM

The host needs Python 3.11 or later, QEMU, xorriso, mtools, GNU objcopy,
zstd, cpio, and ext4 filesystem tools. The console image supplies the
guest shell, mount tools, security-descriptor seeder, and registry service.
QEMU uses two CPUs and 1536 MiB of memory, with hardware acceleration when
available and software emulation otherwise.

From the workspace root, prepare the existing console image:

```sh
python3 radius/tools/dev-vm/vm.py --vm local/radius-dev-vm \
    prepare local/isos/console.iso
python3 radius/tools/dev-vm/vm.py --vm local/radius-dev-vm create-state
```

Disk creation exclusively creates a 512 MiB sparse file and refuses an
existing file. Boot preparation also refuses existing boot assets.

Build raw targets directly in their component repositories. Assemble the
reported outputs into a directory with these entries:

| Entries | Raw targets |
|---|---|
| `bin/peinit2`, `bin/svctl` | peinit: `peinit2 svctl` |
| `bin/authd`, `bin/lpsd`, `bin/lps` | authd: `authd lpsd lps` |
| `bin/radiusd` | radius: `radiusd` |
| `lib/libauth.so.1` | authd: `libauth` |
| `lib/libpeios.so.0` | peios-sdk: `libpeios` |

Administration development adds `bin/radius` and `lib/libgxwi.so.1`, built
from the RADIUS `radius` target and GXWI `libgxwi` target. Stage both
together;
partial administration sets are rejected before publication. The window
also needs a running GXWI desktop; the CLI does not.

For a complete desktop, build `gxwi-server` as the static musl target
specified by GXWI's `build.gcsl`. Its restricted token cannot open a dynamic
loader or arbitrary shared libraries. Build the other desktop programs using
their component recipes. Install `libgxwi.so.1` in the guest's ordinary
library search path as well as supplying it to development services. A user
session has no service-specific `LD_LIBRARY_PATH`; a wrapper around RADIUS
alone does not make the taskbar and launcher load successfully.

LAN development adds `bin/netd`, `bin/net`, and `lib/libnetd.so.1`, built
with netd's raw `netd`, `net`, and `libnetd` targets. Stage all three
together. Partial network sets are rejected before publication. Once a
VM has a saved network attachment, every boot requires these files,
including offline boots, because its service definition persists.

Use matching SDK and authd revisions. The helper checks complete files,
checksums, and guest loader dependencies; those checks do not prove ABI
compatibility. Build-cache warnings about mismatched imported source
revisions require investigation before selecting the outputs.

For an assembled directory at `local/radius-runtime`, stage and boot it:

```sh
python3 radius/tools/dev-vm/vm.py --vm local/radius-dev-vm \
    stage initial local/radius-runtime
python3 radius/tools/dev-vm/vm.py --vm local/radius-dev-vm \
    run initial --initialize
```

Use `run initial` without `--initialize` on subsequent boots. Successful
startup reports that persistent state is mounted, followed by peinit's
ordinary boot messages and the console shell.

## 4.3 Updating development binaries

Stage every update under a different set name. Staging copies every required
files before publishing the set and does not alter the running VM.
Existing set names cannot be overwritten.

For a configured development VM, activate a staged set from its console:

```sh
bash /mnt/dev/activate.sh update-name
```

Activation copies and verifies the set before stopping services. It stops
radiusd if active, then lpsd and authd, and netd if active. It switches the
selected set, restarts netd if needed, starts lpsd and its authd dependency,
and restarts radiusd if it was active. A set that omits network binaries
cannot replace a running netd.
Service definitions must use `/lcl/radius-dev/current/bin` and explicitly
select `/lcl/radius-dev/current/lib` for library loading. Running PID 1
changes only on the next boot. Select the desired set in the next host
`run` command; runtime activation does not change the host boot selection.

A missing or damaged staged set leaves running services untouched. A
failure after services stop remains visible and requires correction or
activation of the previous set; activation promises no automatic rollback.
Old sets remain available until deliberately removed while the VM is off.

## 4.4 Qualifying the desktop

Successful sign-in and a desktop document do not establish that the shell
and management window work. With RADIUS open on Overview, run this additional
check from the host:

```sh
python3 radius/tools/dev-vm/check-desktop.py https://10.10.0.111:7780 \
    --certificate-sha256 "$GXWI_CERT_SHA256" \
    --administrator-file local/radius-administrator.json \
    --unprivileged-file local/radius-user.json
```

Supply the actual development VM address and its certificate's SHA-256
fingerprint, obtained from its console. Each private JSON file contains
`username` and `password` fields. Keep these files outside the repository and
restrict their permissions. The check pins the server certificate before
sending credentials; it never prints passwords, session cookies, or app-origin
secrets.

The check signs in as both accounts and uses the desktop's HTTP and WebSocket
protocols to verify a shell-owned taskbar panel, launcher overlay and declared
RADIUS window. It reads the app's rendered Overview: the administrator must
see Running and active saved configuration, while the non-administrator must
be denied configuration and status access. Both accounts need permission to
sign in through GXWI. This does not change configuration or group membership.
It can start or rejoin those users' desktop sessions; close them through the
ordinary desktop controls after qualification.

This protocol check does not verify browser layout, input or accessibility.
Inspect those separately in a browser. It also does not replace independent
supplicant tests or the real AP assignment and reauthentication trial.

Shut down through the matching control tool:

```sh
LD_LIBRARY_PATH=/lcl/radius-dev/current/lib \
    /lcl/radius-dev/current/bin/svctl shutdown poweroff
```

## 4.5 LAN attachment

LAN mode requires a separately configured persistent Ethernet bridge on
the host, NetworkManager, and permission to control network connections.
The launcher never moves the host's physical Ethernet configuration.
Preparing or changing the bridge is a separate administrative action;
preserve the host's addressing identity and prepare a rollback before
activating that change.

Save a stable virtual MAC address and the bridge/TAP names once:

```sh
python3 radius/tools/dev-vm/vm.py --vm local/radius-dev-vm \
    configure-lan --bridge br-peios
```

This command writes `network.json` beside the state image. It refuses an
existing file, so ordinary setup cannot replace the virtual MAC. The
configuration belongs to this VM and should accompany its state disk.

Configure the guest's `radius-dev-lan` netd profile and a matching
interface rule through the ordinary network registry settings. Static
addressing requires the address/prefix, gateway, and DNS settings; it
does not require a DHCP reservation. Do not copy addresses from another
network into this profile.

Stage a complete runtime set containing the network programs and library.
Boot it offline first to provision the service:

```sh
python3 radius/tools/dev-vm/vm.py --vm local/radius-dev-vm run lan-initial
```

In the guest, apply the prepared profile and rule, then run:

```sh
bash /mnt/dev/provision-network.sh
```

The provisioning helper creates the persistent netd state directory if
absent and configures the ordinary SYSTEM netd service using the raw
executable. It preserves existing network profiles and rules. An existing
netd definition retains its unrelated settings. The service starts at
boot and publishes network readiness through its normal control APIs.

For a VM prepared by an earlier helper version, copy the updated
`activate.sh` and `provision-network.sh` into its host `share` directory
before provisioning. No initramfs or kernel rebuild is required.

After a clean shutdown, boot with the LAN attachment:

```sh
python3 radius/tools/dev-vm/vm.py --vm local/radius-dev-vm \
    run lan-initial --lan
```

The launcher creates a temporary NetworkManager TAP profile owned by the
invoking user and connects it to the configured bridge. QEMU uses that
TAP and the saved virtual MAC. Existing TAP names are rejected. Shutdown
or a failed QEMU launch removes the temporary profile and device while
leaving the host bridge in place. The profile is not saved to disk.

Check `net status` in the guest for the matched profile, saved address,
gateway, and routed readiness. Check reachability from another LAN
machine. Routed readiness reports configured state; it does not prove
that the gateway or a remote service answers. The host must remain
connected after the VM shuts down and its TAP disappears.

LAN attachment does not expand radiusd's trusted-client configuration or
replace the offline fixture's deny-all network policy. Real AP clients,
certificates, and network admission require separate provisioning.

## 4.6 Offline qualification fixture

`tests/dev-vm/prepare.py` prepares inputs from authd's standard policy
seeds and the existing protocol-test certificate helper. Run it only for
a fresh offline VM. The guest fixture refuses an existing account store
or authentication policy and creates a development account, group,
registry marker, and loopback-only radiusd configuration. It supplies
fixed test credentials and a Connect descriptor that denies all access.
It is not real-network provisioning.

```sh
python3 radius/tests/dev-vm/prepare.py \
    --vm local/radius-dev-vm --authd authd
```

In the freshly initialized guest:

```sh
PEIOS_OFFLINE_VM_PROOF=yes bash /mnt/dev/proof-setup.sh
PEIOS_OFFLINE_VM_PROOF=yes bash /mnt/dev/proof-check.sh save
```

After binary activation and again after a clean shutdown and normal boot:

```sh
PEIOS_OFFLINE_VM_PROOF=yes bash /mnt/dev/proof-check.sh check
```

The check requires all three services active and compares the machine ID,
account domain and security identifiers, groups, configuration, policy,
and hashes of the account store and protected credentials. Its PASS
marker establishes offline persistence and activation, not a real Wi-Fi
connection. Certificate onboarding, a LAN address, UniFi integration,
and production credentials require separate provisioning and qualification.

---

# 5 Administration

_Peios / Reference / RADIUS_

> Manage RADIUS clients, policies, methods, certificates, and local service state through the CLI or GXWI.

The `radius` program provides terminal administration and a GXWI window:

```sh
radius --window
```

Both interfaces use the same management library and the caller's actual
permissions. Configuration is stored directly in the local Registry, so
editing works while radiusd is stopped. The daemon's local status endpoint is
read-only. There is no remote management listener. Use an SSH session for a
remote CLI; a GXWI desktop can present the window remotely.

## 5.1 Configuration objects

The window groups authentication, assignment, and accounting administration
into separate sections. Overview reports service and configuration activation
state.

Overview's listener field starts with the saved addresses. Background
refreshes follow external changes while the field is unchanged, preserving an
edit in progress. The saved value shown below the field remains separate from
the draft.

| Object | Purpose |
|---|---|
| Client | Source addresses, shared secret, and allowed policies |
| Access policy | Exact SSID, Connect permissions, profile, and reauthentication |
| Authentication profile | Ordered allowed methods and server identity |
| Server identity | Named certificate chain and matching private key |
| Access profile | Complete assignment settings, including an optional VLAN |
| Assignment rule | Policy-owned conditions, action, priority, and exceptions |
| Session control profile | Reusable device capabilities for Disconnect and CoA |

Objects have immutable GUIDs. Names are editable labels and can be duplicated;
an ambiguous CLI name requires a GUID. References always use GUIDs. Renaming
preserves references. Deleting and recreating an object creates a new GUID.
Management refuses deletion while another object refers to the target and
shows its dependents. It never cascades deletion.

Use these commands to inspect the current objects:

```sh
radius status
radius client list
radius policy list
radius profile list
radius identity list
radius access-profile list
radius rule list
radius dynamic-profile list
radius config check
```

`radius --help` lists commands. `--json` produces structured output, including
GUIDs and typed errors. Exit status is 0 for success, 64 for invalid
arguments, 3 for denied permission, 4 for a missing object, 5 for invalid
configuration, and 1 for other failures. Explicit secret output is raw bytes
and does not accept `--json`.

See [Access Assignment](/peios/reference/radius/access-assignment.md) for profile
selection, rule editing, explicit defaults and hypothetical policy
explanations.

The Accounting section exposes exact-session Disconnect, fresh
reauthentication, authorization updates, and command history. Each action has
an independent Accounting security descriptor right; configuration-write
access alone does not grant control of established sessions. See
[Session Controls](/peios/reference/radius/session-controls.md) for activation,
device capabilities, fallback permissions, and outcome interpretation.

## 5.2 Initial setup

`radius config init` initializes an absent configuration with schema version
2, empty object collections, and a UDP listener at `0.0.0.0:1812`. It refuses
an existing deployment. The empty configuration admits nobody. The radius
package defines the radiusd service, grants its identity the authd capability,
and reserves UDP ports 1812 and 1813 for it, as described in
[Native Integration](/peios/reference/radius/native-integration.md). The service
starts at no time until you turn it on with `radius service boot on`, then
`radius service start`.

Create a server identity first, then a profile, policy, and client. In the
window, reference pickers show object names and retain their GUIDs. CLI
references use the GUID returned by a create or list command. For example:

```sh
radius identity create Main \
    --set CertificateFiles=/path/server.pem,/path/intermediate.pem \
    --set PrivateKeyFile=/path/server.key
radius profile create Passwords \
    --set AuthenticationMethods=peap-mschapv2,ttls-pap \
    --set ServerIdentity=IDENTITY-GUID
radius policy create Household --set SSID=Home \
    --set AuthenticationProfile=PROFILE-GUID \
    --set 'ConnectSecurity=O:SYG:SYD:(A;;0x1;;;HOUSEHOLD-GROUP-SID)'
radius client create AccessPoints --set Addresses=10.10.0.0/16 \
    --set Policies=POLICY-GUID
```

Replace the placeholder GUIDs and group SID with actual values. Source
addresses must be canonical literal addresses or prefixes. The first
authentication method is preferred. Credential rejection does not cause
fallback to another method. PEAP/MSCHAPv2 requires matching authd credential
support; enabling it in a profile does not change authd's password policy.

The client receives a generated 48-character shared secret. Explicitly reveal
it and configure the same value on the corresponding RADIUS client:

```sh
radius client secret AccessPoints show
```

The window similarly requires an explicit reveal. Normal lists, records,
status, and errors contain no secret contents. Reveal still requires read
permission on the protected file. Supply your own secret using an echo-free
prompt, standard input, or a file; avoid placing secrets in process arguments:

```sh
radius client secret AccessPoints set
radius client secret AccessPoints set --file /protected/shared-secret
radius client secret AccessPoints generate
```

A generated replacement also needs updating on the corresponding client. The
policy's reauthentication interval defaults to 3600 seconds.

## 5.3 Permissions and credentials

Connect permissions decide whether an authenticated subject can use a policy.
Management permissions are the ordinary Registry key descriptor controlling
who can edit it. The window opens the existing security descriptor editor for
each, under separate controls. The CLI exposes their descriptors without a
separate permission language:

```sh
radius policy permissions Household connect
radius policy permissions Household management
```

Add an SDDL argument to set a descriptor. Configuration-write rights,
credential-file read rights, service-control rights, and local-status query
rights remain independent. The default status descriptor permits SYSTEM and
Administrators. An explicit `Settings\StatusSecurity` can change that policy;
malformed or unreadable explicit values deny queries. The endpoint checks the
kernel-attested peer token, including deny-only groups.

Certificate import accepts PEM or DER and verifies that the key matches the
leaf certificate. The window shows certificate subject, issuer, DNS names,
validity dates, and fingerprint. Import paths refer to files on the Peios
machine, including when the window is presented remotely. The program does not
issue certificates or replace a CA. Replacing an identity preserves its GUID
and dependent profile references:

```sh
radius identity inspect Main
radius identity import Main --set CertificateFiles=/path/new-chain.pem \
    --set PrivateKeyFile=/path/new-key.pem
```

Shared secrets and keys are staged as new protected files before Registry
references switch in a transaction. Failed saves remove their new files.
Successful replacement retains old files until they can safely be removed;
deleting a record does not erase credential files automatically.

## 5.4 Saving, activation, and recovery

Saving updates stored configuration. It does not claim the daemon activated
it. Overview shows saved and effective fingerprints and activation issues. The
daemon independently validates direct Registry edits. A broken reference, bad
descriptor, or unreadable credential pauses admissions until repaired; the old
policy is not silently kept active. The local status endpoint remains
available even when initial configuration is invalid.

The tools preserve malformed records for inspection and repair. Direct
Registry editing can bypass deletion safeguards. Related management writes are
transactional; there is no stale-form conflict detection.

Disabled clients, policies, and profiles deny affected admissions while
unrelated valid policy continues. A disabled shared profile affects every
policy using it; the window shows those dependents before confirmation.
Established stations are not immediately disconnected by these edits.

Service controls are separate from object state:

```sh
radius service stop
radius service start
radius service restart
radius service boot on
radius service boot off
```

Commands report submission; check status for completion. Boot preference does
not start or stop the current process. Stop and restart interrupt ongoing
authentication; existing network access can continue until reauthentication.
Routine edits reload without a service restart. No command requires a kernel
rebuild.

---

# 6 Accounting

_Peios / Reference / RADIUS_

> Durable network session reports, protected history, principal allowances, and Disconnect outcomes.

Accounting records what a network access server (NAS) reports about access:
session starts, updates, ends, and cumulative traffic counters. The reports
contain identities and device metadata. They contain no browsing history or
packet payloads. Accounting is independent of credential verification.

## 6.1 Storage and acknowledgments

radiusd authenticates the actual sender against the most specific configured
client prefix and its shared secret. An asserted NAS name never establishes
transport trust. Disabled specific prefixes mask broader enabled clients.
The accounting listener uses its own configuration path, independent of
authentication certificates and private keys.

One owner writes a private SQLite ledger at
`/var/state/radius/accounting/ledger.db`. WAL mode with FULL synchronization
commits observations, retry receipts, session interpretation, and quota
evidence together. Accounting-Response follows a successful commit. Failure,
queue pressure, and uncertain outcomes produce no success acknowledgment.
The sender can retry after a lost reply without adding the usage twice.

Batches wait at most their configured intentional delay from the oldest
queued report. Count and byte limits also flush batches. A management or
admission operation flushes pending reports first. These bounds do not promise
a total response latency during slow storage. The database owner never blocks
the authentication packet loop while it performs disk operations.

SQLite limits database pages within a transaction. Free pages remain reusable
after retention. Lowering the limit does not shrink an existing file. The
reported storage size includes the allocated database and WAL; WAL, shared
memory, and filesystem overhead require additional disk space. Automatic
checkpoints bound steady-state WAL growth, but one transaction can exceed
that checkpoint threshold. Keep filesystem headroom outside the database cap.

Corruption, foreign databases, unsupported schema versions, links, and
untrusted file descriptors do not cause automatic replacement with an empty
ledger. A separate file lock prevents two owners. Stop radiusd before copying
the database, WAL, and shared-memory files as a consistent backup set.
Rebuild reinterprets retained evidence; it cannot recover deleted evidence.

Ledger format 4 retains complete issued and requested access settings and
their exact equipment encodings. Formats 1–3 upgrade in place. Existing
evidence and unknown legacy fields are preserved. Earlier binaries refuse
format 4; keep a stopped full-state backup and prior runtime for rollback.

## 6.2 Session interpretation

Start, Interim-Update, and Stop form ordinary sessions. Accounting-On and
Accounting-Off define whole-NAS boundaries; subsystem equivalents use
Called-Station-Id. Reliable event times prevent delayed restart notices from
closing newer sessions. Missing or implausible times remain uncertain.

Tunnel and tunnel-link reports retain their own occurrences and identifiers.
They do not close or charge the parent session again. Unknown status values
remain observations without invented lifecycle effects. IPv6 and opaque
attributes remain bounded report data. A versioned declarative accounting
profile can normalize vendor attributes; profiles execute no code.

Successful local authentication creates an opaque Class reference for the
verified security identifier (SID), membership snapshot, client, policy, and
optional station. The reference and any concurrent reservation commit before
Access-Accept. Retransmissions reuse the exact signed reply and reference.
Class is a correlation receipt, not a bearer credential or logon authority.

Reports without a recognized Class can still form a session. Their asserted
username does not become a verified SID. Ambiguous matches remain unresolved.
Reauthentication can replace the membership snapshot for subsequent evidence;
earlier intervals retain their original attribution. Byte deltas across that
boundary remain approximate because the NAS supplies cumulative snapshots.

Counters retain the full unsigned 64-bit range. Regressions do not refund or
double-charge usage. Missing high words, late reports, inferred ends, and
uncertain boundaries carry warnings. Stale sessions continue to consume
concurrency until Stop, a reliable lifecycle boundary, or configured inferred
expiration. An inferred end is not a factual Stop.

## 6.3 Permissions and privacy

The local accounting socket checks the actual caller token through the kernel.
Registry management permissions, accounting query permissions, and network
Connect permissions are separate. The default accounting security descriptor
(SD) permits SYSTEM and Administrators. A policy can provide its own
accounting SD; an absent policy falls back to the global descriptor.

Accounting rights are Read (`0x1`), Personal (`0x2`), Usage (`0x4`),
Disconnect
(`0x8`), Correct (`0x10`), and Raw (`0x20`). Personal permits identity fields;
Usage permits counters. Session filtering and pagination apply caller scope
before selecting a page. A principal filter needs Personal authority over
its requested scope. Delegated usage queries do not expose global allowances.

Optional self-service compares the real caller SID with verified session
identity. It provides the caller's rows, history, and usage, without granting
Disconnect, Correct, Raw, or direct database access. A reported username alone
cannot satisfy self-service. Linked views require their separate toggle and
preserve individual session occurrences.

`AccountingRetainNames` and `AccountingRetainAttributes` control future
ingest.
They do not retroactively erase retained data. Raw packet capture is off by
default, has separate age and byte limits, and requires both retention
controls. Authentication proofs, passwords, and known key attributes are
rejected before recording. Treat unknown vendor attributes as private data.

Observation retention removes detailed reports through checkpoints. Summary
retention removes ended personal session views. Quota evidence is separate:
byte rollups and principal intervals remain available for lifetime limits.
Personal history expiry does not reset allowances or erase all SID evidence.
The detail interval samples Interim history views; it does not skip live
counter processing or deduplication evidence in the retained journal.

## 6.4 Allowances and enforcement

Allowances attach to user or group SIDs, optionally scoped to a policy.
Every applicable allowance consumes the same attributable usage independently.
Allowances never add together. Duplicate membership does not charge a group
twice. A zero maximum denies the corresponding resource.

Dimensions are received bytes, sent bytes, total bytes, total session time,
connected time, and concurrent sessions. Time amounts use milliseconds.
Total session time sums intervals. Connected time unions overlapping
intervals across applicable sessions. Five simultaneous one-hour sessions
consume five session-hours and one connected-hour. Both limits can coexist.

Periods use UTC days, Monday-based weeks, months, or lifetime. Concurrent
limits use lifetime because slots do not reset on a calendar boundary.
Cumulative byte deltas are assigned to the update's event period. A delta
crossing a reset boundary cannot be divided precisely without another report.
Use the uncertainty flags when interpreting those totals.

Admissions reserve concurrent capacity atomically before Access-Accept.
Reauthentication with the same verified account, configured client, policy,
and nonempty station identity reuses one existing active slot. Its reservation
does not charge principals already represented by that session twice. New
group memberships still reserve their own capacity. Without matching station
context, admission cannot assume it is an existing connection.
Reservations expire if no corresponding session follows. Applicable limits
can shorten Session-Timeout and request Disconnect for ongoing sessions.
Reports arrive late and devices can reject Disconnect, so enforcement is
approximate rather than an exact byte cap.

`OnAccountingUnavailable=deny-new` refuses required or limited admissions
during an outage. `allow-new` bypasses that guarantee and increments the
bypass counter. Unconstrained policies without required accounting can
continue ordinary authentication. No mode acknowledges an unrecorded report
or fabricates a durable Class reference. Storage failure does not disconnect
every existing client.

Disconnect records persist selectors, attempts, and outcomes. Requests target
the recorded source address through its configured client and shared secret.
Attempts commit before transmission. ACK, NAK, and timeout outcomes remain
separate from session state. An ACK does not manufacture Stop. General
Change-of-Authorization is outside this implementation.

Repeated requests for an occurrence with a pending, sent, or uncertain
Disconnect return the existing command. The current interface has no explicit
retry command for an uncertain result; it does not silently reset its
attempts.

## 6.5 Administration and diagnostics

The accounting status query reads `AccountingSecurity` before checking the
caller's token. A failed Registry read makes the query unavailable; it does
not substitute the default descriptor for an unreadable configuration. The
default applies only when a successful read finds no explicit setting.

Run `radius accounting init` as an administrator to provision the private
directory. Creation supplies its private descriptor atomically and requires
the KACS control-handle support described in
[Native Integration](/peios/reference/radius/native-integration.md).
Existing directories and ledger files must already have trusted
owners and private descriptors. SQLite also needs ReadAttributes on its path
prefixes. On a restrictive `/var/state`, grant the service only mask `0x80`
without inheritance; do not grant directory listing or broad data access.
Use the normal port reservation descriptor for the accounting UDP port.

Network packet admission is separate from port binding permission. An
enforcing Flow policy needs to admit incoming accounting traffic to the
configured UDP listener. Disconnect also needs permission for a new outbound
UDP flow from that listener to the configured client's Disconnect port,
conventionally 3799. Scope that exception to the intended server and AP
addresses. Replies to an admitted flow follow its existing Flow judgment.
Enable the NAS's dynamic authorization service separately; a listener or
firewall rule does not enable it on the NAS.

For an existing schema 2 development deployment, provision the `Quotas` and
`AccountingProfiles` collection keys under `Machine\Software\Radius` before
creating their first records, preserving the parent's management permissions.
Fresh `radius config init` creates all collections. This is a one-off
development upgrade, not an automatic schema migration.

Turn on `AccountingEnabled` and set `AccountingListen` under
`Machine\Software\Radius\Settings`. Client records share the existing prefix,
secret, and policy references. `ServiceKind=accounting-only` accepts
accounting for services without Wi-Fi authentication configuration. It does
not implement another authentication protocol. Consult `radiusd.regman` for
the individual controls, defaults, bounds, and restart requirements.

Use `radius accounting status`, `sessions`, `session`, `history`, `usage`,
and `commands` for protected diagnostics. Session pages return a revision and
cursor. Supply both `--after` and `--revision` for the next page; restart the
view if its revision changes. `annotate` records an actor and note.
`correct-end` requires confirmation and can only narrow a stale or inferred
end within the last known evidence bounds. `rebuild --confirm` preserves
stable occurrence IDs, usage evidence, corrections, and command history.
It does not send another Disconnect or replay accounting telemetry.

The GXWI Accounting section displays protected session details, cumulative
traffic history, allowance bars, and health. Allowances and Accounting
Profiles use the same configuration model as CLI editing. Saved settings do
not establish successful daemon activation; inspect health after changes.

eventd receives service health and operational counters only. Accounting
usernames, user SIDs, device addresses, session identifiers, Class references,
and individual traffic measurements remain in the ledger. Metric names have
the fixed `radiusd.accounting` prefix with no personal labels. Provision that
namespace with `radius accounting telemetry-init` after eventd provisioning;
the command preserves existing namespace policy. Telemetry submission is best
effort and is not the authority for limits or accounting facts.

## 6.6 Qualification

Portable checks cover independent integrity fixtures, semantic retries,
reordered reports, exact counters, principal reservations, overlapping limits,
retention, correction, rebuild, full-storage recovery, and process exit after
commit before reply. Native checks use a NIC-less disposable VM and the
production kernel, without rebuilding the kernel or packages.

A real UniFi/iPhone trial passed session Start, one-minute Interim reports,
Class correlation to the verified account despite an anonymous outer username,
Stop, and fresh reconnect occurrences. It also passed authenticated Disconnect
followed by Stop and automatic reconnection, principal time-allowance
exhaustion with subsequent admission refusal and restoration, and a daemon
restart with retained session/history followed by a continuing AP update.
Stored reports
across three APs retained the same verified identity and closed the old
occurrences. Their one-second timestamps do not establish subsecond handoff
latency, zero packet loss, or uninterrupted application traffic.

Passing fixtures does not qualify every NAS, tunnel implementation, or
vendor profile. Test real equipment for reporting frequency, Class echoing,
counter semantics, roaming, and Disconnect enforcement. A process or VM
crash test does not establish power-loss behavior of every host storage stack.
Full eventd ingestion and production-scale capacity remain separate
qualification limits.

---

# 7 Access Assignment

_Peios / Reference / RADIUS_

> Select a complete network access profile using PNP-style rules, typed identity facts, and explicit defaults.

Each access policy owns a forest of assignment rules. A successful decision
selects one complete access profile. Profiles are shared objects with stable
GUIDs; renaming a profile preserves its references.

Assignment supplements authentication, Connect permissions, and accounting
allowances. All gates must permit access before radiusd sends success or keys.
Authd supplies identity and permitted claims; it does not interpret VLANs.

## 7.1 Profiles and defaults

An access profile contains `Name`, `Enabled`, and optional typed network
settings described in [Access Profile Settings](/peios/reference/radius/access-profile-settings.md).
These include timers, rates, filters, addressing, tunnels, and equipment
extensions. The optional `VlanId` is a DWORD.
VLAN IDs range from 1 through 4094. An absent `VlanId` produces no VLAN
override. Zero is invalid. Disabling a selected profile refuses admission.

Profiles live under `Machine\Software\Radius\AccessProfiles\<guid>`. Rules
live under `AccessPolicies\<policy-guid>\Rules\<rule-guid>`, relative to the
same RADIUS root. Child rule keys are exceptions to their parent rule. `Name`
is a display label. Rule keys use canonical UUIDv4 identities.

No selected profile means refusal. An explicit catch-all rule can select a
default profile, including a profile with no VLAN override. Parent rules do
not merge settings into the selected profile.

```sh
radius access-profile create Staff --set VlanId=20
radius access-profile create Default
radius rule create Default --set Policy=POLICY-GUID \
    --set 'Actions=ASSIGN(DEFAULT-PROFILE-GUID)'
radius rule create Staff --set Policy=POLICY-GUID --set Parent=DEFAULT-RULE-GUID \
    --set Subject.Group.Equal=S-1-5-32-545 \
    --set 'Actions=ASSIGN(STAFF-PROFILE-GUID)'
```

Replace the GUID placeholders with identities returned by the creation
commands. A nested `Parent` uses slash-separated ancestor GUIDs. `Policy` and
`Parent` are derived management fields; direct Registry edits do not store
them as rule values. A rule's location remains fixed after creation.

Remove a VLAN override with `radius access-profile unset PROFILE-GUID VlanId`.
Use `radius rule unset RULE-GUID CONDITION-KEY` to remove a condition, or
`radius rule unset RULE-GUID Priority` to restore inherited priority. Deleting
an object with references is refused.

GXWI provides Access Profiles, Assignment Rules, and Explain Policy sections.
The rule editor exposes actions, profiles, conditions, and parent selection.
Shared-profile references appear in the affected-object information.

## 7.2 Rule evaluation

The evaluator shares PNP's tree traversal, ancestor fallback and collation.
Conditions on a rule are ANDed. Alternatives inside one condition are ORed.
Disabled rules hide their subtree. A matching child shadows its parent only
within that tree; independent trees still contribute candidates.

`Priority` is a signed decimal string or a DWORD. It inherits from the parent,
or defaults to zero at a root. `Actions` accepts a string or string list:

- `ASSIGN(profile-guid)` selects a complete profile.
- `REJECT` refuses admission.
- `NULL` abstains. The nearest ancestor with a direct decision speaks for
  that region, using the ancestor's priority.

The highest-priority candidate wins. At equal priority, `REJECT` wins over
assignment. Equal-priority assignments to the same profile agree. Different
profiles tied at the winning priority cause a per-connection refusal, with
both rule paths reported in operational diagnostics. Rule order has no effect
on permission. A single rule cannot select multiple different profiles.

## 7.3 Facts and types

| Fact | Meaning and type |
|---|---|
| `Subject.User` | Authd-verified user SID |
| `Subject.Group` | Authd-disclosed enabled group SIDs; any-member matching |
| `Subject.Name` | Authd's canonical username; exact string |
| `Subject.Claim.<name>.<type>` | Disclosed claim; explicit native type |
| `Client.Id` | GUID of the configured client that verified the request |
| `Client.Address` | Actual packet source IP address |
| `Request.SSID` | Reported SSID bound to the selected access policy |
| `Request.Station` | AP-reported station MAC; not device authentication |

Condition value names append an operator, such as `Subject.Group.Equal` or
`Subject.Claim.Department.String.Equal`. Claim types are `Int64`, `Uint64`,
`Boolean`, `String`, `Sid`, and `Octet`. Claim names use the same
per-character Unicode lowercase equivalence as KACS and authd, without
normalization or full case folding. String values compare exactly.

`Equal` uses one scalar or a list. Signed integers and IP addresses use PNP's
pattern grammar; unsigned integers preserve the full 64-bit range and support
decimal inclusive ranges. Numeric facts support `GreaterThan` and `LessThan`
with one threshold. Boolean patterns use `true` or `false`; octet patterns use
even-length hexadecimal strings. MAC patterns use PNP's colon-separated form.
Runtime values never convert between strings, numbers, and booleans.

Unknown facts, unsupported operators, and malformed patterns invalidate the
configuration. A known fact missing from an authentication does not satisfy an
ordinary comparison. A value of an incompatible type does not match.

`Present = 1` tests known presence; `Present = 0` tests known absence. For
claims, filtered disclosure leaves omitted names unknown unless authd
explicitly confirms absence. Neither presence test matches an unknown claim.
Disabled and deny-only claims are unavailable to assignment comparisons and
cannot prove absence. Withheld claims do not become false, zero or empty.

## 7.4 Configuration and established connections

Rules and profiles join the same short, consistent Registry snapshot as other
RADIUS configuration. Invalid, pending, or unreadable configuration pauses new
admissions and cached success replies. The status endpoint remains available
for repair; radiusd does not continue granting under an older policy.

The final authentication decision uses current policy. Semantic changes
invalidate cached acceptance replies. Existing Wi-Fi connections receive
another assignment when they next authenticate, including automatic
reauthentication. The AP controls how it applies a changed VLAN. Configurable
[Session Controls](/peios/reference/radius/session-controls.md) can act after successful
activation; VLAN-change Disconnect defaults on when automatic controls and
accounting are enabled. The exact issued baseline, current policy, and precise
session selectors determine which occurrences are affected.

A VLAN change does not assign the client's IP configuration. A client can
retain its previous DHCP lease after reauthentication and lose connectivity
until it disconnects and reconnects. Do not assume a live VLAN change is
seamless: qualify both the AP's assignment and the client's address renewal.
DHCP's [network-change guidance](https://www.rfc-editor.org/rfc/rfc2131.html#section-3.7)
describes address verification after disconnection. When testing a change,
check the client's address, gateway, and connectivity on both networks.

VLAN assignment uses the three tunnel attributes described in [RFC 3580
section 3.31](https://www.rfc-editor.org/rfc/rfc3580.html#section-3.31), with
a zero tag and a decimal VLAN string. radiusd signs the complete response,
including accounting Class and timeout attributes, before caching it.

## 7.5 Explain saved policy

Explain Policy uses the same compiler and evaluator as admission. It shows
matching conditions, shadowed rules, ancestor fallback, priorities, competing
profiles, and the backstop. Explanations contain condition outcomes, not claim
values. Normal Registry permissions govern access to rules and profiles.

The CLI accepts typed hypothetical facts from a JSON file:

```json
{
  "values": {
    "Subject.Group": [{"type": "sid", "value": "S-1-5-32-545"}],
    "Subject.Claim.Department": [{"type": "string", "value": "Engineering"}]
  },
  "claim_coverage": "filtered",
  "absent_claims": []
}
```

```sh
radius --json policy explain POLICY-GUID --facts /path/to/facts.json
```

`claim_coverage` defaults to `filtered`. Set `complete` only when the
hypothetical input intentionally asserts a complete claim set. `absent_claims`
supplies known absences separately. GXWI exposes the same knowledge
distinction.

The result identifies saved configuration and its fingerprint. It does not
claim that the daemon activated that configuration. Simulation does not verify
credentials, run Connect checks, reserve allowances, grant access, or contact
an AP.

Supplying a single `Client.Id` fact compiles the selected settings with that
client's saved equipment mapping. The returned authorization plan separates
encoded settings from missing mappings and missing client context. Successful
encoding does not establish that a device supports or enforces the attributes.

## 7.6 Bounds and development migration

The Registry loader accepts at most 1024 rules, 32 nested exception levels, 64
conditions per rule, 256 alternatives per condition and 4 MiB of rule values.
Profile count is bounded at 256. Hypothetical input has equivalent fact
bounds; the CLI file limit is 1 MiB.

Schema 3 requires explicit assignment rules. For a stopped schema 2
development deployment without assignment objects, the `migrate-policy-v3`
example prepares one default profile and a catch-all rule for each
authenticating policy. Running without arguments prints the candidate.
`--apply` creates the defaults and changes the schema in one Registry
transaction. It preserves credentials, existing records, and descriptors;
created keys inherit normal permissions. Do not edit RADIUS configuration
concurrently with this one-off migration. Keep the prior configuration and
runtime available for rollback.

---

# 8 Authentication Diagnostics

_Peios / Reference / RADIUS_

> Protected attempt timelines, exact authority links, dropped-request reports, and incomplete evidence.

`radius diagnostics` and the GXWI Diagnostics section show recorded progress
through authentication. Both read eventd using the caller's identity. radiusd
does not expose a privileged alternative history or store another diagnostic
database. Authentication does not wait for eventd storage or diagnostic
readers.

## 8.1 Attempts and outcomes

One attempt represents one authentication conversation. Retransmissions retain
its identifier. A fresh conversation, including reauthentication, gets
another.
The identifier is displayed as 32 hexadecimal digits. It is not a credential.

Milestones cover method selection, TLS, credential verification, network
permissions, assignment, and accounting admission. Repeated polling does not
create another milestone for the same result under the same configuration.
The final `radiusd.exchange.attempted` event also carries a summary that can
be read independently.

An Accept means the local UDP socket accepted the reply for transmission.
It does not confirm AP admission, DHCP, or internet access. A send failure,
timeout, and credential refusal are separate outcomes. A TLS timeout does not
prove that the person rejected a certificate.

An explicit authority denial for failed credentials or a restricted account
uses the generic `authentication-failed` reason. Unknown accounts and
incorrect passwords share that reason. Authority outages, other authority
denials, and client transport or protocol failures use
`authority-unavailable`; they do not establish that the supplied credentials
were wrong. The authority's free-form error message is not copied into this
classification.

Stage sequence numbers order one attempt. Elapsed milliseconds use the local
monotonic clock. Event timestamps can move after a wall-clock adjustment.
Separate services have separate event orders; nearby timestamps do not prove
that their events belong to the same attempt.

## 8.2 Finding evidence

Use a bounded time window and inspect whether the result was limited:

```sh
radius diagnostics list --since 900 --username alice
radius diagnostics follow --since 300 --station aa:bb:cc:dd:ee:ff
radius diagnostics show ATTEMPT-ID --since 86400
radius diagnostics drops --since 300
radius diagnostics status
```

`--network` selects an access-policy GUID. `--client` selects a client
configuration GUID. `--username` matches the supplied inner username exactly;
it does not establish identity. Station identifiers are normalized reported
MAC addresses. The outer EAP identity is not recorded.

Personal and configuration filters operate on reconstructed, readable attempts
in the returned record window. This keeps anonymous TLS stages alongside a
later supplied username. A limited record window can omit other matches.
Use a narrower time window or adjust the configured bounds when necessary.

Finite `--json` commands return structured results. The command
`diagnostics follow --json` writes one JSON object per line: `kind=status` for
reader state, or `kind=event` with an authorized record. Stop following with
Ctrl+C.

In GXWI, select Diagnostics, enter filters, and select Follow Live or Refresh
History. Details retain the selected attempt during live updates. A selected
attempt outside the returned readable window remains selected but unavailable.

## 8.3 Authority and configuration links

An authority supporting the optional PGSS operation GUID supplies an exact
link to `authd.authentication.attempted`. `show` and Read Linked Events query
that GUID and the RADIUS service caller SID. eventd independently authorizes
the authority records. Empty results do not establish that no authority event
exists. An older authority can authenticate without supplying the identifier.

Correlation is not attestation or authorization. Event type names alone do
not prove an emitter's identity. Retain readable kernel event headers when
reviewing evidence. Principal-source events are not joined by guessing from
names or timestamps.

An attempt records the effective authentication fingerprint, relevant
configuration identifiers and observed decisions. Labels and diagnostic
controls do not alter that authentication fingerprint. The saved configuration
fingerprint is separate. Historical decisions are not recomputed against
edited policy. The hypothetical Explain Policy operation remains separate.

Recorded labels remain historical. Open Current Object opens today's readable
configuration, which can differ or be unavailable after deletion or a
permission change. Current configuration never fills a field missing from the
timeline.

## 8.4 Permissions and privacy

eventd's record and field security descriptors govern both history and live
streams. RADIUS management rights do not automatically grant diagnostic read
rights. The reader does not elevate or query as radiusd. Configuration-read
permission is not required to use independently delegated event access.

Live readers run in the caller's own process. An impersonating host can use
finite history queries on its calling thread, but cannot start a live worker
that would inherit a different process identity. Reader startup checks this
boundary without requiring token-duplication or impersonation rights.

Records can include packet source addresses, AP-reported station identifiers,
supplied usernames, and verified identities. Supplied usernames remain
unverified even when an attempt succeeds. Verified names and security
identifiers come from the authentication result. The normal timeline does not
copy the full groups-and-claims snapshot.

Passwords, authentication proofs, shared secrets, private keys, and decrypted
authentication payloads are excluded. Unknown diagnostic fields are refused
by the emitter's schema guard. This interface provides no packet dump.

A field absent from eventd's response is unavailable. The reader cannot tell
whether it was never recorded or withheld. It does not recover missing fields
through configuration or a more privileged query.

## 8.5 Loss, bounds, and retention

A missing terminal event leaves the outcome unavailable. Late evidence can
complete a timeline. Disconnected streams show their state immediately,
reconnect with overlapping history, and deduplicate records. Reader renewal,
limited backfill, collection loss, and missing stage sequences can leave gaps.
Old results retained during a failed reconnect are marked disconnected.

Finite queries publish no result if eventd fails before confirming completion.
An empty successful query means no matching readable records were returned.
It does not prove that no connection was attempted.

Requests discarded before conversation allocation have separate aggregate
reports, with bounded recent samples. Client matching is not proof of request
integrity. An integrity failure does not prove a wrong shared secret.

Registry values beginning with `Diagnostics` under
`Machine\Software\Radius\Settings` control emission and reader bounds. Consult
`radiusd.regman` for defaults and valid ranges. Client bounds limit retained
records and payload bytes; decoded frames and collection structures require
additional memory. eventd applies its own query resource limits independently.

Emission reserves capacity for final summaries, without guaranteeing delivery
under overload. Collection reports expose emission failures, local rate
suppression, and records omitted by emission policy. These reports are also
best effort. Missing reports leave collection state unconfirmed.

eventd controls persistent retention and field permissions. RADIUS does not
maintain an independent retention database or replay deleted evidence.

---

# 9 Session Controls

_Peios / Reference / RADIUS_

> Reevaluate established access and send precise, durable Disconnect and CoA requests.

RADIUS session controls operate on the accounting ledger's exact connection
occurrences. They use [RFC 5176](https://www.rfc-editor.org/rfc/rfc5176.html)
Disconnect or Change of Authorization (CoA) packets. Authentication can run
without accounting; automatic session controls require its inventory.

Use the local CLI or the GXWI Accounting section:

```sh
radius accounting disconnect SESSION-GUID
radius accounting reauthenticate SESSION-GUID
radius accounting update SESSION-GUID
radius accounting reconciliation SESSION-GUID
radius accounting commands SESSION-GUID
```

These commands retain the original occurrence, NAS selectors, device source,
action, actor and configuration revision before sending. An AP-reported
username never establishes identity or selects another connection. Sessions
without precise NAS and session selectors cannot be controlled. Missing
verified identity also prevents automatic controls; manual Disconnect can
still terminate a precisely identified occurrence.

CLI and GXWI generate a request GUID. Automation can supply `--request-id ID`
and reuse it after a lost reply. The actor/request pair retains one command,
including terminal results; it cannot select another session or action. A
different deliberate action needs a new ID. Inspect command history before
repeating an operation whose reply was lost. Request IDs are not capabilities.

## 9.1 Device capabilities

A client can reference a reusable `DynamicAuthorizationProfile` GUID. Its
record lives under `DynamicAuthorizationProfiles` and contains `Name`,
`Enabled` and a JSON `Definition`. CLI uses the `dynamic-profile` object;
GXWI calls these Session Control Profiles. A missing reference uses the
generic RFC 5176 profile.

The same definition's `authorization` member supplies admission mappings,
qualified live settings and explicit reset attributes for richer profiles.
See [Access Profile Settings](/peios/reference/radius/access-profile-settings.md).
The WISPr template provides rate encodings without claiming live support.

Profiles declare bounded recipes for `disconnect`, `reauthenticate` and
`update-authorization`, optional station targeting, standard attributes and
vendor-specific encodings. They cannot run code, insert usernames as
selectors, or replace integrity, authorization, retries and replay handling.
NAS and Acct-Session-Id selectors remain mandatory. See the source definition
in `radius-accounting/src/dynamic.rs` for the complete validated schema.

`nas_selectors` chooses which recorded NAS attributes the profile transmits:
`ip-address`, `identifier`, and `ipv6-address`. Omitting it retains all
recorded NAS attributes. The list must be nonempty and contain no duplicates;
at least one selected attribute must exist on the recorded occurrence, or the
request is refused. For example, `"nas_selectors": ["identifier"]` uses only
the recorded NAS-Identifier. This changes the wire recipe, not the immutable
session target or destination. Acct-Session-Id and integrity remain mandatory.

The generic profile supports Disconnect and standard VLAN/Session-Timeout
updates. It does not claim fresh reauthentication. Clearing a VLAN override
has no universal CoA encoding; it needs an explicit device reset recipe or an
enabled fallback. A profile that advertises reauthentication must declare
`fresh_proof: true` after device qualification. RFC 5176 Authorize-Only is
reauthorization and cannot serve as that declaration.

Every request carries Message-Authenticator and Event-Timestamp. Profiles
default to `"proxy_state_nonce": true`, adding an opaque Proxy-State nonce.
Set it to false only for a NAS that rejects that attribute; durable request
allocation still applies. Responses must match the packet family, identifier,
peer, and request authenticator. Requiring a response Message-Authenticator
is configurable for
NAS compatibility. Do not advertise a device-specific recipe as qualified
until it has produced a fresh authentication exchange on that device.

Before a new request can be transmitted, the ledger reserves its timestamp
and identifier atomically with the prepared packet. The pair never moves
backwards on the machine, even after a daemon restart, accounting
rebuild, history expiration or clock rollback. Retransmissions reuse the
original committed packet. An old ACK cannot authenticate a later request
using a different reserved pair.

`identifier_reuse_seconds` controls the NAS duplicate-detection window,
defaults to 300, and accepts 1–86400 seconds. Match it to the device's window.
At most 256 new requests can be sent to one NAS address within that
window; retries reuse their original reservation. Exhaustion or clock
rollback leaves requests pending, with a waiting reason, until a valid pair
is available. Other NAS addresses have independent reuse windows. The global
pair allocator permits up to 256 new requests per second across all NAS
addresses, preventing reuse when a destination or shared secret changes.
No timestamp is moved into the future to work around exhaustion. This follows
the identifier and replay constraints in [RFC 5176](https://datatracker.ietf.org/doc/html/rfc5176#section-6.3).

The allocator is retained in ledger format 4 and seeded from stored packets
when upgrading formats 1 or 2. Take a full offline state backup before the
upgrade; earlier daemons cannot open the upgraded ledger. Ordinary evidence
rebuild and retention do not erase the allocator.

For a NAS that rejects Proxy-State, a Disconnect-only compatibility profile
can retain all recorded NAS selectors and require the recorded station:

```json
{
  "version": 1,
  "name": "Disconnect without Proxy-State",
  "proxy_state_nonce": false,
  "station_selector": true,
  "require_station": true,
  "recipes": [
    {"action": "disconnect", "fresh_proof": false, "attributes": []}
  ]
}
```

On the development UniFi AP, the generic request received an authenticated
NAK with Error-Cause 401. Omitting only Proxy-State produced an authenticated
ACK, an accounting Stop and a new session with fresh password proof. This
also worked automatically when changing the assignment to VLAN 20 and back
to no override. This qualifies Disconnect on that tested device; it does not
establish CoA update, other firmware behavior or a DHCP address change.

In the observed iPhone trial, the address eventually changed to the VLAN 20
subnet after Disconnect and fresh authentication. On the return to no
override, the phone still displayed its old address after five minutes.
Explicitly assigning the main VLAN also failed to produce a new address and
connectivity was lost. Manually toggling Wi-Fi restored an address on the
main subnet. Automatic DHCP renewal on VLAN changes is therefore not qualified
by this test. A successful Disconnect and new password proof do not establish
that the client has usable IP configuration. AP forwarding and client DHCP
behavior were not captured, so the precise cause remains unverified.

## 9.2 Automatic behavior

With accounting enabled, automatic session controls default on. The defaults
disconnect a session after its effective VLAN assignment changes or current
access is revoked, and request fresh authentication after password
replacement.
Automatic CoA authorization updates have a separate switch, default off.
Disabling VLAN-change Disconnect therefore does not implicitly select CoA.

Each access policy can override the defaults through `SessionControl` JSON.
Omitted members inherit their global values. GXWI exposes the overrides as
ordinary selectors under Access Policies:

```json
{
  "vlan_disconnect": true,
  "revoke_access": true,
  "password_reauthenticate": true,
  "update_authorization": false,
  "unavailable_grace_seconds": null,
  "fallback": []
}
```

`null` outage grace keeps existing connections and retries. A positive grace
can disconnect when current identity evaluation remains unavailable. The
timer persists across daemon restart and accounting rebuild. This requires
an active, valid control configuration; invalid or pending configuration
pauses controls as well as new successful admissions.

Reconciliation uses the original verified SID with current account status,
permitted claims, groups, Connect permissions, and assignment rules. It never
turns missing or withheld information into a grant or confirmed deletion.
Available, authorized lpsd change events are hints; periodic fresh reads cover
missed events, other sources, and restarts. Rapid hints coalesce without
continually restarting an unfinished inventory scan. Rules and shared-profile
effects use the same activation path as direct Registry edits. Renames and
unchanged effective decisions do not create session-control requests.

Only successfully activated configuration can authorize a command. A bounded
worker rechecks queued intent and retries against fresh identity state, away
from the UDP loop. Changed policy can supersede unsent commands. A transmitted
command whose relevance is lost remains uncertain: it might already have
acted.
An old occurrence's command is never redirected to a new roaming occurrence.

## 9.3 Evidence and outcomes

The ledger keeps issued authorization, desired current authorization, and
device-reported observations separate. A recorded no-VLAN-override is an
explicit issued decision. No baseline means unknown, including sessions from
older ledger versions. Missing NAS observations do not imply an applied VLAN.

Successful authentication also binds an opaque credential reference and
revision. Password, MSCHAPv2, and NTLMv2 share the local password revision.
Replacement rotates it; NT-hash backfill and storage maintenance do not.
Current lookup can detect change or ineligibility, but only successful fresh
authentication can advance the revision proved by a session. RADIUS receives
no stored password hash or private key through this metadata.

The command history distinguishes pending, sent, acknowledged, rejected,
unsupported, uncertain, and superseded outcomes. Retries retain the exact
packet across restart. Only an explicit unsupported capability permits a
configured fallback; timeout, permission refusal, missing selectors, and a
missing session do not. The default fallback reports failure. Allowed fallback
order is update, then fresh reauthentication, then Disconnect; configure only
the steps desired.

An ACK records NAS acceptance. It does not establish fresh proof, a Stop
report, reconnection, DHCP renewal, or working applications. A phone can
retain an old lease after a VLAN change. Qualify reconnection and address
renewal separately on each AP/client combination.

## 9.4 Configuration and permissions

Global controls are under `Machine\Software\Radius\Settings`. Individual
DWORDs override the corresponding `DynamicAuthorizationSettings` JSON member.
Unknown JSON members and out-of-range values prevent activation. GXWI exposes
the same controls; CLI uses `radius config set NAME=VALUE`.

The `radiusd.regman` reference owns each value's type, default, and bounds.
Controls include the scan interval and batch/work limits, identity-read
timeout, retry count and delay, command lifetime, maximum concurrent requests,
response-integrity requirements, and each automatic trigger. One identity
read can complete after the scan's work budget; its own timeout still bounds
that read.

`DynamicAuthorizationFallback` is REG_MULTI_SZ, empty by default. It accepts
`reauthenticate`, `disconnect`, or both in that order. For example, an
explicit
`disconnect` fallback lets an unsupported fresh-authentication request fall
back to terminating that occurrence. It does not bypass permissions.

Accounting SD rights add Reauthenticate (`0x40`) and Update Authorization
(`0x80`) alongside Disconnect (`0x8`). Read and Personal remain independent.
Manual requests need Read and the action right, plus every configured fallback
right, under the actual caller's token. Authorization is captured when the
durable request is submitted. Automatic requests identify radiusd as their
origin and are limited to enabled policy enforcement. Existing custom
descriptors retain their existing grants; review them before delegating new
actions. Packet bytes and shared-secret fingerprints are not returned by the
management interface.

## 9.5 Upgrade and rollback

Ledger schema 2 adds control state while preserving usage, observations,
corrections, and command history. Older sessions keep unknown baselines until
fresh authentication. Rebuild preserves outage timers and command history and
does not resend commands as a side effect. Stable reevaluations do not fsync a
heartbeat on every scan. Schema 3 adds the durable wire allocator described
above, preserving that control state.

Schema 4 retains complete logical authorization, per-setting encodings, timer
caps and command baselines. It accepts schema 1–3 records without inventing
missing legacy attributes. An acknowledged update becomes the comparison
baseline for subsequent changes, including a return to the originally issued
profile. Quota countdowns do not change the configured policy identity.

The matching lpsd uses store format 7 and persists credential bindings before
exposing an upgraded store. Preserve offline copies of both stores, their
security metadata, the prior configuration, and the prior runtime before a
live upgrade. Older binaries cannot read these newer formats. An older
development Registry can also need the `DynamicAuthorizationProfiles`
collection provisioned with the existing parent's permissions; fresh
`radius config init` creates it.

Host regression checks do not qualify an AP's fresh-authentication behavior,
VLAN reset conventions, DHCP renewal or roaming timing. Keep device-specific
qualification evidence separate from protocol and ledger tests.

---

# 10 Component Load and Recovery

_Peios / Reference / RADIUS_

> Measuring synthetic admission and accounting loads, checking storage failures, and interpreting incomplete fuzzing evidence.

`radius-qualify` is a developer tool. It uses temporary synthetic identities,
an ephemeral certificate, and exclusively created scratch directories. It
opens no external sockets, reads no deployed configuration, and contacts no
native authentication service. It does not build a package, kernel, or image.

## 10.1 Build and run

From the repository root:

```sh
pekit build --strict -j 2 qualify
pekit test --strict -j 2 qualification clippy
```

Use the executable path printed by the build. The Cargo equivalent is
`cargo build --locked -p radius-qualification`; the executable is
`target/debug/radius-qualify`. Use an optimized executable for measurements.
Do not compare debug and optimized throughput.

```sh
radius-qualify auth --requests 4096 --concurrency 32
radius-qualify accounting --requests 2048 --concurrency 256 --batch 128 --scratch-parent /path/to/scratch
radius-qualify failures --scratch-parent /path/to/scratch
```

The scratch parent must already exist. Each invocation creates a new private
subdirectory and removes it on completion. The failure fixture creates and
terminates its own child processes; it never opens an existing ledger.
`--help` lists workload options. Requests, peers, queue depth, batch size,
and completion deadlines are bounded. Unexpected rejection fails a normal
load; `--allow-overload` allows intentional rejection while still checking
request conservation and recovery.

To collect the nine standard load cases and machine context:

```sh
python3 tools/capacity-qualification.py --binary /path/to/optimized/radius-qualify --out /path/to/new-results --scratch-parent /path/to/scratch
```

The output directory must be new. The runner records the executable hash,
CPU, affinity, starting load, filesystem type, commands, exit statuses, and
JSON results. Each case has a controller deadline. Keep the report with the
source revision and build settings used to produce that executable.

## 10.2 What the workloads measure

Authentication runs full TTLS/PAP exchanges through the production
coordinator and TLS implementation. Credential verification and authorization
use a fixed synthetic backend. The measurement excludes native authd,
password hashing cost, UDP transport, APs, and client radio behavior. After
the load drains, a fresh conversation must succeed on the same coordinator.

Accounting submits unique session Start records to the real asynchronous
owner and SQLite WAL/FULL ledger. Latency runs from submission to receipt
collection and includes batching delay. Every accepted receipt must map to
a unique retained observation after stopping and reopening the owner. This
is not a mixed Start/Interim/Stop benchmark or a measurement of native packet
ingestion. Both workloads use a bounded window of outstanding work rather
than a fixed external arrival rate.

`max_pending` counts outstanding synthetic peers for authentication and
submitted receipts awaiting collection for accounting. It does not measure
internal queue occupancy. Peak RSS is the process high-water mark from Linux,
including fixtures and recovery checks. Successful completions determine
throughput and latency percentiles; rejections are reported separately.

## 10.3 Observed measurements

On 19 November 2026, the optimized hermetic build ran on a Ryzen 5 7600X
host with 12 logical CPUs available. The host was shared with other work;
starting load averages were approximately 3.7, 7.0, and 4.2. The scratch
filesystem reported `ext2/ext3`. These single-run observations establish
neither a production ceiling nor a recommended deployment limit.

| Workload | Window / batch | Completed per second | p99 latency |
| --- | --- | --- | --- |
| Synthetic TTLS/PAP, serial | 1 / none | 3,990 | 0.29 ms |
| Synthetic TTLS/PAP | 32 / none | 4,112 | 8.05 ms |
| Synthetic TTLS/PAP | 128 / none | 4,088 | 31.66 ms |
| Accounting Starts | 64 / 16 | 4,908 | 25.68 ms |
| Accounting Starts | 256 / 128 | 13,180 | 21.65 ms |
| Accounting Starts | 1,024 / 512 | 17,323 | 59.30 ms |

The timer-driven case used a 64-record window below the 512-record batch
threshold. Its one-second flush timer produced about 1.02-second p99
latency, as expected. Do not infer poor saturated throughput from that case.
Peak process RSS across all nine cases remained below 13 MiB.

The authentication overload case completed 4 and rejected 4,092 requests
with a four-attempt limit, then accepted a new conversation after draining.
The accounting overload case committed 32 and rejected 4,064 submissions
with a four-record queue; all accepted receipts survived reopening. Queue
capacity limits queued work, not all work already committed or in progress.
These rejection counts depend on the synthetic arrival pattern and timing.

## 10.4 Failure regressions

The storage fixture checks 20 cases: eight write-error points, two sync-error
points, eight full-storage points, termination during a sync, and termination
after commit before acknowledgment. It checks atomic retention, idempotent
retry, SQLite integrity, and foreign-key integrity after reopening. Faults
are installed only inside dedicated developer child processes. A fault
family must reach an injection point for its run to pass.

Other deterministic regressions check bounded authentication tables,
accounting queue saturation, recovery when an authority check becomes
available, and failed or stalled required services. The production
coordinator is exercised with unavailable event delivery: a successful
authority and admission result can still succeed, while failed required
authentication or accounting cannot produce an acceptance.

These checks passed on the host. The service failures use synthetic backend
contracts. They do not establish native service restart behavior, physical
power-loss durability, device-specific disconnect behavior, or a long soak.
See [Qualification](/peios/reference/radius/qualification.md) for independent
supplicant and disposable native gates.

## 10.5 Instrumented campaign status

The optional `fuzz/` workspace contains five bounded target adapters for
packets, engine sequences, coordinator sequences, ledger replay, and control
records. Shared entry points also support deterministic stable-Rust replay.
`tools/fuzz-qualification.py` records seeds, commands, source and executable
hashes, execution counts, coverage, logs, and artifacts in a new directory.

The first five AddressSanitizer campaign attempts all aborted during startup
on an SQLite `aiOff` global ODR diagnostic. No execution or coverage counts
were obtained, and no RADIUS failure artifact was produced. Compilation and
deterministic seed checks do not establish an instrumented campaign pass.
The instrumentation issue remains unresolved; the campaign gate is incomplete.
Do not disable sanitizer diagnostics to count this gate as passing.

The adapters have further limits: successful encrypted exchanges in the
coordinator fixture use TTLS/PAP; PEAP coverage here stops at method
selection. Control sequences exercise durable records rather than a real AP
transport. The existing independent and native protocol gates remain
necessary. None of these checks is a complete security audit.

---

# 11 Access Profile Settings

_Peios / Reference / RADIUS_

> Typed network authorization, equipment mappings, complete replies, and the limits of live updates.

An access profile describes the network service a successful authentication
requests. Assignment rules select one complete profile; the receiving
equipment enforces its attributes. The shared `radius-authorization` library
validates logical settings, compiles the reply, and retains the association
between each setting and its wire attributes for later session controls.

## 11.1 Setting families

Profiles cover connection timers, bandwidth and priority, VLAN memberships,
traffic filters and roles, gateway addressing and routes, tunnel parameters,
accounting preferences, and device administration. These are authorization
settings. Adding a gateway pool name does not add an address allocator;
device-administration settings do not add a device authentication
method. Authentication profiles and principal allowances remain separate.

The Registry interface is documented under
`Machine\Software\Radius\AccessProfiles\<guid>` in `radiusd.regman`.
Discover the same setting metadata used by CLI and GXWI with:

```sh
radius access-profile fields
```

An absent setting requests no override. An explicit false flag requests the
equipment's disabled value; it differs from absence. Unknown settings and
wrong Registry types invalidate configuration. `Extensions` is a JSON object
of typed, namespaced `Extension.<namespace>.<name>` values, with explicit
vendor mappings. It cannot override server-owned identity, selectors, keys,
EAP state, Class, or integrity fields.

Rates are per connection, in bits per second from the connected device's
perspective. Upload travels from the device; download travels to it. Bursts
are bytes. The decimal string representation preserves the complete unsigned
64-bit range. Minimum rates cannot exceed configured maximum rates. A minimum
rate requests an equipment capability; it does not reserve capacity in Peios
or enforce a principal-wide aggregate bandwidth limit.

`VlanId` is a numeric untagged assignment. `VlanName` and tagged or untagged
memberships use the distinct RFC 4675 attributes; they are not alternate
spellings of the numeric tunnel assignment. A numeric VLAN and a second
tunnel assignment cannot coexist. Named filters refer to filters installed on
the equipment. Explicit filter rules accept the supported NAS-Filter-Rule
grammar, with one complete rule per list item. Roles, isolation, QoS, and
IPv4 DNS need an explicit equipment mapping.

Addresses, canonical prefixes, routes, MTU, and tunnel parameters apply to
gateways that understand them. A route contains a destination, a gateway, and
an optional numeric metric. A prefix with host bits is refused. IPv4 netmasks
must be contiguous. Pool references do not allocate leases or control a
bridged Wi-Fi client's DHCP state. Management settings require an appropriate
management Service-Type; they do not grant a local Peios token.

`AccountingInterimSeconds` requests a NAS update interval of at least 60
seconds. It does not alter the ledger's durability rules. `ServiceLabel` is
retained local authorization metadata unless an explicit mapping also sends
it to the equipment. It never replaces the server's accounting correlation.

## 11.2 Timers and allowances

RADIUS provides one Session-Timeout and its Termination-Action. Choose a
profile reauthentication interval, or a session timeout with a disconnect or
reauthenticate action. A session timeout defaults to disconnect. Configuring
both interval settings is refused because they cannot be independent wire
timers. Idle timeout is separate and concerns inactivity after admission; the
daemon's similarly named conversation timeout bounds the authentication
exchange itself.

The network's reauthentication cap can shorten the profile timer. Principal
allowances can shorten it again. The accounting proof retains the configured
cap separately from the shorter reply, so an allowance countdown does not
create repeated policy-change commands. Disconnect expiry does not prevent
another successful authentication. Use cumulative principal allowances for
limits that span multiple successful authentications.

## 11.3 Configuring a profile

CLI and GXWI use the same validation and complete-profile selection:

```sh
radius access-profile create Guests --set VlanId=20 \
    --set IdleTimeoutSeconds=300 --set DownloadBitsPerSecond=10000000 \
    --set UploadBitsPerSecond=2000000
radius access-profile set PROFILE-GUID \
    --set 'FilterRules=["permit in 6 from any to assigned 80,443"]'
radius access-profile unset PROFILE-GUID DownloadBitsPerSecond
```

Replace `PROFILE-GUID` with the created identity. List input accepts a JSON
array when an item contains commas; simple lists also accept comma-separated
items. GXWI uses one list item per line. Clearing an optional field removes
the saved value. Saving still requires a valid complete profile; for example,
remove its expiry action when removing its associated session timeout.

The rate example requires an equipment mapping before admission can succeed.
A valid logical setting that cannot be encoded for the actual client refuses
the connection before quota reservation. It is never silently omitted.

## 11.4 Equipment mappings

The client's existing `DynamicAuthorizationProfile` also supplies its
`authorization` mapping. Its definition contains three maps: `settings` for
admission encodings, `live` for qualified CoA settings, and `clear` for
explicit removal values. A missing setting uses its defined standard encoding.
An empty encoding list explicitly marks a setting unsupported. Vendor-only
settings have no guessed default. Encodings are bounded data, not executable
plugins.

Generate the WISPr rate template with:

```sh
radius dynamic-profile template wispr
```

GXWI offers the same template while creating a Session Control Profile. It
changes the draft only. The template encodes upload and download using vendor
14122 attributes 7 and 8. It declares no qualified live rate support. It is
an attribute template, not a claim that a particular AP enforces those rates.

A custom mapping can describe integer, boolean, text, address or prefix
encodings. Integer conversion uses an exact divisor: values that would round
or overflow are refused. Text and decimal-text encodings can add bounded
prefixes and suffixes. For example, a synthetic equipment definition could
contain:

```json
{
  "authorization": {
    "settings": {
      "DownloadBitsPerSecond": [
        {
          "target": {"vendor": 12345, "attribute": 1},
          "format": "decimal-text",
          "divisor": 1000,
          "prefix": "rate=",
          "suffix": "k"
        }
      ]
    },
    "live": [],
    "clear": {}
  }
}
```

This is the authorization portion of a full Session Control Profile
definition. It is not a recipe for real equipment. Standard type checks,
protected targets, conflicting attribute owners, and the complete reply budget
apply to every mapping. A reply accepts at most 96 authorization attributes
and 2400 encoded bytes; credentials and protocol fields remain server-owned.

## 11.5 Explaining and changing established access

Explain Policy shows the selected logical settings. Supplying a single
`Client.Id` fact also compiles an authorization plan with that client's saved
mapping. The plan distinguishes unsupported settings and missing client
selection. It does not authenticate, check every admission gate, send a
packet or prove enforcement. Operational diagnostics record an assignment
fingerprint over the selected VLAN and complete compiled authorization,
without adding raw filter or extension values to events.

An automatic or manual CoA compares complete authorization settings. Changed
settings need declared live support. A removal needs an explicit reset of the
original recorded attribute; omission never means reset. A changed attribute
identity requires fresh authentication. Management protocol and transport
protection changes cannot be sent in CoA. Equipment that replaces an entire
list must be qualified for that replacement behavior.

A recipe that cannot express the new authorization uses the existing
configured fallback and its separate permissions. An ACK records what was
requested and acknowledged, not proof that every setting was enforced. The
issued baseline, desired settings, last acknowledged request, and limited NAS
observations remain distinct. See
[Session Controls](/peios/reference/radius/session-controls.md).

## 11.6 Storage and qualification

Ledger format 4 retains logical settings, exact per-setting encodings,
configured timer caps, and previous acknowledged authorization for commands.
It upgrades formats 1–3 without inventing missing legacy settings. Back up
the complete stopped ledger and prior runtime before upgrading: earlier
daemons refuse format 4. Registry schema remains 3; older readers refuse
unknown profile fields rather than grant a partial assignment.

Deterministic tests check encoding vectors, reply authenticators, protected
fields, unsupported mappings, policy selection, quota gating, retransmission,
reset handling, persistence, and frontend representations. These checks cannot
establish traffic shaping, ACL enforcement, gateway addressing, or device
administration on untested equipment. Qualify each required field on the
actual NAS and firmware before relying on its enforcement.

The underlying attribute definitions are in
[RFC 2865](https://www.rfc-editor.org/rfc/rfc2865.html),
[RFC 3580](https://www.rfc-editor.org/rfc/rfc3580.html),
[RFC 4675](https://www.rfc-editor.org/rfc/rfc4675.html),
[RFC 4849](https://www.rfc-editor.org/rfc/rfc4849.html),
[RFC 6911](https://www.rfc-editor.org/rfc/rfc6911.html), and
[RFC 5607](https://www.rfc-editor.org/rfc/rfc5607.html).
