# KACS

> Peios kernel kacs documentation.

---

# Overview

_Peios Kernel / Internals / KACS / Start here_

> KACS is the security core of Peios — an LSM inside PKM providing identity-based access control — and how it relates to MS-DTYP.

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

The Kernel Access Control Subsystem is the security core of Peios: an LSM
within PKM providing identity-based access control in the Linux
kernel. It is the sole identity-based authorization mechanism for
managed objects. Every identity-based decision — a file open, a
registry read, an IPC connection, a signal, a token operation — passes
through one evaluation function, AccessCheck.

This chapter covers tokens ([The Token Model](</kernel/internals/kacs/tokens/the-token-model.md#trm-3-2-1>)), the Process Security Block ([The PSB Model](</kernel/internals/kacs/process-security/state-and-lifetime.md#trm-3-3-1>)),
privileges ([The Privilege Model](</kernel/internals/kacs/privileges/the-privilege-model.md#trm-3-4-1>)), impersonation ([Impersonation Levels](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-1>)), binary signature verification
([Binary Signature Verification](</kernel/internals/kacs/executable-trust/signature-verification.md#trm-3-6>)), Process Integrity Protection ([Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)), the AccessCheck algorithm
in full ([AccessCheck Overview](</kernel/internals/kacs/access-check/accesscheck-overview.md#trm-3-8-1>)), file enforcement ([The Handle Model](</kernel/internals/kacs/file-security/the-handle-model.md#trm-3-9-1>)), and how Peios identity is
projected onto the Linux credential model ([Credential Projection](</kernel/internals/security/credentials.md#trm-3-10-1>)).

The kernel-private storage and call-site inventory is in [LSM integration](</kernel/internals/kacs/integration/lsm-hooks-and-object-state.md#trm-3-e>): the LSM
security blobs, every registered KACS hook, and the direct metadata
entry points used by patched file-descriptor operations.

Two bodies of material that KACS owns conceptually live elsewhere in
the documentation. The binary structures — SIDs, security descriptors,
ACLs, ACEs, access masks, conditional ACE bytecode — are specified in
PCDS, because userspace tooling constructs and interprets them and has
to agree with the kernel byte for byte. The signing format a third
party would use to sign a binary with a PIP level is specified in
PSPK; this chapter describes only the verification side. What remains
here is the kernel's own behaviour: how it holds identity, and how it
decides.

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

## Terminology

A **token** is a per-thread identity object held in the kernel's
credential structure, carrying a user SID, group SIDs, a privilege
bitmask, an integrity level, an impersonation level, and metadata.
Identity fields — SIDs, type, integrity level — are immutable; policy
fields — enabled privileges, enabled groups, default owner, group and
DACL — are atomically adjustable. Every thread has a token, and there
is no such thing as a null token.

A **primary token** defines a process's baseline identity and is
inherited on fork, reached through `task->real_cred`. An
**impersonation token** temporarily overrides it for access decisions
on one thread only, reached through `task->cred`.

A **LogonSession** is a kernel object representing one authentication
event: a session ID, a logon type, a user SID, an authentication
package, a logon time, and a logon SID. Tokens reference their session
by ID.

A **privilege** is a system-wide right carried on a token. Some
influence AccessCheck; others gate a standalone operation.

An **impersonation level** controls how far an identity can travel:
Anonymous, Identification, Impersonation, or Delegation. It is a
ratchet carried by every token, primary or impersonation, and only
ever goes down ([Impersonation Levels](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-1>)).

An **integrity level** is a vertical trust classification on tokens
and objects. Numerically it is the mandatory label SID's single
sub-authority compared as an unsigned integer, so any `S-1-16-<n>`
with exactly one sub-authority is valid. In practice five standard
levels form a strict total order — Untrusted (0), Low (4096), Medium
(8192), High (12288), System (16384) — and non-standard values such as
`S-1-16-8448` appear only in SDs authored for Windows interop.
**Mandatory Integrity Control** is the constraint evaluated before the
DACL, blocking write access, and optionally read and execute, when the
caller's level is below the object's label.

**Process Integrity Protection** is a two-dimensional trust model —
type against trust level — protecting processes and objects from
insufficiently trusted callers. Unlike MIC, it revokes rights that a
privilege would otherwise have granted.

The **Process Security Block** is a per-process structure carrying PIP
identity, process mitigations, and process restrictions. It is never
affected by impersonation, which is the point of keeping it separate
from the token.

**FACS**, the File Access Control Shim, is the part of KACS that
replaces Linux DAC with security-descriptor evaluation on files. It
enforces the handle model: AccessCheck runs at open time and the
granted mask is cached on the file description, with later operations
checked against the cached mask.

An **object type** is the category of a protected resource. Each
defines a GenericMapping table translating generic rights into
object-specific ones.

The **TCB** — the components whose correct behaviour is necessary for
system security — is the Linux kernel, PKM, and the core trusted
userspace daemons: peinit, authd, and loregd.

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

## Relationship to MS-DTYP

KACS is not a port of another system's security model. Tokens,
security descriptors, AccessCheck, structured SIDs, and per-thread
impersonation were chosen because they solve what Peios needs solved:
coherent identity, rich per-object access control, scoped delegation,
and integrated audit.

Those same primitives are the ones Active Directory uses, and Peios is
built to join AD domains as a first-class member — exchanging security
data with domain controllers, authenticating through Kerberos, and
enforcing policy distributed by Group Policy. That imposes binary
format compatibility, which PCDS specifies: an SD written by a Windows
domain controller and replicated through Samba is evaluated by KACS
without translation.

Format compatibility does not imply evaluator compatibility in every
corner. Given the same token, descriptor, and desired mask, KACS
generally reaches the same decision MS-DTYP describes, which is what
makes policy authored in an AD environment behave predictably here.
Where it deliberately does not, [Departures from MS-DTYP](</kernel/userspace/native/kacs/ms-dtyp-compatibility-and-divergences.md#trm-3-b>) records every departure and why.

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

## Build configuration

`CONFIG_SECURITY_PKM=y` and `CONFIG_RUST=y` are required, as are
`CONFIG_STRICT_DEVMEM=y` and `CONFIG_MODULE_SIG_FORCE=y`. The last two,
and the absence of every other MAC LSM and of `CONFIG_BPF_LSM`, are
enforced at build time by `BUILD_BUG_ON` in `pkm_init` ([Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)): a kernel
configured without them does not compile. They were once checked at
initialisation instead, which is no refusal at all -- the LSM framework
answers a failed init with a warning and boots with the hooks
uninstalled, the opposite of what the gate intends (PEI-487). <a id="cite-abi-notes.build.configs-enforced-at-build"></a>
`CONFIG_SECURITY_SELINUX`, `_APPARMOR`, `_SMACK` and `_TOMOYO` are
additionally refused by Kconfig dependency. `CONFIG_LSM` is never
parsed.

Two further symbols gate large bodies of code:

- `CONFIG_SECURITY_PKM_KUNIT`, which compiles in the test harness and,
  in the signing path, a different and publicly known verification key
  ([Binary Signature Verification](</kernel/internals/kacs/executable-trust/signature-verification.md#trm-3-6>)). <a id="cite-abi-notes.build.kunit-test-key"></a>
- `CONFIG_STRATAFS_FS`, without which the copy-up API of [The StrataFS Copy-Up Context](</kernel/internals/stratafs/security/kacs-admission-and-object-phases.md#trm-3-9-7>) is
  inert. <a id="cite-abi-notes.build.stratafs-gates-copy-up"></a>

## Related explanations

- [ABI status and naming differences](</kernel/userspace/native/kacs/abi-status-and-naming-differences.md>)
- [Descriptor and ACE semantics](</kernel/userspace/native/kacs/descriptor-and-ace-semantics.md>)
- [Token query semantics](</kernel/userspace/native/kacs/token-query-semantics.md>)
- [Socket ABI compatibility](</kernel/userspace/native/kacs/socket-abi-compatibility.md>)

## Calling the subsystem

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

## Topics

- [Tokens](</kernel/internals/kacs/tokens/overview.md>)
- [Process security](</kernel/internals/kacs/process-security/overview.md>)
- [Privileges](</kernel/internals/kacs/privileges/overview.md>)
- [Impersonation](</kernel/internals/kacs/impersonation/overview.md>)
- [Executable trust](</kernel/internals/kacs/executable-trust/overview.md>)
- [Access check](</kernel/internals/kacs/access-check/overview.md>)
- [File security](</kernel/internals/kacs/file-security/overview.md>)
- [Linux credentials](</kernel/internals/kacs/linux-credentials/overview.md>)
- [System V IPC](</kernel/internals/kacs/system-v-ipc/overview.md>)
- [Network objects](</kernel/internals/kacs/network-objects/overview.md>)
- [Mount namespaces](</kernel/internals/kacs/mount-namespaces/overview.md>)
- [Auditing](</kernel/internals/kacs/auditing/overview.md>)
- [Integration](</kernel/internals/kacs/integration/overview.md>)

---

# Boot and trust invariants

_Peios Kernel / Internals / KACS / Start here_

> Boot and trust invariants: behaviour and implementation of the Peios kernel.

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

KACS depends on a kernel configuration that protects the kernel trust boundary
and installs its enforcement hooks. The supported build records that
configuration in `peios/config/pkm.fragment` and checks it with
`peios/verify-config.sh`. Kconfig and compile-time assertions impose additional
constraints. These mechanisms have different failure behaviour; a build
requirement is not an init-time check.

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

## The LSM stack invariant

PKM implements KACS through the Linux Security Module framework and direct
integration points. The supported configuration uses
`CONFIG_LSM="landlock,lockdown,integrity,pkm"`. Capability hooks are implicit in
the framework. See [LSM hooks and object state](</kernel/internals/kacs/integration/lsm-hooks-and-object-state.md>)
for the registered hooks and direct callers.

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

### What the kernel verifies

`security/pkm/Kconfig` requires security support, Rust, a 64-bit target,
`STRICT_DEVMEM` and `MODULE_SIG_FORCE`. It excludes SELinux, AppArmor, SMACK and
TOMOYO. In `security/pkm/kacs/lsm.c`, `pkm_init()` also has `BUILD_BUG_ON`
checks for those MAC LSMs, the BPF LSM, and the two hardening prerequisites.
An incompatible configuration fails to build; it is not a supported path
where the kernel boots and PKM merely declines to activate.

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

### The required stack

The supported build disables the conflicting MAC LSMs, BPF LSM and Yama and
checks the exact LSM list. Yama's ptrace policy would introduce an independent
attach decision ahead of KACS. Landlock, lockdown and integrity remain in the
configured stack; their presence does not turn KACS into the authority for
every Linux check. Native process and object policy must be understood
alongside the particular interface's remaining checks.

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

## Module signing

`CONFIG_MODULE_SIG_FORCE=y` is a PKM build prerequisite. Module loading also
has authorization checks, but possession of a loading privilege does not
waive signature verification. The signature establishes trust in executable
kernel code; it does not prove the module is free of defects.

The authoritative operational explanation is
[Module signing](</kernel/administration/admin-guide/boot/module-signing.md>),
including Peios's supported signing mechanism and load failures. Kernel
module signatures and executable PIP signatures must not be treated as an
interchangeable format or key-selection mechanism.

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

## The module-loading helper

Kernel-initiated userspace helpers are subject to KACS executable verification
and the helper integrity floor. That is separate from verification of the
module subsequently requested by a helper. The executable must meet the
helper rule, and the module must independently meet module-loading policy.
See process integrity protection ([Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)) and executable verification ([Binary Signature Verification](</kernel/internals/kacs/executable-trust/signature-verification.md#trm-3-6>)).

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

## Memory access restrictions

`CONFIG_STRICT_DEVMEM=y` is a build prerequisite and limits physical-memory
access according to the architecture's implementation. It must not be
described as a universal list of accessible physical regions or as the sole
defence against process-isolation bypasses. KACS also gates relevant device
and physical-memory operations; see process integrity protection ([Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)).

The status of `/dev/kmem` follows the supported kernel's interfaces and
configuration, rather than being implied by `STRICT_DEVMEM` alone. A native
descriptor grant does not waive another check performed by the device path.

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

## What the kernel will not have

The supported configuration excludes SELinux, AppArmor, SMACK, TOMOYO, BPF LSM
and Yama. The first five are also covered by PKM compile-time assertions.
Keep the distinction between configuration validation and compile-time
enforcement when changing the supported build; do not infer a universal
runtime rejection mechanism from the configuration file.

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

## What about user-space hardening

Service signing and deployment policy are additional requirements. The kernel
derives executable integrity from the verified executable and applies the
rules for the particular exec path. A service being intended as part of the
trusted computing base does not itself assign a PIP tier.

Kernel integrity requirements do not establish that a complete image has the
right service binaries, signatures, descriptors or startup ordering. Those
are properties of the assembled deployment and must be checked there.

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

## The invariant verification

Use the supported build entry points described in
[Building Peios](</kernel/development/start-here/building-peios.md>); they apply
and validate the Peios configuration. During PKM initialization,
`pkm_init()` initializes the Rust state, creates bootstrap tokens, constructs
the initial process security state and installs the hooks on success.
Allocation and initialization errors are separate from rejected build
configurations and are not evidence that all boot failures are fail-stop.

The initial userspace program is selected by the boot and init configuration.
The kernel's bootstrap tokens do not by themselves specify the full
prelude/peinit deployment sequence.

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

## Failure modes

A rejected configuration should fail the build or its verification step.
A runtime initialization failure must be diagnosed from the actual init
return path and kernel messages. Do not assume that an ordinary LSM init
error necessarily halts the Linux boot process.

Disabling enforcement prerequisites or changing the LSM stack creates a
different kernel configuration and requires a fresh review of its security
properties. A successful boot alone does not establish that the intended
policy is active. The supported configuration checker and the runtime LSM
list exposed by securityfs provide distinct evidence.

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

## Why these invariants

Native access control assumes that kernel code and data retain their
integrity. Restrictions on loading executable kernel code and accessing
physical memory help protect that boundary. The LSM configuration ensures
that the supported build includes the intended enforcement components.

These are necessary conditions for the intended system, not a proof that
there are no kernel defects or other authority paths. Interface-specific
checks and deployment validation remain relevant.

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

## Where to go next

Read [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the
Linux compatibility boundaries, KACS process integrity ([Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)) for runtime
protection, and [Building Peios](</kernel/development/start-here/building-peios.md>)
for configuration and build validation.

---

# Tokens

_Peios Kernel / Internals / KACS / Tokens_

> Find the Peios kernel articles about tokens.

Use these articles to understand tokens in the Peios kernel.

- [The Token Model](</kernel/internals/kacs/tokens/the-token-model.md>)
- [Token Structure](</kernel/internals/kacs/tokens/token-structure.md>)
- [Token Lifecycle](</kernel/internals/kacs/tokens/token-lifecycle.md>)
- [Token Creation](</kernel/internals/kacs/tokens/token-creation.md>)
- [Token Adjustment](</kernel/internals/kacs/tokens/token-adjustment.md>)
- [Linked Tokens and Elevation](</kernel/internals/kacs/tokens/linked-tokens-and-elevation.md>)
- [LogonSessions and Revocation](</kernel/internals/kacs/tokens/logonsessions-and-revocation.md>)
- [Token Access Rights](</kernel/internals/kacs/tokens/token-access-rights.md>)

---

# The Token Model

_Peios Kernel / Internals / KACS / Tokens_

> A token is a thread's identity and security policy — how it relates to Linux credentials, primary against effective, and the evaluation context.

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

A token is a kernel object representing a thread's identity and
security policy: the user's SID, group memberships, privileges,
integrity level, impersonation state, claims, confinement settings,
and metadata. Every KACS-mediated access control decision evaluates
the thread's effective token. <a id="cite-token.decisions-use-effective-token"></a>

Every live userspace thread has one. <a id="cite-token.every-thread-has-one"></a> KACS-mediated authorization never
evaluates a null token — credentials that are blank, uncommitted,
kernel-only, asynchronous, or otherwise outside a meaningful userspace
evaluation context may carry no token at all, and an LSM hook that
reaches KACS with such a credential fails closed rather than evaluate
a meaningless identity. <a id="cite-token.null-credential-fails-closed"></a>

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

## Relationship to Linux credentials

Tokens are independently allocated, reference-counted kernel objects.
A `struct cred` holds a *pointer* to the token in its LSM security
blob, not the token data itself.

That indirection is architecturally load-bearing. Linux credentials
are immutable once committed: after `commit_creds()` a `struct cred`
cannot be modified. Had token data been embedded in the credential,
every token mutation — toggling a privilege, adjusting a group — would
have required allocating a whole new credential. Keeping the token
behind a pointer lets token-internal mutations use the token's own
synchronisation and leave the credential alone.

Several thread credentials within a process may reference one token
object through `real_cred`, and a mutation to a shared token is
visible to every thread sharing it. <a id="cite-token.shared-within-process"></a> At fork the child receives an
independent deep copy, so mutations after fork are invisible across
the process boundary.

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

## Primary and effective tokens

The `real_cred`/`cred` split on `task_struct` carries two roles.

`real_cred` is the task's **objective** identity, used when other
tasks evaluate access *to* this task. Its LSM blob points at the
**primary token** — the process's baseline identity, inherited from
the parent at fork. <a id="cite-token.real-cred-is-objective"></a>

`cred` is the task's **subjective** identity, used when this task
evaluates access to other objects. Its blob points at the **effective
token**: normally the primary token, or an impersonation token
installed by a server thread acting for a client. <a id="cite-token.cred-is-subjective"></a>

With no impersonation in play, `real_cred` and `cred` are the same
credential and resolve to the same token. Impersonation swaps `cred`
to a new credential pointing at a different token; reverting restores
`cred` to `real_cred`. <a id="cite-token.impersonation-swaps-cred-only"></a>

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

## Evaluation context

Token evaluation — AccessCheck, privilege checks — happens only where
a meaningful subject authority exists. In task context that authority
is the effective token reached through `current_cred()`.

Linux credential substitution is authoritative for deferred work. When
a kernel path runs under credentials installed by `override_creds()`
or another subjective-credential mechanism, the token pointer in that
credential's blob travels with it and is evaluated normally. KACS does
not strip authority merely because the current task carries a
kernel-thread, workqueue, or io_uring-worker flag — the credential is
what counts, not the worker flag. <a id="cite-token.override-creds-authoritative"></a>

Authorization already cached on an object handle, such as the granted
mask on a file description, continues to use that cached authority for
post-open operations. <a id="cite-token.cached-handle-authority-persists"></a> User-originated asynchronous work that has
neither captured credentials nor cached handle authority reaches KACS
without a token-bearing credential and fails closed. <a id="cite-token.uncaptured-async-fails-closed"></a>

Kernel-originated infrastructure work running under the boot SYSTEM
credential evaluates as SYSTEM. <a id="cite-token.kernel-work-evaluates-as-system"></a> There is no separate worker-flag-based
kernel authority identity.

---

# Token Structure

_Peios Kernel / Internals / KACS / Tokens_

> Every token field by mutability class — fixed identity, adjustable privileges, one-way elevation — and what each carries.

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

Token fields fall into three mutability classes. **Fixed** fields are
set at creation and never change — every security-critical identity
field is fixed. **Adjustable** fields can be modified at runtime
through the adjustment operations ([Token Adjustment](</kernel/internals/kacs/tokens/token-adjustment.md#trm-3-2-5>)). **One-way** fields can be
set or tightened but never cleared or loosened. <a id="cite-token.mutability-classes"></a>

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

## Identity core (fixed)

| Field | Type | Description |
|---|---|---|
| `user_sid` | SID | The token's primary identity. |
| `user_deny_only` | bool | When true, the user SID matches only deny ACEs, never allow ACEs. Set at creation by CreateToken or FilterToken. True whenever `write_restricted` is true. <a id="cite-token.user-deny-only-with-write-restricted"></a> |
| `groups` | SID_AND_ATTRIBUTES[] | Group memberships. The set of SIDs is fixed at creation; the per-group attribute flags are adjustable. |
| `restricted_sids` | SID_AND_ATTRIBUTES[]? | Secondary SID list for restricted tokens, null on unrestricted ones. Set at creation by CreateToken or FilterToken. AccessCheck treats the list as presence-based: a restricting SID participates whenever it is present, and neither `SE_GROUP_ENABLED` nor `SE_GROUP_USE_FOR_DENY_ONLY` affects restricted-pass matching. <a id="cite-token.restricted-sids-presence-based"></a> |
| `write_restricted` | bool | When true, the restricted SID check applies only to write access. Set at creation by CreateToken or FilterToken. |

The **logon SID** — `S-1-5-5-X-Y`, tying the token to its
LogonSession — is not stored as a token field at all. It is derived
from the session on every read, and materialised once in `groups`
carrying `SE_GROUP_LOGON_ID`, which is where AccessCheck finds it. <a id="cite-token.logon-sid-materialised-in-groups"></a>

The group SID set is fixed at creation — adjustment never adds or
removes a SID. <a id="cite-token.group-set-fixed"></a> Individual groups can be enabled or disabled by
modifying `SE_GROUP_ENABLED`, within two limits: a mandatory group
(`SE_GROUP_MANDATORY`) cannot be disabled, and a deny-only group
(`SE_GROUP_USE_FOR_DENY_ONLY`) cannot be re-enabled. <a id="cite-token.group-toggle-limits"></a>

A token holds at most 1024 group entries including the kernel-injected
logon SID, so CreateToken accepts at most 1023 caller-supplied groups. <a id="cite-token.group-limit-1024"></a>

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

## Token type (fixed)

| Field | Type | Description |
|---|---|---|
| `token_type` | enum | Primary or Impersonation. |
| `impersonation_level` | enum | Anonymous, Identification, Impersonation, or Delegation. On every token it is the ceiling on what may be derived from it: an impersonation token acts at this level, and a primary token bounds everything captured from, conveyed by, or duplicated out of the process carrying it ([Impersonation Levels](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-1>)). |

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

## Integrity (fixed)

| Field | Type | Description |
|---|---|---|
| `integrity_level` | uint | Numeric integrity level. Standard values are 0 (Untrusted), 4096 (Low), 8192 (Medium), 12288 (High), 16384 (System), but any unsigned integer is valid and is compared numerically against object labels. <a id="cite-token.integrity-level-any-unsigned"></a> |
| `mandatory_policy` | flags | `NO_WRITE_UP` (0x0001) and `NEW_PROCESS_MIN` (0x0002). Per-token MIC enforcement policy, set at creation. |

`mandatory_policy` is immutable: a process cannot change its own MIC
constraints at runtime, neither loosening nor tightening them. <a id="cite-token.mandatory-policy-immutable"></a> This is
a deliberate departure from MS-DTYP, where the mandatory policy is
runtime-modifiable — which reduces MIC to a constraint that stops only
processes not actively trying to bypass it. Immutability is what makes
MIC a real boundary here, and it is also what allows the impersonation
integrity ceiling ([Impersonation Levels](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-1>)) to be enforced unconditionally.

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

## Privileges (adjustable)

Each privilege on a token has four independent states.

**Present** — the privilege exists on the token. A present privilege
can be removed permanently, but no privilege can be added after
creation. <a id="cite-token.priv.no-add-after-creation"></a> **Enabled** — the privilege is currently active; only
present privileges can be enabled or disabled. <a id="cite-token.priv.enable-requires-present"></a> **Enabled by default**
— the creation-time enabled state, which adjustment can restore.
**Used** — the privilege has been exercised during this token's
lifetime; monotonic, and never cleared once set. <a id="cite-token.priv.used-is-monotonic"></a>

The lifecycle runs: present and disabled, to enabled, to used, then
optionally disabled, then optionally removed permanently. Removal
clears the privilege from the present, enabled, and enabled-by-default
states together. <a id="cite-token.priv.removal-clears-three-states"></a>

The four states are encoded as four 64-bit bitmasks, one bit per
defined privilege, which makes a privilege check constant-time and a
multi-privilege operation atomic.

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

## Elevation (one-way)

| Field | Type | Description |
|---|---|---|
| `elevation_type` | enum | Default (non-elevated), Full (elevated), or Limited (filtered). |

A token is created as Default. <a id="cite-token.elevation-default-at-creation"></a> Only `KACS_IOC_LINK_TOKENS` sets Full
or Limited, when a linked pair is established, and once set neither
reverts to Default on that token object. <a id="cite-token.elevation-only-link-sets"></a> The role is sticky: relinking
can replace the partner but never converts Full to Limited or the
reverse. <a id="cite-token.elevation-role-sticky"></a> DuplicateToken and FilterToken produce new token objects
whose `elevation_type` starts again at Default, because a new token is
not part of any linked pair. <a id="cite-token.elevation-resets-on-derivation"></a>

Linked pairs are associated at the LogonSession level rather than
stored on individual tokens; [Linked Tokens and Elevation](</kernel/internals/kacs/tokens/linked-tokens-and-elevation.md#trm-3-2-6>) describes the pairing mechanism.

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

## Default object security (adjustable)

| Field | Description |
|---|---|
| `owner_sid_index` | Index into `[user_sid, groups...]` selecting the default owner SID for new objects: 0 is the user SID, 1..N are `groups[0..N-1]`. The referenced SID is the user SID or a group carrying `SE_GROUP_OWNER`. <a id="cite-token.owner-index-rule"></a> |
| `primary_group_index` | Index into `[user_sid, groups...]` selecting the default primary group. The referenced SID is the user SID or any group SID on the token. <a id="cite-token.primary-group-index-rule"></a> |
| `default_dacl` | The DACL applied to objects this token creates when no explicit descriptor is supplied. It is kept as given; its generic rights are mapped through each new object's GenericMapping when it is copied into that object's descriptor. |

Storing indices rather than SID copies keeps the owner and primary
group consistent with the group array they name.

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

## Metadata (fixed)

| Field | Type | Description |
|---|---|---|
| `token_id` | LUID | Unique identifier for this token instance. |
| `token_guid` | UUID | 128-bit identifier for this token instance, generated by the kernel at creation and immutable. Used by KMES for identity stamping and event correlation; readable through `KACS_TOKEN_CLASS_GUID` under `TOKEN_QUERY`. |
| `auth_id` | LUID | The LogonSession LUID, linking the token to the authentication event that produced it. |
| `source` | TOKEN_SOURCE | Who minted the token: an 8-character name plus a LUID. |
| `created_at` | timestamp | When the original token was minted by CreateToken. Copied unchanged by DuplicateToken, FilterToken, and `NEW_PROCESS_MIN`, so it tracks original minting rather than duplication. <a id="cite-token.created-at-tracks-minting"></a> |
| `expiration` | timestamp | When the token becomes invalid; zero means no expiry. Not enforced by AccessCheck. <a id="cite-token.expiration-not-enforced"></a> |
| `origin` | LUID | The originating LogonSession for derived tokens, such as S4U or network logon. |

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

## Mutation tracking (adjustable)

| Field | Description |
|---|---|
| `modified_id` | Counter incremented on any token adjustment. <a id="cite-token.modified-id-bumps-on-adjustment"></a> |

Marking a privilege used is audit and accounting state rather than an
access-decision input, so it stays monotonic but does not bump
`modified_id`. Setting the elevation type is the one other mutation
that leaves the counter alone. <a id="cite-token.modified-id-exemptions"></a>

The counter is intended as a cache invalidation key — a `modified_id`
that has changed since a cached decision was taken means the decision
is stale. Nothing currently reads it for that purpose: it is
maintained on every adjustment and reported through the statistics
query class, and no cache anywhere invalidates on it. <a id="cite-token.modified-id-nothing-invalidates"></a>

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

## Interactivity scope (adjustable)

| Field | Description |
|---|---|
| `interactivity_scope` | 0 for services, which have no interactive environment; 1 and above for interactive and remote user environments. Changing it requires `SeTcbPrivilege`. <a id="cite-token.interactivity-scope-needs-tcb"></a> |

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

## Claims and security attributes (fixed)

| Field | Type | Description |
|---|---|---|
| `user_claims` | CLAIM_ATTRIBUTES[] | Name-value pairs from the user's directory object, fed into conditional ACE evaluation. |
| `device_claims` | CLAIM_ATTRIBUTES[] | Name-value pairs from the machine's directory object. |

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

## LCS registry credentials (fixed)

| Field | Type | Description |
|---|---|---|
| `lcs_scope_guids` | GUID[] | Ordered private registry scope GUIDs used by LCS private hive routing. LCS checks the list in order before falling back to global hives. |
| `lcs_private_layers` | string[] | Registry layer names visible to this token even when disabled globally, using LCS layer-name syntax and matching rules. |

These are KACS-owned credential material belonging to LCS. They are
fixed at creation and copied by duplication and filtering, and
attaching them is authorized by the same trusted-minting gate as the
rest of CreateToken — only a caller holding `SeCreateTokenPrivilege`
can create a token carrying them. <a id="cite-token.lcs-credentials-fixed-and-gated"></a>

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

## Device identity (fixed)

| Field | Type | Description |
|---|---|---|
| `device_groups` | SID_AND_ATTRIBUTES[]? | The machine's group memberships, for compound identity. |
| `restricted_device_groups` | SID_AND_ATTRIBUTES[]? | Filtered device groups for restricted tokens. |

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

## Confinement (fixed)

| Field | Type | Description |
|---|---|---|
| `confinement_sid` | SID? | Places the token in a default-deny sandbox; null means unconfined. When set, AccessCheck switches to default-deny and access requires an explicit grant to this SID or to a SID present in `confinement_capabilities`. <a id="cite-token.confinement-sid-default-deny"></a> |
| `confinement_capabilities` | SID_AND_ATTRIBUTES[] | Declared access capabilities for a confined process, empty if none. The `attributes` field is carried for wire-format uniformity only: AccessCheck treats capability membership as presence-based and consults neither `SE_GROUP_ENABLED` nor `SE_GROUP_USE_FOR_DENY_ONLY` when matching confinement SIDs. <a id="cite-token.confinement-capabilities-presence-based"></a> |
| `isolation_boundary` | bool | Adds namespace filtering on top of confinement, making objects outside the boundary invisible rather than merely denied. Requires `confinement_sid`. Settable at creation but not enforced. <a id="cite-token.isolation-boundary-not-enforced"></a> |
| `confinement_exempt` | bool | Escape hatch: confinement restrictions are not evaluated at all. <a id="cite-token.confinement-exempt-skips-evaluation"></a> |

`ALL_APPLICATION_PACKAGES` participates only when it is present in
`confinement_capabilities`. KACS never synthesises it, and equally
never rejects an otherwise valid confined token merely because it is
present — strict confinement is expressed by the caller omitting it. <a id="cite-token.all-application-packages-not-synthesised"></a>
Deciding which capabilities a package token receives is authd's job
and policy tooling's, not the kernel's.

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

## Audit (fixed)

| Field | Type | Description |
|---|---|---|
| `audit_policy` | u32 | Per-token audit overrides as a bitmask, fixed at creation — no adjustment operation exists. <a id="cite-token.audit-policy-fixed"></a> |

| Flag | Value | Description |
|---|---|---|
| `OBJECT_ACCESS_SUCCESS` | 0x0001 | Audit successful object access. |
| `OBJECT_ACCESS_FAILURE` | 0x0002 | Audit failed object access. |
| `PRIVILEGE_USE_SUCCESS` | 0x0004 | Audit successful privilege exercises: the privilege contributed requested bits that survive into the final granted result. <a id="cite-token.audit-policy.privilege-use-success"></a> |
| `PRIVILEGE_USE_FAILURE` | 0x0008 | Audit failed privilege exercises: the privilege contributed requested bits during evaluation, but they do not survive into the final result. <a id="cite-token.audit-policy.privilege-use-failure"></a> |

The policy is additive. It forces audit events that system-wide policy
would not generate, and cannot suppress events that system-wide policy
requires. <a id="cite-token.audit-policy-additive"></a> It follows impersonation: when service A impersonates client
B and B's token has a category enabled, operations during
impersonation are audited under B's identity. <a id="cite-token.audit-policy-follows-impersonation"></a> The creation default is
0. <a id="cite-token.audit-policy-default-zero"></a>

The audit records these categories produce describe the effective token
in their `subject.token` fields: the user SID as `sid`, the groups as
`groups` with their attribute words as the parallel `group-attributes`,
the integrity level as `integrity`, `token_id` as `id`, `auth_id` as
`auth-id`, the token type as `type` (`primary` or `impersonation`), the
impersonation level as `impersonation` (0 for a primary token), and the
projected Linux UID as `uid` ([Audit Event Schemas](</kernel/internals/kacs/auditing/event-families-and-delivery.md#trm-3-c>)).

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

## Credential projection (fixed)

| Field | Description |
|---|---|
| `projected_uid` | Linux UID for the user SID, precomputed by authd when the token is minted (PSPU [Overview](</kernel/internals/kmes/overview.md#trm-2-1>)); 65534 for the anonymous identity. <a id="cite-token.projection.anonymous-is-nobody"></a> |
| `projected_gid` | Linux primary GID, precomputed the same way; 65534 for the anonymous identity. |
| `projected_supplementary_gids` | Linux supplementary GIDs, one per group SID, precomputed the same way. |

authd computes these at token creation and they are stored on the
token; KACS never resolves a SID-to-UID mapping at runtime. <a id="cite-token.projection.precomputed-never-resolved"></a> Projection
reflects all groups regardless of enabled state, so adjusting groups
does not trigger recalculation. <a id="cite-token.projection.ignores-enabled-state"></a> [Credential Projection](</kernel/internals/security/credentials.md#trm-3-10-1>) covers how the projection is
used.

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

## Token security (adjustable)

| Field | Description |
|---|---|
| `security_descriptor` | The token's own SD, controlling who may query, adjust, duplicate, or impersonate it. <a id="cite-token.own-sd-governs-handle-ops"></a> |

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

## Internal

| Field | Description |
|---|---|
| `refcount` | Reference count; the token is freed when the last reference drops. Not exposed to userspace. |

---

# Token Lifecycle

_Peios Kernel / Internals / KACS / Tokens_

> How tokens follow a process through fork, clone and exec — NEW_PROCESS_MIN, self-installation, bootstrap tokens and external tokens.

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

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

## Fork and clone

Every process and thread creation path goes through `clone()`, and
KACS branches on `CLONE_THREAD`.

**Without `CLONE_THREAD`** — fork or vfork — a new process is created
and the child receives an independent deep copy of the parent's
primary token. <a id="cite-token.fork.independent-copy"></a> If the parent is impersonating, the impersonation token
is not inherited: the child's effective credential is set from
`real_cred`. <a id="cite-token.fork.impersonation-not-inherited"></a> After the fork, mutations to either token are invisible
to the other. <a id="cite-token.fork.mutations-invisible-after"></a>

**With `CLONE_THREAD`** a new thread is created. Threads share the
parent's `real_cred` by reference and therefore share one primary
token object, so a privilege adjustment on it is visible to every
thread. <a id="cite-token.thread.shared-primary"></a> Each thread keeps independent impersonation state through its
own `cred`. <a id="cite-token.thread.independent-impersonation"></a> If the cloning thread is impersonating at the moment of
the clone, the impersonation token does not become the new thread's
primary or effective identity — the new thread starts with the shared
primary token as both, and may impersonate independently later. <a id="cite-token.thread.clone-starts-on-primary"></a>

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

## Exec

The primary token survives `execve()` unchanged, with the single
exception of `NEW_PROCESS_MIN` below. <a id="cite-token.exec.primary-survives"></a> If the calling thread is
impersonating, impersonation is reverted before the new program runs;
a new program always starts with the primary token as its effective
identity. <a id="cite-token.exec.reverts-impersonation"></a>

Token assignment for services happens between fork and exec: peinit
forks, installs the service's token on the child, and the child then
execs the service binary.

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

### NEW_PROCESS_MIN <a id="cite-token.new-process-min"></a>

When a token's `mandatory_policy` includes `NEW_PROCESS_MIN`, the
kernel replaces the primary token at exec time if the executable
carries an explicit, lower integrity label.

1. The executable's integrity label is read from the mandatory label
   ACE in its descriptor's SACL. A file with no label — no SACL, or no
   non-inherit-only mandatory label ACE — is **unlabelled**, and the
   token survives exec unchanged. <a id="cite-token.new-process-min.unlabelled-unchanged"></a> This is deliberately not the
   access-check rule, under which an unlabelled *object* counts as
   Medium ([Mandatory Integrity Control](</kernel/internals/kacs/access-check/mandatory-integrity-control.md#trm-3-8-3>)): an image that labels nothing would otherwise demote
   every process on it, PID 1 first, to Medium — which is exactly what
   happened before PEI-530, leaving the TCB below every High-integrity
   user and unable to convey their identity.
2. If the file's level is lower than the token's, a new token is
   created following DuplicateToken semantics — new `token_id`, new
   `token_guid`, `modified_id` initialised to the new `token_id`,
   `elevation_type` reset to Default — with `integrity_level` set to
   the file's label. Every other field — the impersonation level
   included — is copied from the source, and the original token is
   dropped. <a id="cite-token.new-process-min.lowers-to-file-label"></a>
3. If the file's level is greater than or equal to the token's,
   nothing happens and the token survives exec unchanged. <a id="cite-token.new-process-min.higher-label-unchanged"></a>

The mechanism only ever lowers integrity, so a child's level is always
at most its parent's, and only to a level the image itself claims. The
flag itself is immutable on the token, which is what prevents a process
from opting out before exec.

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

## Self-installing a primary token

`KACS_IOC_INSTALL` commits a new primary token on the calling process.
The operation is process-wide: the kernel replaces the primary token
for the entire thread group, not just the calling thread. <a id="cite-token.install.process-wide"></a>

The handle has to carry `TOKEN_ASSIGN_PRIMARY`, the token has to be a
primary token, and the caller's *real* token has to hold
`SeAssignPrimaryTokenPrivilege` enabled — an impersonating thread's
effective token does not satisfy the gate, and the privilege is marked
used on success. <a id="cite-token.install.gates"></a> Unless that real token also
holds `SeTcbPrivilege` enabled, the token being installed has to carry
the same user SID and the same LogonSession as the caller's, or the
call fails with `EPERM`; this is what stops a non-TCB holder of
`SeAssignPrimaryTokenPrivilege` from installing an arbitrary
higher-privilege token on itself, and `SeTcbPrivilege` bypassing it is
how peinit installs service tokens with a different user SID and
LogonSession. <a id="cite-token.install.same-user-same-session-unless-tcb"></a>

A thread that is not impersonating switches both `real_cred` and
`cred` to the new primary token. A thread that is impersonating has
only `real_cred` replaced, and its active impersonation stays in
`cred` until it reverts or execs — so reverting after an install
restores the thread to the *new* primary token, not the old one. <a id="cite-token.install.impersonating-thread-keeps-cred"></a>

The calling thread installs immediately. Sibling threads converge in
their own context through queued in-kernel credential work, with no
atomic all-threads-at-once swap: during a brief transition window some
siblings may still observe the old primary token until they run their
queued work. <a id="cite-token.install.siblings-converge-asynchronously"></a> No completion barrier is exposed to the caller.

Successful installations are ordered per process. Siblings converge to the
latest successful installation in that order; older queued work must not
restore a superseded token, including when retried after an allocation
failure. Concurrent callers need not complete their syscalls in installation
order. Once exec commits its primary token, delayed pre-exec installation
work cannot replace it. <a id="cite-token.install.latest-successful-install-wins"></a>

Installation and exec credential preparation are serialised. If a successful
installation precedes exec, an execing sibling whose queued update has not
run derives its new primary token from that latest installation, applying
`NEW_PROCESS_MIN` normally. It does not derive from the sibling's stale
primary token, and does not replay the raw installed token over the derived
result afterward. If exec has already begun preparing credentials, a new
installer waits for exec to release its credential guard; a waiting sibling
remains killable so exec can finish removing the other threads. A failed
exec releases the guard without consuming a pending installation.
<a id="cite-token.install.serialized-with-exec"></a>

Such an exec also gives the new image the installed token's Linux
credentials, projected as an installation projects them ([Credential Projection](</kernel/internals/security/credentials.md#trm-3-10-1>)): uid, gid,
supplementary groups and user come from the installed token, not from the
token it replaced. A setuid or setgid binary's effective ID then applies on
top as it would to any exec. Unless the thread is impersonating, the
installed token is also the subject that decides whether that ID change is
allowed. <a id="cite-token.install.lagging-exec-takes-installed-identity"></a>

A new thread joins the same convergence rule even if it was not yet visible
when an installation selected the siblings to update. This does not change
a process fork's independent copy of the calling thread's primary token.
<a id="cite-token.install.clone-enrollment"></a>

If the installed token's user SID differs from the outgoing primary
token's, the process security descriptor is regenerated from the
default template for the new token. Otherwise the existing process
descriptor is preserved. <a id="cite-token.install.process-sd-regenerated-on-sid-change"></a>

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

## Bootstrap tokens

Two tokens are created by PKM during kernel initialisation, before any
userspace process exists. Neither involves a syscall — the kernel
allocates the objects directly.

The **SYSTEM token** is hardcoded with user SID `S-1-5-18` (Local
System); groups `S-1-5-32-544` (BUILTIN\Administrators), `S-1-1-0`
(Everyone), `S-1-5-11` (Authenticated Users) and other well-known
SIDs; every defined privilege present and enabled; integrity level
System; token type Primary; impersonation level Delegation, the top of
the ratchet; elevation type Default; token source `PeiosKrn`;
projected UID 0; and `auth_id` set to `SYSTEM_LUID`. It is assigned to
the kernel's init task and inherited by PID 1 at exec. <a id="cite-token.bootstrap.system-token"></a>
Its `audit_policy` is `PRIVILEGE_USE_SUCCESS`, so every privilege SYSTEM
spends — at a capability gate and in an access check — is recorded as
`kacs.audit.privilege.used` ([The Privilege Model](</kernel/internals/kacs/privileges/the-privilege-model.md#trm-3-4-1>)), and tokens derived from it carry the
same policy. <a id="cite-token.bootstrap.system-token-audits-privilege-use"></a> The Anonymous
token and the query-only SYSTEM token have an audit policy of 0.

The **Anonymous token** is a global singleton with user SID `S-1-5-7`;
Everyone (`S-1-1-0`) as its only group; no privileges; integrity level
Untrusted; logon type Network; token type Impersonation; impersonation
level Anonymous; elevation type Default; token source `PeiosKrn`; and
`auth_id` set to `ANONYMOUS_LOGON_LUID`. It is effectively immutable,
having no privileges and no groups to adjust. <a id="cite-token.bootstrap.anonymous-token"></a> A peer token captured
at Anonymous level references this global object, whereas
`KACS_IOC_DUPLICATE` targeting Anonymous level creates a fresh
independent token of the same shape, because the DuplicateToken
contract requires a new object. <a id="cite-token.bootstrap.anonymous-singleton-vs-duplicate"></a>

| LUID | Value | Description |
|---|---|---|
| `SYSTEM_LUID` | 999 (0x3E7) | The SYSTEM LogonSession, created at kernel init. |
| `ANONYMOUS_LOGON_LUID` | 998 (0x3E6) | The Anonymous LogonSession, created at kernel init for Anonymous impersonation tokens. |

LogonSessions created dynamically by authd receive auto-generated
LUIDs starting at 1000; 999 and 998 are never assigned dynamically. <a id="cite-token.bootstrap.reserved-luids"></a>

The SYSTEM token carries `SeBackupPrivilege` and `SeRestorePrivilege`
present and enabled at boot. <a id="cite-token.bootstrap.system-backup-restore-present"></a> FACS passes backup and restore intent
flags into AccessCheck, which grants read and write regardless of file
DACLs — subject still to PIP. <a id="cite-token.bootstrap.backup-restore-intent-bypasses-dacl"></a> Once peinit has launched the TCB
services and early boot is complete, it disables these on child
service tokens through FilterToken.

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

## External token replacement

A privileged process being able to replace the primary token on
another running process — peinit downgrading a pre-authd service from
SYSTEM to a purpose-built token, for instance — is designed but **not
built**. Nothing in the kernel implements it today. <a id="cite-token.external-replacement-not-built"></a>

The design uses `task_work_add()` to queue a credential swap on each
task in the target thread group, each task executing the swap in its
own context to preserve RCU safety, with an impersonating thread
having only `real_cred` replaced and its impersonation left intact.
The gates would be `SeAssignPrimaryTokenPrivilege` on the caller's
real token, `TOKEN_ASSIGN_PRIMARY` (0x0001) on the token fd,
`PROCESS_SET_INFORMATION` on the target process's descriptor, and two
constraints — the new token's user SID matching the target's current
one, and the new token belonging to the same LogonSession — both
bypassed by `SeTcbPrivilege`. The process descriptor gate puts the
target's owner in control of who can change its identity, while the
SID and LogonSession constraints stop a non-TCB holder of
`SeAssignPrimaryTokenPrivilege` assigning an arbitrary token to a
process it can reach. `SeTcbPrivilege` bypassing both is how peinit
would assign tokens with different user SIDs and LogonSessions to
child services. Per-thread queuing would leave a brief window with
some threads on the new token and some on the old, which is acceptable
only because replacement is always a downgrade.

In its absence, the mitigation for pre-authd services is privilege
removal: peinit uses FilterToken to copy the SYSTEM token with the
dangerous privileges permanently deleted and assigns that filtered
token to the service at launch. The service keeps the SYSTEM SID but
permanently lacks the ability to exercise those privileges.

---

# Token Creation

_Peios Kernel / Internals / KACS / Tokens_

> The three operations that produce a token — CreateToken from nothing, DuplicateToken from another, FilterToken for a restricted one.

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

Three operations create tokens, each for a different purpose:
CreateToken mints one from nothing, DuplicateToken copies one, and
FilterToken produces a strictly weaker copy.

<a id="trm-3-2-4-1"></a>

## CreateToken

Mints a new token from scratch. The caller supplies the
security-meaningful content; the kernel generates the internal
bookkeeping and validates the structural invariants. The operation is
gated by `SeCreateTokenPrivilege`. <a id="cite-token.create.privilege-gate"></a>

The caller supplies `user_sid`, `groups` with their attributes,
privileges as `privs_present` plus `privs_enabled`, `owner_sid_index`,
`primary_group_index`, `default_dacl`, `integrity_level`,
`mandatory_policy`, `token_type`, `impersonation_level`, `auth_id`
referencing an existing LogonSession, `expiration` (0 for none),
`audit_policy`, `source` as a name plus LUID, `user_claims`,
`device_claims`, `lcs_scope_guids`, `lcs_private_layers`,
`device_groups`, `restricted_sids`, `restricted_device_groups`,
`confinement_sid`, `confinement_capabilities`, `confinement_exempt`,
`isolation_boundary`, `write_restricted`, `user_deny_only`,
`projected_uid`, `projected_gid`, `projected_supplementary_gids`,
`origin`, and `interactivity_scope`. The wire format is in [KACS ABI Reference](</kernel/userspace/native/kacs/generated-syscall-index.md#trm-3-a>).

Including the well-known implicit groups is the caller's
responsibility — Everyone (`S-1-1-0`), Authenticated Users
(`S-1-5-11`), and whatever else the principal's authentication context
implies, such as `S-1-5-4` Interactive, `S-1-5-6` Service, or
`S-1-5-15` This Organization. The kernel injects none of these. The
logon SID is the sole kernel-generated group. <a id="cite-token.create.no-implicit-groups"></a>

The kernel generates `token_id` as a LUID, `token_guid`, `modified_id`
initialised to `token_id`, `created_at` as the current time,
`elevation_type` always Default, the token's own default security
descriptor ([LogonSessions and Revocation](</kernel/internals/kacs/tokens/logonsessions-and-revocation.md#trm-3-2-7>)), and `logon_sid`, derived from the LogonSession ID
as `S-1-5-5-{id >> 32}-{id & 0xFFFFFFFF}`. <a id="cite-token.create.kernel-generated-fields"></a>

The logon SID is injected into the groups array carrying
`SE_GROUP_MANDATORY | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_ENABLED |
SE_GROUP_LOGON_ID`, appended after the caller's groups. <a id="cite-token.create.logon-sid-appended"></a> Callers do not
include it themselves. Because the injected entry is appended,
`owner_sid_index` and `primary_group_index` are interpreted relative
to the caller-supplied groups — 0 for the user SID, 1..N for the
caller's groups — and not against the array with the logon SID in it. <a id="cite-token.create.indices-relative-to-caller-groups"></a>

Validation covers, in turn:

- that the caller holds `SeCreateTokenPrivilege`;
- that every SID is structurally well-formed; <a id="cite-token.create.validate.sids-well-formed"></a>
- that the owner SID is the user SID or a group carrying
  `SE_GROUP_OWNER`, resolved to `owner_sid_index`; <a id="cite-token.create.validate.owner-sid"></a>
- that the primary group SID is the user SID or a group on the token,
  resolved to `primary_group_index`; <a id="cite-token.create.validate.primary-group-sid"></a>
- that `auth_id` references an existing LogonSession; <a id="cite-token.create.validate.auth-id-exists"></a>
- that `user_deny_only` is true whenever `write_restricted` is; <a id="cite-token.create.validate.deny-only-with-write-restricted"></a>
- that `confinement_sid` is present whenever `isolation_boundary` is; <a id="cite-token.create.validate.isolation-needs-confinement"></a>
- that the wire format's `elevation_type` field is 0, since the kernel
  always sets Default itself; <a id="cite-token.create.validate.elevation-type-zero"></a>
- and that the caller's group count plus the injected logon SID fits
  the 1024-entry limit. <a id="cite-token.create.validate.group-limit"></a>

The optional LCS registry credential extension, when present, has to
use the version and layout of [KACS ABI Reference](</kernel/userspace/native/kacs/generated-syscall-index.md#trm-3-a>), and carries at most 256 scope
GUIDs and at most 256 private layer names, with no nil scope GUID, no
duplicate scope GUIDs, no empty or overlong layer names, and no
duplicate layer names under LCS case-insensitive matching. <a id="cite-token.create.lcs-extension-limits"></a> Malformed
LCS credentials fail the whole call closed. <a id="cite-token.create.lcs-malformed-fails-closed"></a>

CreateToken accepts all four impersonation levels for a Primary token,
including Identification and Anonymous, and preserves the chosen level
and user identity. The level limits what may be derived from the token;
it does not prevent the process from acting as its own primary identity.
A peer capture takes the lower of the primary and socket levels:
Identification conveys identity without authority to act as it, while
Anonymous conveys the anonymous identity. <a id="cite-token.create.primary-levels"></a>

A minter chooses this ceiling deliberately ([Impersonation Levels](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-1>)). authd uses Delegation
for verified evidence and Impersonation for attested evidence; peinit's
SYSTEM token uses Delegation. Each client may lower its level per
connection. Older kernels refused Primary tokens below Impersonation as
a migration guard; callers must not use an ignored or default Anonymous
field when they intend peers to impersonate the identity.

The kernel does not authenticate the user, look up SIDs in the
directory, resolve SID-to-UID mappings, or check that the principal
exists at all. Holding `SeCreateTokenPrivilege` is what makes the
caller trusted, and that trust is total.

The call returns a token file descriptor. Since CreateToken takes no
desired-access parameter, the returned handle always carries a cached
access mask of `TOKEN_ALL_ACCESS`. <a id="cite-token.create.returns-all-access"></a>

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

## DuplicateToken

Creates an independent copy of an existing token, requiring
`TOKEN_DUPLICATE` access on the source. <a id="cite-token.duplicate.requires-token-duplicate"></a>

Two things may change during duplication. The **token type** may go
from primary to impersonation or the reverse. <a id="cite-token.duplicate.type-may-change"></a> The **impersonation
level** is chosen by the caller and is a ratchet: whatever the types
involved, the new level has to be equal to or lower than the source's,
and asking for more fails with `EINVAL`. <a id="cite-token.duplicate.level-ratchet"></a> A primary minted at
Delegation can be duplicated to an impersonation token at any level; a
primary at Impersonation cannot yield a Delegation-level token; an
Identification-level token cannot be duplicated up to Impersonation or
Delegation. The level only ever goes down — reaching a higher one
again means minting a fresh token with CreateToken.

Duplicating **to Primary** is how an impersonated identity becomes a
process — the server's impersonation token, converted, is what a
service manager installs on a child it launches as that client. The
result keeps the identity and the level, so a primary made from a
client captured at Impersonation is itself capped at Impersonation and
so is every process and token descended from it. The kernel refuses a
Primary result below Impersonation: a captured Identification or
Anonymous identity must not become an acting process through duplication.
This restriction applies even when the source is itself Primary. It is
separate from privileged CreateToken, which may deliberately mint a
primary with a low derivation ceiling. <a id="cite-token.duplicate.primary-result-floor"></a>

On the new token, `token_id` and `token_guid` are fresh, `modified_id`
is initialised to the new `token_id`, and `elevation_type` resets to
Default because the copy belongs to no linked pair. <a id="cite-token.duplicate.fresh-fields"></a> `token_type` and
`impersonation_level` are as the caller specified, within the rules
above. The token's own descriptor is a fresh default ([LogonSessions and Revocation](</kernel/internals/kacs/tokens/logonsessions-and-revocation.md#trm-3-2-7>)): no
custom descriptor can be supplied at duplication time, and changing it
afterwards means using `WRITE_DAC` on the new handle. <a id="cite-token.duplicate.fresh-default-sd"></a>

Everything else is copied from the source: `user_sid`,
`user_deny_only`, `logon_sid`; `groups` with all per-group attributes;
`restricted_sids` and `write_restricted`; the privilege present,
enabled, enabled-by-default **and used** states; `integrity_level` and
`mandatory_policy`; `auth_id`, `origin`, `source`, `created_at`,
`expiration`, `audit_policy`; `interactivity_scope`; `default_dacl`,
`owner_sid_index`, `primary_group_index`; `user_claims`,
`device_claims`, `device_groups`, `restricted_device_groups`;
`lcs_scope_guids` and `lcs_private_layers`; `confinement_sid`,
`confinement_capabilities`, `confinement_exempt`; and the three
projection fields. <a id="cite-token.duplicate.copies-everything-else"></a>

One target is not a copy at all. Duplicating to **Impersonation at
Anonymous level** discards the source entirely and returns a fresh
token of the boot Anonymous shape — user SID `S-1-5-7`, Everyone as
its only group, no privileges, Untrusted integrity, and LogonSession
998 rather than the source's. <a id="cite-token.duplicate.anonymous-is-fresh-shape"></a> None of the copied-field rules above
apply to it. Assuming Anonymous is an identity boundary rather than a
level change, so the operation constructs the minimal identity instead
of narrowing the caller's.

The original token is unaffected. <a id="cite-token.duplicate.source-unaffected"></a>

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

## FilterToken

Creates a restricted copy, requiring `TOKEN_DUPLICATE` access on the
source. <a id="cite-token.filter.requires-token-duplicate"></a> Filtering only ever weakens: there is no parameter that grants
anything.

It can **remove privileges**, deleting them permanently from the new
token by clearing them from the present, enabled, and
enabled-by-default states at once. <a id="cite-token.filter.remove-privileges"></a> It can **set groups to deny-only**,
giving them `SE_GROUP_USE_FOR_DENY_ONLY` so they block access through
deny ACEs but never grant it through allow ACEs — permanently, with no
way back. <a id="cite-token.filter.deny-only-groups"></a> It can **add restricted SIDs**, a secondary list that makes
AccessCheck evaluate the DACL twice, granting access only when the
normal SIDs and the restricted SIDs independently both pass. <a id="cite-token.filter.restricted-sids-double-evaluation"></a> And it
can **enable write-restricted mode**, limiting that second evaluation
to write operations so reads use the normal list alone; enabling it
forces `user_deny_only` true on the new token. <a id="cite-token.filter.write-restricted-forces-deny-only"></a>

Input validation is all-or-nothing — a single malformed entry means no
token is created. <a id="cite-token.filter.validation-all-or-nothing"></a> The deny-only list uses zero-based group indices
into the source's group array, and a duplicate or out-of-range index
is invalid. <a id="cite-token.filter.deny-only-index-rule"></a> The restricting SID blob has to parse exactly as the
declared packed SID list, with no truncated or trailing bytes. <a id="cite-token.filter.sid-blob-exact"></a> If the
source token is already restricted and the intersection of its
restricted SID list with the supplied list is empty, the request is
invalid and nothing is created. <a id="cite-token.filter.empty-intersection-invalid"></a>

On the new token, `token_id` and `token_guid` are fresh, `modified_id`
is initialised to the new `token_id`, and `elevation_type` resets to
Default. <a id="cite-token.filter.fresh-fields"></a> The privilege states are the source's modified by the removal
list, except that **`used` resets to 0** — unlike duplication, which
carries it across. <a id="cite-token.filter.used-resets"></a> `groups` keeps the source's SIDs with attributes
modified per the deny-only list, adding and removing nothing. <a id="cite-token.filter.groups-unchanged-except-attributes"></a>
`restricted_sids` is the supplied list, or its intersection with the
source's when the source was already restricted. <a id="cite-token.filter.restricted-sids-intersection"></a> `write_restricted` is
sticky: set if requested or if the source had it. <a id="cite-token.filter.write-restricted-sticky"></a> `user_deny_only` is
true when write-restricted is enabled and otherwise copied.
`user_sid`, `logon_sid`, `integrity_level`, `mandatory_policy`,
`token_type` and `impersonation_level` are copied, as are `auth_id`,
`origin`, `source`, `created_at`, `expiration`, `audit_policy`,
`default_dacl`, `owner_sid_index`, `primary_group_index`, the claims
and device group arrays, the LCS credentials, the confinement fields,
and the projection fields. The token's descriptor is a fresh default. <a id="cite-token.filter.copies-everything-else"></a>

---

# Token Adjustment

_Peios Kernel / Internals / KACS / Tokens_

> What can be changed on a live token — privileges, groups, interactivity scope and object-creation defaults — and what cannot.

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

A live token's privileges, groups, default object-creation metadata,
and interactive session metadata can be adjusted at runtime. These are
distinct operations with separate access rights and constraint models.
All of them mutate the token object in place using atomic operations,
all become visible immediately to every thread sharing the token, and
all bump `modified_id`. <a id="cite-token.adjust.in-place-visible-bumps-modified-id"></a>

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

## AdjustPrivileges

Requires `TOKEN_ADJUST_PRIVILEGES` on the token, and has three modes. <a id="cite-token.adjust.privs.requires-right"></a>

**Enable and disable** flips individual bits in `privileges_enabled`
for privileges present on the token. A privilege that is not present
cannot be enabled, and disabling one that is already absent is a
no-op. <a id="cite-token.adjust.privs.absent-enable-fails-disable-noop"></a> The operation activates existing privileges; it never grants
new ones.

**Reset to defaults** restores `privileges_enabled` to match
`privileges_enabled_by_default`, returning every privilege to its
creation-time state in one operation. It is encoded as a single
`kacs_priv_entry` with `luid = 0` and
`attributes = KACS_PRIV_RESET_ALL_DEFAULTS`. <a id="cite-token.adjust.privs.reset-encoding"></a> The reset touches only
`privileges_enabled`: it does not restore privileges that were removed
from `privileges_present`. <a id="cite-token.adjust.privs.reset-does-not-restore-removed"></a>

**Remove** permanently deletes a privilege, clearing its bit in
`privileges_present`, `privileges_enabled`, and
`privileges_enabled_by_default` together. Removing an already-absent
privilege is a no-op. <a id="cite-token.adjust.privs.remove-absent-noop"></a> The deletion is irreversible; nothing re-adds a
privilege to a token.

Duplicate privilege indices in one request are invalid. <a id="cite-token.adjust.privs.duplicate-indices-invalid"></a> The kernel
validates every entry before applying any change, so an invalid entry
fails the whole operation with no state change at all. <a id="cite-token.adjust.privs.all-or-nothing"></a> The caller
receives a report of each adjusted privilege's previous state. <a id="cite-token.adjust.privs.reports-previous-state"></a>

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

## AdjustGroups

Requires `TOKEN_ADJUST_GROUPS` on the token, and has two modes. <a id="cite-token.adjust.groups.requires-right"></a>

**Enable and disable** flips `SE_GROUP_ENABLED` on individual groups,
within two constraints. A group carrying `SE_GROUP_MANDATORY`,
`SE_GROUP_USE_FOR_DENY_ONLY`, or `SE_GROUP_LOGON_ID` cannot be
adjusted **in either direction** — not enabled, not disabled, whatever
its current state; naming one in a request fails the whole call. <a id="cite-token.adjust.groups.protected-attributes-either-direction"></a> And
the user SID, when it appears in the group list, cannot be disabled,
which is the one constraint that is direction-scoped. <a id="cite-token.adjust.groups.user-sid-cannot-disable"></a>

**Reset to defaults** restores every group to its creation-time
enabled state. It restores only that state — it does not clear
`SE_GROUP_USE_FOR_DENY_ONLY` from a group that FilterToken marked
deny-only afterwards. <a id="cite-token.adjust.groups.reset-keeps-deny-only"></a>

Groups are addressed by zero-based index into the token's groups
array. A count of 0 is invalid, as is a count above 1024, as are
duplicate indices in one request. <a id="cite-token.adjust.groups.count-and-duplicate-limits"></a> Reset is encoded as a single
`kacs_group_entry` of `{ index = 0xFFFFFFFF, enable = 0 }`. <a id="cite-token.adjust.groups.reset-encoding"></a>

The caller receives the previous enabled state of every group as a
1024-bit mask encoded as sixteen 64-bit words in ascending order: word
0 covers group indices 0–63, word 1 covers 64–127, and bit `i % 64` of
word `i / 64` corresponds to group index `i`. Since group arrays cap
at 1024 entries, the mask is complete for any valid token. <a id="cite-token.adjust.groups.previous-state-mask"></a>

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

## AdjustInteractivityScope

Requires `TOKEN_ADJUST_INTERACTIVITY_SCOPE` on the token and
`SeTcbPrivilege` on the caller's real token. <a id="cite-token.adjust.interactivity-scope.gates"></a> It changes the token's
`interactivity_scope` to a new `u32` and nothing else: the field is
metadata, and changing it grants or removes no privilege, group,
access right, label, claim, default owner, default primary group,
default DACL, or any other authorization state. <a id="cite-token.adjust.interactivity-scope.metadata-only"></a>

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

## AdjustDefault

Requires `TOKEN_ADJUST_DEFAULT` on the token, and covers three fields. <a id="cite-token.adjust.default.requires-right"></a>

The **default DACL** applied to new objects is replaced by an RCU
pointer swap, with the old DACL freed after a grace period. The
**owner SID index** changes which SID becomes the default owner of new
objects, and has to reference the user SID or a group carrying
`SE_GROUP_OWNER`. The **primary group index** changes the default
primary group, and has to reference the user SID or any group SID on
the token. Both index updates are atomic.

All three affect future object creation only; existing objects are
untouched. <a id="cite-token.adjust.default.future-objects-only"></a> None can escalate anything, because the caller is choosing
among SIDs already on their own token.

`audit_policy` is fixed at creation, and no adjustment operation
changes it.

---

# Linked Tokens and Elevation

_Peios Kernel / Internals / KACS / Tokens_

> Two linked tokens for one principal — what the kernel does with the link, what it deliberately leaves to userspace, and the pair's lifecycle.

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

At logon, authd may create two tokens for one principal and link them.
The **elevated token**, `elevation_type = Full`, carries the user's
complete identity: every group active, every assigned privilege
present and enabled. The **filtered token**,
`elevation_type = Limited`, carries the same user SID with
administrative groups set to deny-only and dangerous privileges
stripped, produced from the elevated token by FilterToken.

Both tokens belong to the same LogonSession, are both primary tokens,
and carry the same user SID. <a id="cite-token.link.pair-invariants"></a> The filtered token is installed as the
LogonSession's default; the elevated token exists but is not directly
reachable by unprivileged processes.

A token never assigned a linked-pair role has
`elevation_type = Default`. Once `KACS_IOC_LINK_TOKENS` sets a token
object to Full or Limited, that role is sticky on that object. If the
pair is later replaced or destroyed the token has no active partner
and `KACS_IOC_GET_LINKED_TOKEN` returns an error, but the token goes
on reporting its last assigned elevation type. <a id="cite-token.link.stale-partner-errors-role-persists"></a>

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

## What KACS does

KACS provides pairing, storage, and query restriction — three
mechanisms, no policy.

**Linked pair association** registers the pair on the LogonSession, so
given either token the system can retrieve its partner. The pairing
lives at the LogonSession level and is not stored on the token
objects.

Establishing a pair is a TCB operation: the caller holds
`SeTcbPrivilege` on its **primary** token — an impersonating thread's
effective token does not satisfy it — and holds `TOKEN_DUPLICATE` on
*both* of the token handles being linked. <a id="cite-token.link.gates"></a> The two handles have to name
distinct token objects, and both have to belong to the LogonSession
named in the request, which itself has to be published. <a id="cite-token.link.handles-distinct-same-published-session"></a> The ioctl
ignores the handle it was issued on entirely; only the two named
handles matter. <a id="cite-token.link.issuing-handle-ignored"></a>

**Elevation type classification** puts `elevation_type` on each token
so a consumer can tell which side it is holding.

**Identification-level query restriction** governs what an unprivileged
caller gets when it queries a token's partner: a deep clone at
Identification impersonation level. The clone follows DuplicateToken
semantics — a new token object, a new `token_id`, `modified_id`
initialised to it, a fresh default descriptor — except that it
preserves the partner's `elevation_type`, and it is always returned
through a `TOKEN_QUERY`-only handle. <a id="cite-token.link.query-returns-identification-clone"></a> The caller can inspect the
elevated token but cannot use it for an access decision. A caller
holding `SeTcbPrivilege` receives a full handle to the actual linked
token instead. <a id="cite-token.link.tcb-gets-real-handle"></a>

Returning a copy through `TOKEN_QUERY` is a deliberate exception to
the normal access-right model, where `TOKEN_DUPLICATE` would be
expected. It holds because the returned copy is always
Identification-level: functionally a query result rather than a usable
token.

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

## What KACS does not do

The elevation decision itself — whether this user should be allowed to
use their elevated token right now — is entirely authd's. KACS does
not gate elevation, verify credentials, or display prompts. It stores
the pair and restricts unprivileged access to it.

Beyond enforcing the LogonSession, token-type and same-user
invariants, KACS does not verify that the filtered token really is a
FilterToken-derived reduction of the elevated one. <a id="cite-token.link.no-reduction-check"></a> That correspondence
is authd's to get right.

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

## Lifecycle

Both tokens in a pair share a LogonSession, and that session is not
destroyed while any token fd, credential, pair slot, or other
reference keeps one of its token objects live. When the last external
reference is released and only the linked-pair's own references
remain, KACS destroys the LogonSession, removes the linkage, and drops
the pair's references to both tokens. <a id="cite-token.link.pair-released-with-last-external-ref"></a> After that cleanup no token
object from the session remains live purely because it was linked.

Stale-role tokens can exist before final destruction — for instance
when `KACS_IOC_LINK_TOKENS` replaces a LogonSession's active pair
while an old token object is still held by an fd or credential. Fork
produces them too: the deep copy a child receives preserves the
parent's elevation type, so a forked child can hold a Full or Limited
token that was never linked to anything. <a id="cite-token.link.fork-preserves-elevation-type"></a> Once a
token is no longer the active member of the pair, querying its linked
token returns an error, because the partner relationship no longer
exists for it. Such survivors keep their sticky Full or Limited
elevation type: they are stale-role tokens with no active partner, not
Default tokens.

---

# LogonSessions and Revocation

_Peios Kernel / Internals / KACS / Tokens_

> The LUID-identified object every token references — how sessions are created, how they expire, and how revocation propagates.

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

<a id="trm-3-2-7-1"></a>

## LogonSessions

A LogonSession is a lightweight kernel object identified by a LUID,
carried on tokens as `auth_id`. Every token references one.

authd creates a LogonSession through a KACS syscall at authentication
time, before creating the token. <a id="cite-token.session.created-before-token"></a> The object holds the LogonSession ID,
the logon type (Interactive, Network, Service, and so on), the user
SID, the authentication package name such as `Kerberos` or
`Negotiate`, and a creation timestamp. <a id="cite-token.session.fields"></a> The logon SID, `S-1-5-5-X-Y`,
is derived from the LogonSession ID. Several tokens may share one
session — linked pairs, and tokens derived by duplication. <a id="cite-token.session.shared-by-many-tokens"></a>

When the last token referencing a session is freed, the kernel
destroys the session object and emits a `kacs.session.destroyed`
event through KMES. <a id="cite-token.session.destroyed-with-last-token"></a> The last
token usually goes when a credential is freed, which happens in an RCU
callback where no record can be built, so the session is queued, still
referenced, and a kernel work item writes the event moments later and
then releases it. The session is gone at once — it no longer resolves —
but its event follows the teardown rather than coming from it, and its
header names the kernel worker that wrote it. <a id="cite-token.session.destroyed-record-deferred"></a> The event is for whatever keeps per-session state
outside the kernel — an audit pipeline, an accounting tool, an authority
that caches credentials per session. authd keeps none and does not
subscribe.

The record describes the session under `object.session`: its LUID as
`id` (the `subject.token.auth-id` of every record made under it), the
user SID as `user.sid`, the logon type as `logon-type`, the
authentication package as `auth-package`, and the creation time as
`logon-time`. The logon type is written by name — `interactive`,
`network`, `batch`, `service`, `network-cleartext`, `new-credentials`
or `remote-interactive` — and the time in realtime nanoseconds, though
the kernel holds it to whole seconds.

### Logon types

The logon type records how the issuer established the session. It
describes the situation, not the principal: one principal can hold
sessions of several types at once. Session creation rejects any value
outside this table with `-EINVAL`.

| Value | Name | The issuer asserts | Origin |
|---|---|---|---|
| 2 | Interactive | A user signed in at the machine | Local |
| 3 | Network | A client on another machine authenticated to use a service here | Remote |
| 4 | Batch | A scheduled job started | Local |
| 5 | Service | A service started | Local |
| 8 | NetworkCleartext | As Network, and the credential was presented in the clear | Remote |
| 9 | NewCredentials | The caller's local identity is unchanged, and only the credentials it presents to other machines differ | Remote |
| 10 | RemoteInteractive | A user signed in from another machine, to a terminal or a desktop | Remote |

The kernel takes the issuer's word for the type and never verifies it.
Its only use of the type is the origin column: the `CAP_SYS_BOOT`
mapping additionally requires `SeRemoteShutdownPrivilege` for a
remote-origin session. The well-known
group SIDs that let an ACE distinguish one kind of session from
another, such as `INTERACTIVE` and `NETWORK`, are placed on the token
by the issuer, not derived by the kernel from the logon type.

There is one rollback path for the case where authd creates a session
but no token ever becomes live for it:
`kacs_destroy_empty_logon_session`, which requires `SeTcbPrivilege`
and succeeds only when the session exists, has zero live tokens, has
no linked-token state, and has no other in-flight kernel references. <a id="cite-token.session.destroy-empty.gates"></a>
On success it destroys the object and emits the same
`kacs.session.destroyed` event as normal cleanup. <a id="cite-token.session.destroy-empty.emits-event"></a> A nonexistent
session fails with `-ENOENT`; one with any live token, linked-token
state, or in-flight reference fails with `-EBUSY`. <a id="cite-token.session.destroy-empty.errors"></a>

A second enumeration surface exists alongside `/proc`:
`/sys/kernel/security/kacs/sessions` lists every live session, one
line each, giving the session ID, user SID, logon type, authentication
package, and creation time. <a id="cite-token.session.securityfs-listing"></a> Each
line reads

```
logon_session_id=<u64> user_sid=<hex> logon_type=<u32> auth_package=<hex> created_at=<u64>
```

with the user SID's binary form and the package name's bytes in
lowercase hexadecimal, and `created_at` in seconds since the Unix
epoch. securityfs itself is unclassified by FACS,
so its objects sit deny-missing until the mount is given a synthesising
policy ([File Descriptor Storage](</kernel/internals/kacs/file-security/descriptor-storage-and-caching.md#trm-3-9-5>)); only then can the file be opened at all. On Peios,
peinit gives it one at boot that lets Authenticated Users open and
traverse. Reading it is access-checked against a
synthetic descriptor granting read to SYSTEM and Administrators, and is
PIP-checked. <a id="cite-token.session.securityfs-access-check"></a>

AccessCheck never consults `auth_id`, and the logon SID influences a
decision only because it is materialised as an ordinary group SID on
the token. <a id="cite-token.session.auth-id-not-consulted"></a> Two enforcement decisions elsewhere in the kernel do read
session state, though. Installing a primary token denies a non-TCB
caller whose target token belongs to a different
LogonSession ([Token Lifecycle](</kernel/internals/kacs/tokens/token-lifecycle.md#trm-3-2-3>)). And the
`CAP_SYS_BOOT` mapping selects between `SeShutdownPrivilege` and
`SeRemoteShutdownPrivilege` by inspecting the session's logon type
([Credential Projection](</kernel/internals/security/credentials.md#trm-3-10-1>)). `interactivity_scope` is metadata in the same way: the kernel
stores it and returns it on query, and no kernel security mechanism
evaluates it.

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

## Expiration

The `expiration` field carries a timestamp, and AccessCheck does not
enforce it. It is informational.

Token lifetime is governed by reference counting instead: a token
exists as long as at least one reference — a process credential or an
open file descriptor — exists. <a id="cite-token.session.lifetime-by-refcount"></a>

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

## Revocation

KACS has no token revocation primitive. There is no "invalidate token
X" syscall, and no syscall destroys a LogonSession while tokens still
reference it. <a id="cite-token.session.no-revocation-primitive"></a> `kacs_destroy_empty_logon_session` is only authd's
rollback for a session that never acquired live tokens.

Terminating a LogonSession is therefore userspace coordination. On
Peios authd does it, when asked over `/run/logon.sock` ([PGSS session termination](https://learn.peios.org/specifications/pgss/logon/ending-a-session)):

1. A caller asks authd to end the session, and authd decides whether it
   may: its own session as a person, anyone else's by an access check
   against local policy. SYSTEM's session (999), Anonymous's (998) and
   every session of logon type Service are never ended this way; a
   service is stopped through peinit.
2. authd enumerates processes whose **primary** token carries the
   target `auth_id`, by walking `/proc`, opening each process with
   `pidfd_open`, opening its primary token with
   `kacs_open_process_token` on that pidfd, and reading
   `TokenStatistics`, which includes `auth_id`. No dedicated enumeration
   syscall exists or is needed. A thread's impersonation token is not
   consulted, so a service impersonating a member of the session is not
   one of its processes.
3. authd sends each `SIGTERM` with `pidfd_send_signal`, waits up to a
   grace period (5 seconds) for them to exit, and sends `SIGKILL` to the
   survivors.
4. It walks again, since a process may have forked meanwhile, for at
   most three rounds.
5. The processes terminate, dropping their token references.
6. The last reference drops and the session object is cleaned up.

Each token handle authd opens in the walk is itself a reference to the
session, and is closed as soon as `auth_id` has been read.

Token file descriptors can be passed between processes over IPC, so a
reference held by a process outside the target session survives that
session's process termination. <a id="cite-token.session.fd-reference-survives-termination"></a> The walk finds processes running under the
session, not every process holding one of its tokens, so such a
reference keeps the session alive after authd has ended every process
in it, and authd reports nothing about it. A process that has exited
but not been reaped likewise keeps its token, and the session, until it
is reaped.

Kernel-side invalidation — a dead flag on the LogonSession object
checked during AccessCheck, so that access checks against its tokens
fail immediately — is not implemented.

---

# Token Access Rights

_Peios Kernel / Internals / KACS / Tokens_

> Tokens are securable objects — obtaining a token file descriptor, the token-specific rights, the generic mapping and the default descriptor.

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

Tokens are securable objects: each has its own security descriptor,
and reaching a token means passing an AccessCheck against it. <a id="cite-token.rights.access-checked-object"></a>

<a id="trm-3-2-8-1"></a>

## Obtaining a token file descriptor

**Opening directly.** A syscall takes a pidfd — not a raw PID — and a
desired access mask. The kernel finds the target's
primary token, evaluates the caller's token against that token's
descriptor, and returns a token fd with the granted mask cached on it. <a id="cite-token.rights.open-by-pidfd"></a>
A separate variant opens a thread's impersonation token. <a id="cite-token.rights.open-thread-token"></a> Opening
another process's token additionally requires
`PROCESS_QUERY_INFORMATION` on the target process's descriptor. <a id="cite-token.rights.open-other-needs-process-query"></a>

**Opening through `/proc`.** `/proc/<pid>/token` and
`/proc/<pid>/task/<tid>/token` open a process's primary token and a
thread's effective token as a query-only handle: the fd always carries
`TOKEN_QUERY` and nothing else. Opening another process's file makes
both of the syscall's checks — `PROCESS_QUERY_INFORMATION` on the
process's descriptor, with PIP dominance, and `TOKEN_QUERY` on the
token's own descriptor — so the path reads nothing the syscall would
refuse. A process opens its own without either check. <a id="cite-token.rights.proc-token-file"></a>

The peer-token socket option (`getsockopt(SOL_KACS,
KACS_SO_PEER_TOKEN)`) is the exception: it takes no desired-access
mask, and the fd it returns always carries the fixed rights
`TOKEN_QUERY | TOKEN_IMPERSONATE | TOKEN_DUPLICATE`. <a id="cite-token.rights.peer-token-fixed-rights"></a> A token delivered
in a `KACS_SCM_TOKEN` control message carries the same three. <a id="cite-token.rights.scm-token-fixed-rights"></a>
`TOKEN_DUPLICATE` is what lets a server turn a client's identity into a
primary token for a process it launches on the client's behalf
([Token Creation](</kernel/internals/kacs/tokens/token-creation.md#trm-3-2-4>)); it is safe to hand out because the level ratchet means the
copy can never act above the level the client chose ([Impersonation Levels](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-1>)).

**Receiving over IPC.** A token fd can be passed over a Unix socket
with `SCM_RIGHTS`. What the recipient may do is bounded by the mask
cached on the fd when it was originally opened, not by the recipient's
own identity. <a id="cite-token.rights.passed-fd-keeps-cached-mask"></a>

**Implicit self-access.** A thread has implicit access to its own
effective token for query operations, but this is not a kernel bypass.
It follows from the default token descriptor, which grants
`TOKEN_QUERY` and the adjustment rights to the token's own user SID.
The AccessCheck still runs; it simply succeeds while the descriptor
continues to grant the right. Explicitly mutating a token's own
descriptor later can revoke self-query by removing that grant. <a id="cite-token.rights.self-query-revocable"></a>

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

## Token-specific rights

| Right | Value | Grants |
|---|---|---|
| `TOKEN_ASSIGN_PRIMARY` | 0x0001 | Install as a process's primary token. Also requires `SeAssignPrimaryTokenPrivilege` on the caller's token. <a id="cite-token.rights.assign-primary-needs-privilege"></a> |
| `TOKEN_DUPLICATE` | 0x0002 | Duplicate the token, or create a restricted copy with FilterToken. |
| `TOKEN_IMPERSONATE` | 0x0004 | Install as a thread's impersonation token. |
| `TOKEN_QUERY` | 0x0008 | Read token information: SIDs, groups, privileges, integrity, claims, source, statistics, GUID, elevation type. |
| `TOKEN_ADJUST_PRIVILEGES` | 0x0020 | Enable, disable, or permanently remove privileges. |
| `TOKEN_ADJUST_GROUPS` | 0x0040 | Enable or disable groups. |
| `TOKEN_ADJUST_DEFAULT` | 0x0080 | Change the default DACL, owner SID, and primary group SID. |
| `TOKEN_ADJUST_INTERACTIVITY_SCOPE` | 0x0100 | Change the interactivity scope. Also requires `SeTcbPrivilege`. |

Bit 0x0010, `TOKEN_QUERY_SOURCE`, is subsumed by `TOKEN_QUERY`: a
holder of 0x0008 can query source information too. <a id="cite-token.rights.query-source-subsumed"></a> The bit is not
reused for anything else, for format compatibility with MS-DTYP.

`TOKEN_ALL_ACCESS` is 0x000F01FF — the union of the token-specific
rights with `STANDARD_RIGHTS_REQUIRED`
(`DELETE | READ_CONTROL | WRITE_DAC | WRITE_OWNER`, 0x000F0000). The
named rights alone OR to 0x01EF; the reserved `TOKEN_QUERY_SOURCE` bit
adds 0x0010 to reach 0x01FF. <a id="cite-token.rights.all-access-value"></a>

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

## Generic mapping <a id="cite-token.rights.generic-mapping"></a>

| Generic right | Maps to |
|---|---|
| `GENERIC_READ` | `TOKEN_QUERY \| READ_CONTROL` |
| `GENERIC_WRITE` | `TOKEN_ADJUST_PRIVILEGES \| TOKEN_ADJUST_GROUPS \| TOKEN_ADJUST_DEFAULT \| WRITE_DAC` |
| `GENERIC_EXECUTE` | `TOKEN_IMPERSONATE` |
| `GENERIC_ALL` | `TOKEN_ALL_ACCESS` (0x000F01FF) |

<a id="trm-3-2-8-4"></a>

## Standard rights

`READ_CONTROL` reads the token's own descriptor, `WRITE_DAC` modifies
its DACL, and `WRITE_OWNER` changes its owner. `DELETE` has no
practical effect on a token and is present only for uniformity across
standard rights. <a id="cite-token.rights.delete-inert"></a>

<a id="trm-3-2-8-5"></a>

## The default token descriptor <a id="cite-token.rights.default-descriptor"></a>

A newly created token receives a descriptor owned by the creating
process's user SID, with a DACL granting:

- the token's own user SID `TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES |
  TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT`;
- the creator `TOKEN_ALL_ACCESS`;
- SYSTEM (`S-1-5-18`) `TOKEN_ALL_ACCESS`;
- Administrators (`S-1-5-32-544`) `TOKEN_QUERY`.

The Administrators grant is read-only: it lets an administrator see who
any process runs as, its groups and privileges, and which logon session
it belongs to, which is what a machine-wide process listing needs.
Duplicating, impersonating, adjusting or rewriting the token still
needs the token's own grants. <a id="cite-token.rights.default-sd-administrators-query"></a>

Self-access is deliberately limited to the adjustment operations that
cannot escalate. `TOKEN_DUPLICATE`, `TOKEN_IMPERSONATE`, and
`WRITE_DAC` are not granted to the token's own subject. <a id="cite-token.rights.default-sd-no-self-escalation"></a>

That limit needs protecting in the case where the creator and the
token's own user SID are the same, which would otherwise hand the
subject `TOKEN_ALL_ACCESS` through the creator ACE. When the two SIDs
are identical the creator ACE is omitted — and the descriptor also
gains a non-inherit-only `OWNER RIGHTS` ACE suppressing the owner's
implicit `READ_CONTROL | WRITE_DAC` grant while preserving
`READ_CONTROL`. <a id="cite-token.rights.default-sd-self-created-owner-rights"></a> Without it, owner-implicit `WRITE_DAC` would let the
subject rewrite its own DACL and reintroduce exactly the escalation
that omitting the creator ACE was meant to close.

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

## Check-at-open

The check-at-open model applies to tokens exactly as it does to files,
for the token-specific rights. AccessCheck runs once, when the token
fd is obtained; the granted mask is cached on the fd; and each of the
token ioctls verifies against that cached mask with no re-evaluation. <a id="cite-token.rights.check-at-open"></a>

The standard rights are the exception. Reading and writing a token's
own descriptor passes no cached mask at all and runs a **live**
AccessCheck on every call, so `READ_CONTROL`, `WRITE_DAC` and
`WRITE_OWNER` are re-evaluated per operation rather than snapshotted
at open. <a id="cite-token.rights.standard-rights-live-check"></a> A descriptor change therefore takes effect immediately for
those three rights, while already-opened handles keep their cached
token-specific rights.

---

# Process security

_Peios Kernel / Internals / KACS / Process security_

> Find the Peios kernel articles about process security.

Use these articles to understand process security in the Peios kernel.

- [State and lifetime](</kernel/internals/kacs/process-security/state-and-lifetime.md>)
- [PSB Fields](</kernel/internals/kacs/process-security/psb-fields.md>)
- [Process Security Descriptors](</kernel/internals/kacs/process-security/process-security-descriptors.md>)

---

# State and lifetime

_Peios Kernel / Internals / KACS / Process security_

> The per-process structure describing what a process is, independent of the principal running it.

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

The Process Security Block is a per-process structure carrying
properties that describe **what the process is**, independent of the
principal running it.

Its PIP identity fields, `pip_type` and `pip_trust`, are determined by
the binary loaded at exec ([Binary Signature Verification](</kernel/internals/kacs/executable-trust/signature-verification.md#trm-3-6>)). Its other fields — process
mitigations and process restrictions — are process policy, set by
whoever launches the process. Neither category is token identity, and
neither is determined by the principal.

Keeping the PSB separate from the token is the point. The token
describes identity and travels with impersonation: when a thread
impersonates a client, the effective token changes. The PSB describes
the process, and impersonation never touches it. <a id="cite-psb.impersonation-untouched"></a>

> The PSB is never affected by impersonation. Impersonation changes
> who the thread is acting as. It does not change what the process is.

The canonical PSB reference lives on the task's LSM security blob,
`task_struct->security`, separate from the credential that holds the
token pointer. <a id="cite-psb.canonical-on-task-blob"></a> A mirrored, non-authoritative reference is also kept in
credential security blobs, for the benefit of Linux hooks that receive
only a credential. For any task-attached credential that mirror refers
to the same PSB as the task blob, and it never defines a different
process identity. <a id="cite-psb.cred-mirror-same-psb"></a>

Credentials are swapped during impersonation, and that swap may change
the credential's token pointer — but the canonical PSB is untouched
and any credential-level mirror continues to refer to it. <a id="cite-psb.cred-swap-preserves-psb"></a>

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

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

## Fork

The child receives a copy of the parent's PSB with a single exception:
`process_guid` is not copied, and the child is given a new
kernel-generated one. <a id="cite-psb.fork.new-guid"></a> Everything else — the PIP fields, the
mitigations, and any active restrictions — is inherited, so a
Protected process's children start Protected and PIP propagates across
fork. <a id="cite-psb.fork.inherits-rest"></a>

The child also receives a new default process descriptor. Its owner is
the forking thread's **primary** token's user SID, not the
impersonation token's, even when the thread is impersonating at the
time. <a id="cite-psb.fork.sd-owner-primary-token"></a> The DACL follows the default template.

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

## Exec

The PIP fields are reset at exec from the new binary's cryptographic
signature. A Protected parent that execs an unsigned binary loses PIP
protection: protection follows the binary, not the lineage. <a id="cite-psb.exec.pip-reset-from-binary"></a>

The mitigation flags — `lsv`, `wxp`, `tlp`, `cfif`, `cfib`, `pie`,
`sml`, `ui_access` — are not reset. They persist across exec
unchanged, so a mitigation set between fork and exec survives whatever
binary is subsequently loaded. <a id="cite-psb.exec.mitigations-persist"></a> `no_child_process` persists in the same
way: a process restricted from creating children stays restricted no
matter what it execs. <a id="cite-psb.exec.no-child-process-persists"></a>

`process_guid` is not reset either, because it identifies the process
— the scheduling entity — rather than the binary. <a id="cite-psb.exec.guid-preserved"></a>

The process descriptor is not reset. Exec preserves it unchanged. <a id="cite-psb.exec.sd-preserved"></a> It
was initialised at fork from the forking thread's primary token and
reflects the process creation context, or a later explicit management
context, rather than the binary being executed. Primary token
installation and the other explicit process-descriptor mutation paths
replace or modify it only under their own rules ([Token Lifecycle](</kernel/internals/kacs/tokens/token-lifecycle.md#trm-3-2-3>)).

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

## Clone with CLONE_THREAD

Threads share the process's PSB. <a id="cite-psb.clone-thread.shares-psb"></a> Thread creation is unaffected by
`no_child_process`, which blocks new processes only.

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

## Relationship to AccessCheck

The PSB is not an input to AccessCheck in the general case. AccessCheck
takes a token and a descriptor and evaluates access; most PSB fields
are invisible to it.

PIP is the exception. The pipeline includes a PIP enforcement step
reading `pip_type` and `pip_trust`, which come from the PSB rather
than from any token: the enforcement layer extracts them and passes
them to AccessCheck as explicit parameters. <a id="cite-psb.accesscheck.pip-from-psb"></a>

The asymmetry between MIC and PIP follows from that. **MIC** uses the
effective token, so impersonation changes how it evaluates — which is
safe because the integrity ceiling on impersonation ([Impersonation Gates](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-2>)) prevents
escalation. **PIP** uses the PSB, so impersonation cannot change how
it evaluates — necessary because there is no impersonation gate
constraining the PIP dimensions, making the PSB the only safe source.

The process mitigations and `no_child_process` do not interact with
AccessCheck at all. Each is enforced at its own enforcement point,
independently of the access control pipeline.

---

# PSB Fields

_Peios Kernel / Internals / KACS / Process security_

> Every PSB field — the process GUID fixed at fork, the protection fields set at exec, the one-way mitigations and the UI access flag.

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

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

## Process identity (fixed at fork)

| Field | Type | Description |
|---|---|---|
| `process_guid` | UUID | 128-bit identifier for this process instance, generated by the kernel at fork and immutable for the process's lifetime. It is **not** copied from the parent — every process receives a new one. Used by KMES and kernel-internal consumers for identity stamping and event correlation. <a id="cite-psb.guid.new-and-immutable"></a> |

The process GUID is distinct from the PID. PIDs are recycled; process
GUIDs are unique within a boot, and globally unique in practice. <a id="cite-psb.guid.unique-within-boot"></a> It is
the stable correlation key that lets KMES attribute events to a
process across its whole lifetime.

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

## Protection (set at exec, fixed)

| Field | Type | Description |
|---|---|---|
| `pip_type` | u32 | Process Integrity Protection type. Determined by the binary's cryptographic signature at exec. |
| `pip_trust` | uint | Trust tier within a PIP type; higher values can reach lower ones. Determined by the signer's identity. |

PIP fields are signing-based. At exec the kernel verifies the binary's
signature and derives both fields from the signer, using the algorithm
and key model of [Binary Signature Verification](</kernel/internals/kacs/executable-trust/signature-verification.md#trm-3-6>).

Both are plain unsigned integers rather than enumerations, and are
compared numerically. Three type values are conventional — None (0),
Protected (512) and Isolated (1024) — but only two are producible: the
key table validator accepts a key only at exactly Protected with
`PeiosTcb` trust (8192) and rejects the whole table otherwise, so
**Isolated is unreachable** and a signed binary is always
Protected/8192. <a id="cite-psb.pip.only-protected-tcb"></a> Neither None nor Isolated is defined as a named
constant in the public ABI at all. <a id="cite-psb.pip.none-isolated-absent-from-abi"></a> The parent process cannot influence the
determination at all — even a compromised peinit running as SYSTEM
cannot forge PIP protection for an unsigned binary. <a id="cite-psb.pip.parent-cannot-influence"></a> The public
verification key is compiled into the kernel image, and the kernel
only ever verifies; it never signs.

This is a deliberate departure from MS-DTYP, where the parent sets a
protection level at process creation and the kernel validates the
binary's signature against it. Peios removes the parent-controlled
half entirely: one input, one answer.

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

## Process mitigations (one-way)

| Field | Description |
|---|---|
| `lsv` | **Library Signature Verification.** Only signed shared libraries load. When the process has `pip_type != None` the library's trust level has to be at or above the process's PIP trust; when `pip_type = None` any valid signature suffices and trust is not compared. <a id="cite-psb.lsv.trust-floor"></a> |
| `wxp` | **Write-XOR-Execute Protection.** No page is simultaneously writable and executable; W+X mappings and transitions between writable and executable are rejected. <a id="cite-psb.wxp.no-write-and-execute"></a> |
| `tlp` | **Trusted Library Paths.** Shared libraries load only from approved directory prefixes. Weaker than LSV, since it trusts the path rather than the binary. <a id="cite-psb.tlp.approved-prefixes-only"></a> |
| `cfif` | **Forward-Edge Control Flow Integrity.** Hardware indirect-branch tracking — Intel IBT, ARM BTI — is locked on and cannot be disabled by the process. Not settable: see below. |
| `cfib` | **Backward-Edge Control Flow Integrity.** The hardware shadow stack, Intel CET, is locked on and cannot be disabled by the process. <a id="cite-psb.cfib.shadow-stack-locked"></a> |
| `pie` | **Position-Independent Executable Requirement.** Non-PIE binaries are rejected at exec, so that ASLR is actually effective. <a id="cite-psb.pie.non-pie-rejected-at-exec"></a> |
| `sml` | **Speculation Mitigation Lock.** Speculation mitigations are locked on and cannot be disabled by the process. <a id="cite-psb.sml.speculation-locked"></a> |

Mitigations are inherited from the parent at fork and can be set by
syscall. They are one-way:
once set they are never cleared, and exec does not reset them — a
mitigation set by the launcher persists regardless of which binary is
loaded. <a id="cite-psb.mitigations.one-way"></a>

Do not infer an additional service policy from peinit launch: the
[source-checked peinit 0.0.12 path](/peios/using-peios/services-and-jobs/identity-and-privileges.md#token-installation-and-executable-trust)
does not make a per-service PSB mitigation request. Inherited and self-applied
flags are separate from that launcher behavior.

Setting a bit is **activation-backed**. Before a mitigation bit moves
from clear to set, KACS either activates the underlying protection for
the target process or verifies that the process already satisfies the
invariant. <a id="cite-psb.mitigations.activation-backed"></a> If any requested mitigation cannot be activated or
verified, the whole operation fails closed without mutating any bit
from that request. <a id="cite-psb.mitigations.all-or-nothing"></a> Once committed, later operations that would disable
the protection or make the process violate the invariant are rejected,
and re-requesting an already-set mitigation never weakens what is
already committed. <a id="cite-psb.mitigations.recommit-never-weakens"></a>

For the runtime memory mitigations, activation covers existing state
as well as future transitions. Enabling `wxp` fails if the process
already has a mapping that is simultaneously writable and executable,
or otherwise already violates the invariant in a way KACS can observe. <a id="cite-psb.wxp.enable-fails-on-existing-wx"></a>
Enabling `tlp` fails if the process already has a file-backed
executable mapping whose kernel-resolved path is missing,
unresolvable, outside the approved prefix cache, or otherwise
TLP-denied. <a id="cite-psb.tlp.enable-fails-on-denied-mapping"></a> Enabling `lsv` fails if the process already has a
file-backed executable mapping whose signing material is missing,
invalid, or below the required PIP trust. <a id="cite-psb.lsv.enable-fails-on-untrusted-mapping"></a> Anonymous executable
mappings are governed by `wxp` alone; `tlp` and `lsv` apply only to
file-backed ones. <a id="cite-psb.mitigations.anonymous-exec-is-wxp-only"></a>

For the architecture-backed mitigations, activation goes through the
architecture's kernel interface to place the process in the protected
state and prevent later process-controlled disablement. Enabling
`cfif`, `cfib`, or `sml` fails closed when the platform cannot make
the protection true for the target. <a id="cite-psb.mitigations.arch-fails-closed"></a>

`sml` also accepts a second route: a platform that reports speculation
as unconditionally not-affected satisfies activation by that fact
alone, with nothing to enable. <a id="cite-psb.sml.not-affected-satisfies"></a>

`cfif` cannot currently be committed at all. Activation against a live
task returns `ENODEV` unconditionally, because the kernel exposes no
userspace control surface for IBT or BTI, so the bit fails closed on
every request. <a id="cite-psb.cfif.enodev-always"></a> `cfib` works, through shadow-stack enable-and-lock,
with one restriction: enabling it on a task other than the caller
fails. <a id="cite-psb.cfib.self-only"></a>

Two mitigations are event-gated rather than retroactive: `pie` is
enforced at subsequent exec and `no_child_process` at subsequent
process creation. <a id="cite-psb.mitigations.event-gated"></a> They still follow the one-way commit rule, and have
to be set before the event they are meant to constrain.

All of this is distinct from PIP. Mitigations are policy set by the
launcher; PIP is a property of the binary determined by the kernel.

The mitigations compose deliberately: LSV ensures only signed
libraries load, WXP blocks code injection, CFIF blocks forward-edge
code reuse through indirect calls and jumps, CFIB blocks
return-oriented programming, and PIE makes ASLR effective. Together
they make exploitation dramatically harder than any one of them alone.

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

## UI access (one-way) <a id="cite-psb.ui-access.set-once-fixed"></a>

| Field | Description |
|---|---|
| `ui_access` | Permits interaction with higher-integrity UI elements. Reserved for future desktop functionality. Set by syscall, typically by peinit between fork and exec, and fixed thereafter. |

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

## Process restrictions (one-way)

| Field | Description |
|---|---|
| `no_child_process` | Once set, the process creates no child processes — fork, or clone without `CLONE_THREAD`. New threads are unaffected, and the flag is never cleared. <a id="cite-psb.no-child-process.blocks-fork"></a> |

Unlike the exec-time fields, this one can be set at two points. The
parent's code, running in the freshly forked child, can set it before
exec, so the new binary loads with the restriction already in place.
Or a process can restrict itself at any time during its life — after
it has finished spawning its own workers, for instance. <a id="cite-psb.no-child-process.two-set-points"></a>

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

## The TLP cache

The approved directory prefixes for TLP live in a global kernel cache
rather than on individual PSBs: the `tlp` flag decides whether a
process is subject to enforcement, while the paths themselves are
machine-wide.

The cache is an array of absolute directory prefix byte strings
evaluated against kernel-resolved Linux path bytes, holding at most 64
entries of at most 4096 bytes each. <a id="cite-psb.tlp.cache-bounds"></a> Every prefix begins with `/` and
**ends** with `/` — so that `/usr/lib/` does not match `/usr/libevil`
— and contains no embedded NUL byte. <a id="cite-psb.tlp.prefix-slash-terminated"></a> An empty, relative,
NUL-containing, or non-slash-terminated prefix is invalid and is
rejected without mutating the existing cache, which is staged and
swapped under a mutex so a rejected update cannot leave it partly
written. <a id="cite-psb.tlp.invalid-prefix-rejected-atomically"></a>

**The cache has no production writer.** The only code that populates
it is a test helper compiled in solely under the KUnit configuration:
there is no syscall, no securityfs node, and no registry path that
fills it. <a id="cite-psb.tlp.no-production-writer"></a> In a shipping build the cache is therefore permanently
empty — and since an empty cache matches no path, enabling `tlp` on a
process denies *every* file-backed executable mapping it subsequently
attempts. <a id="cite-psb.tlp.empty-cache-denies-all"></a>

At `mmap(PROT_EXEC)` time, a process with TLP enabled has the mapped
file's current kernel-resolved backing path checked against every
approved prefix. If the path cannot be resolved, if no prefix matches,
or if the cache is empty, the mapping is rejected. <a id="cite-psb.tlp.mmap-rejects-unmatched"></a>

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

## Reading the PSB

`/proc/<pid>/psb` gives a process's PSB as one line of text, in this
order:

```
pip_type=<u32> pip_trust=<u32> mitigations=0x<hex> process_guid=<uuid>
```

`mitigations` is the committed mitigation bitfield in at least three
hexadecimal digits, including `ui_access` and `no_child_process`, with
the bit values of [KACS ABI Reference](</kernel/userspace/native/kacs/generated-syscall-index.md#trm-3-a>). `process_guid` is the 16 bytes in order,
formatted 8-4-4-4-12. <a id="cite-psb.proc.psb-file"></a>

A process reads its own without any check. Reading another process's
needs `PROCESS_QUERY_LIMITED` on its process descriptor, with
`SeDebugPrivilege` rescuing a descriptor denial as it does for every
process right, and **does not** need PIP dominance. That a process is
protected is not a secret every other refusal keeps; it is what a
caller needs to see to understand those refusals. <a id="cite-psb.proc.psb-read-access"></a>

The PSB is otherwise written only: `kacs_set_psb` sets mitigations and
returns nothing about them.

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

## Identity virtualization (reserved) <a id="cite-psb.virtualization.reserved"></a>

| Field | Description |
|---|---|
| `virtualization` | Per-process state for setuid compatibility redirection. Not active, and implementations may omit the field until it is. |

---

# Process Security Descriptors

_Peios Kernel / Internals / KACS / Process security_

> The descriptor controlling who may operate on a process — the access rights, signal classification, what bypasses the check, and the default.

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

Every process carries a security descriptor controlling who may
operate on it, stored on the PSB alongside the PIP and mitigation
fields. It replaces Linux's UID-based process access control — a
patchwork of UID comparisons and capabilities — with a single
descriptor evaluation.

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

## Process access rights

| Right | Value | Meaning |
|---|---|---|
| `PROCESS_TERMINATE` | 0x0001 | Send signals whose default action is termination. <a id="cite-psb.right.terminate"></a> |
| `PROCESS_SIGNAL` | 0x0002 | Send informational signals whose default action is to ignore: `SIGCHLD`, `SIGURG`, `SIGWINCH`. <a id="cite-psb.right.signal"></a> |
| `PROCESS_VM_READ` | 0x0010 | Read process memory — ptrace peek, `/proc/<pid>/mem`, `process_vm_readv`. <a id="cite-psb.right.vm-read"></a> |
| `PROCESS_VM_WRITE` | 0x0020 | Write process memory — ptrace poke, `/proc/<pid>/mem`, `process_vm_writev`. Includes debugger attach. <a id="cite-psb.right.vm-write"></a> |
| `PROCESS_DUP_HANDLE` | 0x0040 | Extract file descriptors from the process through `pidfd_getfd`. <a id="cite-psb.right.dup-handle"></a> |
| `PROCESS_SET_INFORMATION` | 0x0200 | Change priority, CPU affinity, I/O priority, resource limits, process group membership where Linux permits it, timer slack, memory-placement policy or pages, and mutable `/proc/<pid>` task state — `sched`, `autogroup`, `timens_offsets`, `timerslack_ns`, `coredump_filter`, `oom_adj`, `oom_score_adj`, `make-it-fail`, `fail-nth`, `latency` and `clear_refs`, plus write intent on the coupled `uid_map`, `gid_map`, `projid_map` and `setgroups` seq files. <a id="cite-psb.right.set-information"></a> |
| `PROCESS_QUERY_INFORMATION` | 0x0400 | Inspect the process's token; read the detailed `/proc/<pid>/*` files — `cmdline`, `status`, `io`, `limits`, `sched`, `autogroup`, `timens_offsets`, `personality`, `syscall`, `latency`, `timers`, `timerslack_ns`, `mounts`, `mountinfo`, `mountstats`, `coredump_filter`, `oom_adj`, `oom_score_adj`, `loginuid`, `make-it-fail`, `fail-nth`, `seccomp_cache`, `ksm_merging_pages` and `ksm_stat` — plus read intent on the coupled `uid_map`, `gid_map`, `projid_map` and `setgroups` seq files; query Linux compatibility capability state through `capget(pid)`; and query detailed scheduler, CPU-affinity and I/O-priority state. <a id="cite-psb.right.query-information"></a> |
| `PROCESS_SUSPEND_RESUME` | 0x0800 | Send signals whose default action is to stop or continue. <a id="cite-psb.right.suspend-resume"></a> |
| `PROCESS_QUERY_LIMITED` | 0x1000 | Read basic process information: PID, process group ID, session ID, image name, state, CPU and memory usage — `stat`, `statm`, `comm`, `wchan`, `schedstat`, `cpuset`, `cgroup`, `cpu_resctrl_groups`, `oom_score`, `sessionid`, `patch_state`, `stack_depth`, `arch_status` and `psb`. This is what `ps` and `top` show, it covers `/proc/<pid>/stat`, and it is the right required for `pidfd_open()` and for `kill(pid, 0)` existence probes. <a id="cite-psb.right.query-limited"></a> |
| `READ_CONTROL` | 0x20000 | Read the process's own descriptor. |
| `WRITE_DAC` | 0x40000 | Modify the process's DACL. |
| `WRITE_OWNER` | 0x80000 | Change the descriptor's owner. |

Three `/proc` entries are not where the right names suggest.
`maps`, `fd` and `environ` are not gated by
`PROCESS_QUERY_INFORMATION`: they keep their upstream
`PTRACE_MODE_READ_FSCREDS` gating, which maps to **`PROCESS_VM_READ`**
— reading a process's memory map is treated as reading its memory,
which is defensible but is not what the right's name implies. <a id="cite-psb.proc.maps-fd-environ-are-vm-read"></a> And
`cgroup` sits in the **`PROCESS_QUERY_LIMITED`** set rather than the
detailed one. <a id="cite-psb.proc.cgroup-in-query-limited"></a>

`psb` is the process's PSB, read under `PROCESS_QUERY_LIMITED` with no
PIP dominance ([PSB Fields](</kernel/internals/kacs/process-security/psb-fields.md#trm-3-3-2>)). It is the one `/proc` entry whose check is
KACS's own rather than the metadata rule's.

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

## Signal classification <a id="cite-psb.signal.by-default-action"></a>

Each Linux signal maps to a process access right according to its
default action.

Signal 0 is not delivered at all. A `kill()`, `tkill()`, or `tgkill()`
call with signal 0 is an existence and permission probe, requiring
`PROCESS_QUERY_LIMITED` on the target plus PIP dominance. <a id="cite-psb.signal.zero-is-probe"></a>

**`PROCESS_TERMINATE`** — default action terminate, or terminate with
a core dump: <a id="cite-psb.signal.terminate-set"></a>

| Signal | # | Default | Notes |
|---|---|---|---|
| `SIGHUP` | 1 | Terminate | Session hangup |
| `SIGINT` | 2 | Terminate | Ctrl-C |
| `SIGQUIT` | 3 | Terminate + core | Quit request |
| `SIGILL` | 4 | Terminate + core | Illegal instruction |
| `SIGTRAP` | 5 | Terminate + core | Debug trap |
| `SIGABRT` | 6 | Terminate + core | Abort |
| `SIGBUS` | 7 | Terminate + core | Bus error |
| `SIGFPE` | 8 | Terminate + core | Floating point exception |
| `SIGKILL` | 9 | Terminate | Forced kill, cannot be caught |
| `SIGUSR1` | 10 | Terminate | User-defined |
| `SIGSEGV` | 11 | Terminate + core | Segfault |
| `SIGUSR2` | 12 | Terminate | User-defined |
| `SIGPIPE` | 13 | Terminate | Broken pipe |
| `SIGALRM` | 14 | Terminate | Alarm timer |
| `SIGTERM` | 15 | Terminate | Graceful termination request |
| `SIGSTKFLT` | 16 | Terminate | Stack fault |
| `SIGXCPU` | 24 | Terminate + core | CPU time exceeded |
| `SIGXFSZ` | 25 | Terminate + core | File size exceeded |
| `SIGVTALRM` | 26 | Terminate | Virtual timer |
| `SIGPROF` | 27 | Terminate | Profiling timer |
| `SIGIO` | 29 | Terminate | I/O possible |
| `SIGPWR` | 30 | Terminate | Power failure |
| `SIGSYS` | 31 | Terminate + core | Bad syscall |

**`PROCESS_SUSPEND_RESUME`** — default action stop or continue: <a id="cite-psb.signal.suspend-resume-set"></a>

| Signal | # | Default | Notes |
|---|---|---|---|
| `SIGSTOP` | 19 | Stop | Forced stop, cannot be caught |
| `SIGTSTP` | 20 | Stop | Terminal stop, Ctrl-Z |
| `SIGTTIN` | 21 | Stop | Background read from terminal |
| `SIGTTOU` | 22 | Stop | Background write to terminal |
| `SIGCONT` | 18 | Continue | Resume a stopped process |

**`PROCESS_SIGNAL`** — default action ignore: <a id="cite-psb.signal.ignore-set"></a>

| Signal | # | Default | Notes |
|---|---|---|---|
| `SIGCHLD` | 17 | Ignore | Child status change |
| `SIGURG` | 23 | Ignore | Urgent socket data |
| `SIGWINCH` | 28 | Ignore | Window resize |

The real-time signals, `SIGRTMIN` through `SIGRTMAX` (32–64), default
to terminate and therefore require `PROCESS_TERMINATE`. <a id="cite-psb.signal.realtime-terminate"></a>

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

### What bypasses the check

This classification applies only to signals sent by userspace through
`kill()`, `tkill()`, and `tgkill()`. Kernel-generated signals —
hardware faults such as `SIGSEGV`, `SIGBUS` and `SIGFPE`, `SIGCHLD`
from a child exiting, `SIGPIPE` from a broken pipe — are delivered by
the kernel and bypass the process descriptor check entirely, because
the `task_kill` LSM hook does not fire for kernel-originated delivery. <a id="cite-psb.signal.kernel-generated-bypass"></a>

Terminal-generated job control signals are kernel-originated under
that rule and bypass the check the same way: `SIGINT`, `SIGQUIT` and
`SIGTSTP` from the tty driver's `isig` handling, and `SIGHUP` on
hangup. <a id="cite-psb.signal.tty-isig-bypass"></a> This is intentional. Authorization for keyboard-driven signals
is possession of the controlling terminal, which was gated by the
terminal's file descriptor at open time — so Ctrl-C reaches the whole
foreground process group even when a member of it is more privileged
or more PIP-trusted than whoever holds the terminal. A process that
cannot accept that exposure must not attach to an untrusted
controlling terminal.

The `si_uid` in a delivered signal's `siginfo_t` is the sender's
projected UID ([Credential Projection](</kernel/internals/security/credentials.md#trm-3-10-1>)), captured at send time. <a id="cite-psb.signal.si-uid-projected"></a> Like every projected
credential surface it is informational only and is not an
authorization input; `si_pid` carries the same caveat and is subject
to PID reuse besides.

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

## Generic mapping <a id="cite-psb.generic-mapping"></a>

| Generic right | Maps to |
|---|---|
| `GENERIC_READ` | `PROCESS_QUERY_INFORMATION \| PROCESS_VM_READ \| READ_CONTROL` |
| `GENERIC_WRITE` | `PROCESS_SET_INFORMATION \| PROCESS_VM_WRITE \| WRITE_DAC` |
| `GENERIC_EXECUTE` | `PROCESS_TERMINATE \| PROCESS_SUSPEND_RESUME \| PROCESS_QUERY_LIMITED` |
| `GENERIC_ALL` | every process right above, together with `READ_CONTROL`, `WRITE_DAC` and `WRITE_OWNER` |

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

## The default process descriptor <a id="cite-psb.sd.default-template"></a>

Every process receives a default descriptor at creation:

```
Owner: <creator's primary token user SID>
Group: <creator's primary token primary group SID>
DACL:
  ALLOW  <process's own user SID>   GENERIC_ALL
  ALLOW  BUILTIN\Administrators     GENERIC_ALL
  ALLOW  SYSTEM                     GENERIC_ALL
  ALLOW  Everyone                   PROCESS_QUERY_LIMITED
```

A process can therefore do anything to itself; Administrators and
SYSTEM have full control over every process; everyone can see basic
process information, which is what makes `ps` and `top` work for all
users; and detailed inspection — token, memory, environment — is
restricted to the process itself, administrators, and SYSTEM.

A service can modify its own descriptor at runtime with
`kacs_set_sd`, which requires `WRITE_DAC` — granted to the process
itself by the default DACL. <a id="cite-psb.sd.set-sd-requires-write-dac"></a> Requesting a custom descriptor *at launch*
through a service definition is not implemented: the only descriptor
creation path always builds the default template, so every process
starts from it and any deviation is a subsequent write. <a id="cite-psb.sd.no-custom-at-launch"></a>

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

## How PIP relates to it

PIP and the process descriptor are complementary, and both checks have
to pass. <a id="cite-psb.pip.both-checks-must-pass"></a> The descriptor controls *who* may operate on the process; PIP
controls *what trust level* is required for invasive access to a
protected one. AccessCheck evaluates the caller's token against the
target's descriptor for the requested right, and PIP evaluates the
caller's trust against the target's `pip_type` and `pip_trust` for
operations crossing the process boundary.

The two are genuinely independent. A process may have a permissive
descriptor granting Administrators `GENERIC_ALL` and still be
PIP-protected, so administrators pass the descriptor check and are
stopped only by insufficient PIP trust.

The converse — a process with no PIP protection carrying a restrictive
descriptor that denies even administrators — holds with one
qualification. When a descriptor check denies access and PIP was not
the deciding factor, an enabled `SeDebugPrivilege` on the caller
grants the access anyway and is marked used. <a id="cite-psb.sd.sedebug-overrides-denial"></a> The privilege therefore
rescues a descriptor denial while remaining unable to cross a PIP
boundary, which is exactly the split [Privilege Catalogue](</kernel/internals/kacs/privileges/privilege-catalogue.md#trm-3-4-2>) describes for it.

---

# Privileges

_Peios Kernel / Internals / KACS / Privileges_

> Find the Peios kernel articles about privileges.

Use these articles to understand privileges in the Peios kernel.

- [The Privilege Model](</kernel/internals/kacs/privileges/the-privilege-model.md>)
- [Privilege Catalogue](</kernel/internals/kacs/privileges/privilege-catalogue.md>)

---

# The Privilege Model

_Peios Kernel / Internals / KACS / Privileges_

> Rights that do not fit the subject-object model — the privilege lifecycle, the two enforcement categories, intent gating, assignment and auditing.

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

Some operations do not fit the subject-object model at all. Rebooting
the machine, loading a kernel module, changing the system clock,
creating a token — these affect the system itself rather than a
specific protected resource, so there is nothing to attach a security
descriptor to. They still need authorization.

Privileges fill that gap. A privilege is the right to perform a
particular system operation, carried on the token beside the
principal's identity. Where a descriptor says "this principal may read
this file", a privilege says "this principal may shut down the
system". The descriptor lives on the object; the privilege lives on
the subject.

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

## Lifecycle

A privilege is **assigned by policy** when authd creates the token,
resolving the principal's assignments from security policy once, at
creation. There are no runtime grants: a privilege absent at creation
can never be added later. <a id="cite-priv.lifecycle.no-runtime-grants"></a>

The privilege then sits on the token in whatever enabled state it was
created with. The kernel accepts any enabled set that is a subset of
the present set, and takes the creation-time enabled set as the
enabled-by-default set. <a id="cite-priv.enabled-subset-of-present"></a> authd issues every privilege it grants already
enabled, on the reasoning that a privilege the holder had to enable
before it worked would be a grant in name only — so the
present-but-disabled resting state exists in the model and is
reachable through AdjustPrivileges, but is not where privileges
normally start.

A privilege that has been disabled is re-activated by **explicitly
enabling** it through AdjustPrivileges.

When the privilege is **exercised**, the kernel checks that it is both
present and enabled — a single mask test against both words — permits
the operation, and records it as used. <a id="cite-priv.check.enabled-not-just-present"></a>

For a standalone gate, "exercised" means the gate accepted that bit,
and the used bit is meant to be recorded even when a later independent
check — a process descriptor, PIP, or a malformed-input test — denies
the operation afterwards. <a id="cite-priv.used.recorded-despite-later-denial"></a> Where the shared privilege helper performs
the check, it marks the bit immediately, and the impersonation gate
does the same. <a id="cite-priv.used.helper-marks-immediately"></a> Three gates mark later and therefore record nothing
when a subsequent check fails:

- token creation marks after the token has been constructed and its
  descriptor allocated, so a malformed specification leaves the bit
  unset; <a id="cite-priv.used.create-token-marks-late"></a>
- primary token installation marks after the same-user and
  same-LogonSession gate; <a id="cite-priv.used.install-marks-late"></a>
- and the `CAP_SYS_BOOT` mapping marks after the remote-shutdown
  origin gate. <a id="cite-priv.used.cap-sys-boot-marks-late"></a>

Used-state for the AccessCheck-influencing privileges follows the
provenance rules of [AccessCheck Overview](</kernel/internals/kacs/access-check/accesscheck-overview.md#trm-3-8-1>) instead.

Recording the used bit is not merely bookkeeping. Every gate treats a
failure to record it as a failure of the operation itself and returns
`EPERM` or `EACCES`. <a id="cite-priv.used.record-failure-fails-operation"></a>

Afterwards the privilege may be **disabled**, returning to rest, or
**removed permanently**, which clears it from the present, enabled,
and enabled-by-default states while preserving the `used` bit for
audit. <a id="cite-priv.remove.preserves-used-bit"></a>

<a id="trm-3-4-1-2"></a>

## Two enforcement categories

**Standalone operation gates** are the majority. They authorize
specific operations that AccessCheck does not mediate — rebooting,
loading modules, debugging processes — and the kernel simply checks
whether the calling thread's token holds the privilege present and
enabled before allowing the operation.

**AccessCheck-influencing privileges** alter the outcome of
AccessCheck itself, causing it to grant rights the object's DACL would
not grant on its own. They are evaluated inside the pipeline alongside
DACL rules, integrity policy, and confinement. There are five:
`SeSecurityPrivilege` grants `ACCESS_SYSTEM_SECURITY` for SACL access
(and doubles as a standalone gate for the audit-related Linux
capabilities); `SeTakeOwnershipPrivilege` grants `WRITE_OWNER` as a
post-DACL fallback; `SeBackupPrivilege` grants all read access;
`SeRestorePrivilege` grants all write access plus `WRITE_DAC`,
`WRITE_OWNER`, `DELETE` and `ACCESS_SYSTEM_SECURITY`; and
`SeRelabelPrivilege` loosens MIC's constraint on `WRITE_OWNER` for
non-dominant callers. <a id="cite-priv.accesscheck.five-privileges"></a> [AccessCheck Overview](</kernel/internals/kacs/access-check/accesscheck-overview.md#trm-3-8-1>) gives the exact mechanics.

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

## Intent gating <a id="cite-priv.intent-gating"></a>

`SeBackupPrivilege` and `SeRestorePrivilege` are intent-gated. Other
AccessCheck-influencing privileges are self-scoping —
`SeSecurityPrivilege` only matters when `ACCESS_SYSTEM_SECURITY` is
requested — but backup and restore grant such broad categories of
access that evaluating them unconditionally would apply them to every
AccessCheck on the system.

AccessCheck therefore takes a `privilege_intent` parameter. A caller
passes `BACKUP_INTENT` for a backup-context operation and
`RESTORE_INTENT` for a restore-context one, and the corresponding
privilege is evaluated only when its flag is present. Without the
flag, these privileges are invisible to the pipeline.

Intent gating also keeps backup and restore *inside* the pipeline
rather than short-circuiting it, which matters because later stages —
PIP in particular — have to be able to constrain privilege-granted
access.

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

## Assignment

Privileges are assigned by security policy, not by identity.
Membership of the Administrators group confers no privilege by itself.
Groups and privileges are orthogonal: groups determine which objects
you can reach through DACLs, privileges determine which system
operations you can perform.

An administrator defines policy — that members of Backup Operators
receive `SeBackupPrivilege` and `SeRestorePrivilege`, say. At
authentication authd resolves the principal's group memberships,
evaluates the policy against them, and creates the token carrying the
result. The kernel neither verifies nor evaluates that policy; it
trusts authd as a TCB component. The token then carries those
privileges for its whole lifetime.

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

## Auditing

Every exercise sets the token's monotonic used state for that
privilege, and every standalone gate emits an ftrace event. <a id="cite-priv.audit.ftrace-per-standalone-gate"></a>

KMES audit events, of type `kacs.audit.privilege.used`, are emitted
only when the token's `audit_policy` opts in through
`PRIVILEGE_USE_SUCCESS` or `PRIVILEGE_USE_FAILURE`, and they come from
two places, told apart by `operation.name`.

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

### In an access check

An access check records the five AccessCheck-influencing privileges,
with `operation.name` `access-check`. The event fires
when the privilege's provenance bits intersect both the mapped desired
mask and the final granted mask. For `SeSecurityPrivilege` and
`SeTakeOwnershipPrivilege` that intersection is genuinely
counterfactual — `ACCESS_SYSTEM_SECURITY` is pre-decided by the
privilege, and take-ownership contributes only when `WRITE_OWNER` was
not already granted — so an event means the privilege was load-bearing. <a id="cite-priv.audit.security-takeownership-counterfactual"></a>
Backup and restore seed their bits unconditionally, without asking
whether the DACL would have granted the same access, so their events
also fire for accesses the DACL alone would have permitted. <a id="cite-priv.audit.backup-restore-not-counterfactual"></a>

A `MAXIMUM_ALLOWED` request short-circuits this accounting entirely,
recording no used bits and emitting no `kacs.audit.privilege.used`
events for any privilege.

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

### At a capability gate

A privilege that satisfies a Linux capability check is recorded too,
with `operation.name` `linux-cap`, the capability in `linux.cap` and the
privilege it mapped to in `privilege.name`, under the token's
`PRIVILEGE_USE_SUCCESS` policy. The volume-management gate the mount
paths consult in place of `CAP_SYS_ADMIN` records the same way with
`operation.name` `volume-mount` and no `linux.cap`. Such a record carries
no object, masks or contribution. <a id="cite-priv.audit.gate-record"></a>

Each gate is recorded once per process and effective token: the first
use of a capability by a process under a token is recorded, and later
uses are not, until the process acts under a token with another GUID,
when every gate counts as unused again. The set belongs to the process,
not to the token, whose used flags derived tokens copy and every process
sharing it shares. <a id="cite-priv.audit.gate-once-per-process-and-token"></a>

Only successful uses are recorded, and only those of a user process's
own capability checks: a check made with `CAP_OPT_NOAUDIT` is a probe
and records nothing, nor does a kernel thread's check, a check from
interrupt context, or a check against another process's credentials. A
check that consumes no privilege — the capabilities every process holds
and the ones none may hold — records nothing either. <a id="cite-priv.audit.gate-only-own-audited-checks"></a>

A capability check can run with spinlocks held, where a record cannot
be built, so the gate notes the use and the record is written as the
process returns to user space, or as it exits. The record therefore
follows the system call that spent the privilege rather than appearing
within it. <a id="cite-priv.audit.gate-record-deferred"></a>

The boot SYSTEM token carries `PRIVILEGE_USE_SUCCESS` ([Token Lifecycle](</kernel/internals/kacs/tokens/token-lifecycle.md#trm-3-2-3>)), so on a
stock system these records come from SYSTEM and the services running on
its token: they answer who used `SeTcbPrivilege`, and for what.

---

# Privilege Catalogue

_Peios Kernel / Internals / KACS / Privileges_

> Every Peios privilege with the bit it occupies in the token's four privilege words, grouped by what it governs.

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

The complete set of Peios privileges, with the bit each occupies in
the token's four 64-bit privilege words. Format-compatible privileges
sit at their standard Windows LUID positions in bits 2–35; custom
Peios privileges are allocated downward from bit 63, so that a
privilege defined by a future AD release cannot collide with one of
ours. <a id="cite-priv.bits.luid-positions-and-downward-allocation"></a>

Enforcement classes are: **kernel standalone**, enforced at a specific
operation boundary independently of AccessCheck; **AccessCheck**,
evaluated inside the pipeline; **AccessCheck + standalone**, both;
**application-level**, checked by a userspace service rather than the
kernel; and **reserved**, allocated for format compatibility with no
enforcement point.

<a id="trm-3-4-2-1"></a>

## Identity and token management

| Privilege | Bit | Mask | Enforcement |
|---|---:|---|---|
| `SeCreateTokenPrivilege` | 2 | 0x4 | Kernel standalone |
| `SeAssignPrimaryTokenPrivilege` | 3 | 0x8 | Kernel standalone |
| `SeImpersonatePrivilege` | 29 | 0x20000000 | Kernel standalone |

`SeCreateTokenPrivilege` mints tokens from scratch, and only TCB
components — authd and peinit — carry it. <a id="cite-priv.catalogue.se-create-token"></a> `SeImpersonatePrivilege`
lets a service impersonate a principal other than itself, and every
service that handles requests on behalf of users needs it; it is
checked in exactly one place, the impersonation identity gate ([Impersonation Gates](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-2>)). <a id="cite-priv.catalogue.se-impersonate"></a>

`SeAssignPrimaryTokenPrivilege` gates installing a token as a
process's primary identity. <a id="cite-priv.catalogue.se-assign-primary-token"></a> Installation is **self-directed**:
`KACS_IOC_INSTALL` acts on the calling process and fans out to the
sibling threads of its own thread group. There is no mechanism for
installing a token on a different process ([Token Lifecycle](</kernel/internals/kacs/tokens/token-lifecycle.md#trm-3-2-3>)). The kernel also
requires the new token to carry the same user SID and the same
LogonSession as the outgoing one, unless the caller additionally holds
`SeTcbPrivilege` ([Token Lifecycle](</kernel/internals/kacs/tokens/token-lifecycle.md#trm-3-2-3>)). The privilege is also consulted as a *deny* gate on
the exec and credential projection paths.

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

## Access control

| Privilege | Bit | Mask | Enforcement |
|---|---:|---|---|
| `SeSecurityPrivilege` | 8 | 0x100 | AccessCheck + standalone |
| `SeTakeOwnershipPrivilege` | 9 | 0x200 | AccessCheck |
| `SeBackupPrivilege` | 17 | 0x20000 | AccessCheck + standalone |
| `SeRestorePrivilege` | 18 | 0x40000 | AccessCheck + standalone |
| `SeRelabelPrivilege` | 32 | 0x1_0000_0000 | AccessCheck + standalone |
| `SeChangeNotifyPrivilege` | 23 | 0x800000 | Kernel standalone |
| `SeCreateSymbolicLinkPrivilege` | 35 | 0x8_0000_0000 | Kernel standalone |
| `SeLockParentagePrivilege` | 61 | 0x2000_0000_0000_0000 | Kernel standalone |

`SeSecurityPrivilege` reads and writes an object's SACL, and also
gates `CAP_AUDIT_CONTROL`, `CAP_MAC_ADMIN` and `CAP_AUDIT_READ`
through the capability mapping, the KMES ring buffer attach, and
supplying a SACL at object creation. <a id="cite-priv.catalogue.se-security"></a>

`SeTakeOwnershipPrivilege` takes ownership of any object regardless of
its permissions. It is the only privilege here with no standalone
enforcement point at all — it exists purely inside AccessCheck. <a id="cite-priv.catalogue.se-take-ownership"></a>

`SeBackupPrivilege` and `SeRestorePrivilege` read and write any object
regardless of the DACL. Inside AccessCheck they are intent-gated
([The Privilege Model](</kernel/internals/kacs/privileges/the-privilege-model.md#trm-3-4-1>)), but both are also used as plain standalone gates outside it:
restore on the descriptor replacement path when the cache is invalid
and on owner assignment to a SID the subject does not hold, and both
on the registry key backup and restore paths. <a id="cite-priv.catalogue.backup-restore-standalone-gates"></a>

`SeRelabelPrivilege` changes an object's integrity label, punching
`WRITE_OWNER` through MIC for non-dominant callers and removing the
at-or-below-own-level restriction when a label is written. <a id="cite-priv.catalogue.se-relabel"></a>

`SeChangeNotifyPrivilege` bypasses traverse checking — without it,
reaching a file requires `FILE_TRAVERSE` on every intermediate
directory. <a id="cite-priv.catalogue.se-change-notify"></a> The bypass has one exception the name does not suggest: it
is suppressed when the access carries `MAY_CHDIR`, so an explicit
`chdir` takes a full `FILE_TRAVERSE` check whether or not the caller
holds the privilege. <a id="cite-priv.change-notify.chdir-exception"></a> The privilege additionally gates
`open_by_handle_at`, which has nothing to do with traversal. <a id="cite-priv.change-notify.open-by-handle-at"></a> It is
checked once per intermediate directory on every path resolution, and
each check takes the token's mutation lock for a snapshot and then
performs a used-bit update, so the cost is O(depth) locked operations
per path walk. <a id="cite-priv.change-notify.checked-per-directory"></a>

`SeCreateSymbolicLinkPrivilege` creates symbolic links, and is
required in addition to `FILE_ADD_FILE` on the parent directory. <a id="cite-priv.catalogue.se-create-symbolic-link"></a>

`SeLockParentagePrivilege` pins a file's ancestor directories for as
long as an open of it lasts, so that nobody can rename or remove them
([Sharing and Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md#trm-3-9-10-6>)). It is a Peios privilege, allocated
downward from bit 63. File servers hold it, to give Windows clients the
folder protection they expect; it blocks other people's work, so
ordinary programs do not. <a id="cite-priv.catalogue.se-lock-parentage"></a>

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

## System operations

| Privilege | Bit | Mask | Enforcement |
|---|---:|---|---|
| `SeTcbPrivilege` | 7 | 0x80 | Kernel standalone |
| `SeLockMemoryPrivilege` | 4 | 0x10 | Kernel standalone |
| `SeIncreaseQuotaPrivilege` | 5 | 0x20 | Kernel standalone |
| `SeLoadDriverPrivilege` | 10 | 0x400 | Kernel standalone |
| `SeSystemProfilePrivilege` | 11 | 0x800 | Kernel standalone |
| `SeSystemtimePrivilege` | 12 | 0x1000 | Kernel standalone |
| `SeProfileSingleProcessPrivilege` | 13 | 0x2000 | Kernel standalone |
| `SeIncreaseBasePriorityPrivilege` | 14 | 0x4000 | Kernel standalone |
| `SeManageVolumePrivilege` | 28 | 0x10000000 | Kernel standalone <a id="cite-priv.catalogue.se-manage-volume"></a> |
| `SeShutdownPrivilege` | 19 | 0x80000 | Kernel standalone |
| `SeDebugPrivilege` | 20 | 0x100000 | Kernel standalone |
| `SeAuditPrivilege` | 21 | 0x200000 | Kernel standalone |
| `SeRemoteShutdownPrivilege` | 24 | 0x1000000 | Kernel standalone |

`SeTcbPrivilege` is the catch-all for system operations with no more
specific privilege, and only TCB services need it. It has by far the
widest reach of any privilege: fourteen Linux capability mappings,
several token operations, the mount policy paths, the central access
policy cache, LogonSession creation and destruction, removal of
mandatory resource attribute ACEs during descriptor merge, a KMES rate
limit exemption, the LCS source authentication path, and the upgrade
of a linked-token query from an Identification-level copy to the real
token at full access. <a id="cite-priv.catalogue.se-tcb"></a>

The PEI-549 block-layer change also accepts enabled `SeManageVolumePrivilege`
or `SeTcbPrivilege`, with successful privilege-use marking, for `BLKRRPART`
(partition-table rescan), `BLKPG` (partition management) and `BLKFLSBUF`
(buffer-cache flush). The caller still needs a usable block-device handle.
Administrators membership alone, or a present but disabled privilege, does
not pass this gate. Other `CAP_SYS_ADMIN` checks, including `BLKROSET`, retain
their existing TCB requirement. This change has native VM qualification;
older published kernels may still require `SeTcbPrivilege` for all three.

`SeShutdownPrivilege` shuts down or reboots the machine, mapped
through `CAP_SYS_BOOT`. <a id="cite-priv.catalogue.se-shutdown"></a> `SeRemoteShutdownPrivilege` is required *in
addition* when the request originates from a Network,
NetworkCleartext, NewCredentials, or RemoteInteractive logon. <a id="cite-priv.catalogue.se-remote-shutdown"></a>

`SeLoadDriverPrivilege` loads and unloads kernel modules through
`CAP_SYS_MODULE`. <a id="cite-priv.catalogue.se-load-driver"></a> `SeDebugPrivilege` attaches to and inspects any
process regardless of its descriptor, and does not bypass PIP ([Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)). <a id="cite-priv.catalogue.se-debug"></a>

- `SeSystemtimePrivilege` changes the clock, <a id="cite-priv.catalogue.se-systemtime"></a>
- `SeIncreaseBasePriorityPrivilege` raises scheduling priority and
  sets CPU affinity for other processes, <a id="cite-priv.catalogue.se-increase-base-priority"></a>
- `SeIncreaseQuotaPrivilege` overrides resource limits, <a id="cite-priv.catalogue.se-increase-quota"></a>
- `SeLockMemoryPrivilege` locks pages in physical memory, <a id="cite-priv.catalogue.se-lock-memory"></a>
- and `SeAuditPrivilege` writes events to the audit log — it is what
  KMES requires for userspace event emission. <a id="cite-priv.catalogue.se-audit"></a>

`SeProfileSingleProcessPrivilege` attaches `perf_event_open()` to a
specific other process. <a id="cite-priv.catalogue.se-profile-single-process"></a> It respects PIP dominance, and own-task
profiling requires nothing. <a id="cite-priv.profile.pip-dominance-and-own-task"></a> `SeSystemProfilePrivilege` covers
system-wide profiling — per-CPU events, all-task sampling, kernel-mode
events — and does not respect PIP at the per-sample level, since
system-wide samples include PIP-protected tasks. <a id="cite-priv.catalogue.se-system-profile"></a> It is an
operator-class privilege.

Those two and `SeLoadDriverPrivilege` share one mapping: `CAP_PERFMON`
is satisfied by **any** of the three, and every one the caller holds is
marked used. <a id="cite-priv.perfmon.satisfied-by-any-of-three"></a> The two profiling privileges are otherwise disjoint
tiers.

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

## Network

No privilege. Binding a port is an access check against the port's
reservation — a security descriptor keyed by protocol and port range —
not a privilege test; see [Port reservations](/kernel/internals/kacs/network-objects/port-reservations.md#trm-3-12-1). <a id="cite-priv.network.no-port-privilege"></a>
Bit 63 was `SeBindPrivilegedPortPrivilege` until that object existed; the
bit is retired and not reused.

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

## Directory and domain operations

| Privilege | Bit | Enforcement |
|---|---:|---|
| `SeSyncAgentPrivilege` | 26 | Application-level |
| `SeEnableDelegationPrivilege` | 27 | Application-level |
| `SeMachineAccountPrivilege` | 6 | Application-level |

`SeSyncAgentPrivilege` reads every object in the directory regardless
of per-object permissions, for AD replication agents.
`SeEnableDelegationPrivilege` marks a principal as trusted for
delegation. `SeMachineAccountPrivilege` adds computer accounts to the
domain. None has a kernel definition, which is consistent with their
being application-level — but none has a userspace definition in the
tree either, so at present nothing anywhere enforces them. <a id="cite-priv.application-level.none-enforced-anywhere"></a>

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

## Reserved

Allocated for format compatibility so that tokens from Active
Directory environments carry them without information loss. None is
defined in the kernel and none has an enforcement point. <a id="cite-priv.reserved.no-enforcement-point"></a>

| Privilege | Bit | Reservation rationale |
|---|---:|---|
| `SeCreatePagefilePrivilege` | 15 | Absorbed into `SeTcbPrivilege`. |
| `SeCreatePermanentPrivilege` | 16 | No Linux equivalent. |
| `SeSystemEnvironmentPrivilege` | 22 | Gated by descriptors on efivar files under FACS. |
| `SeUndockPrivilege` | 25 | Server operating system. |
| `SeCreateGlobalPrivilege` | 30 | Peios has no per-LogonSession object namespaces. |
| `SeTrustedCredManAccessPrivilege` | 31 | Reserved for future secrets infrastructure. |
| `SeIncreaseWorkingSetPrivilege` | 33 | Linux does not gate memory residency hints. |
| `SeTimeZonePrivilege` | 34 | Linux does not gate timezone changes. |

<a id="trm-3-4-2-7"></a>

## Unallocated and unnamed bits

`SeCreateJobPrivilege` is allocated bit 62 and is unused: no kernel
definition exists for it and nothing consults it. <a id="cite-priv.create-job.bit-62-unused"></a> Submitting a
supervised job is not a privilege at all — it is governed by the file
Security Descriptor on the service manager's jobs socket, checked by
the kernel when a process connects (the Peinit TRM). The bit is
nevertheless included in the boot SYSTEM token's privilege set, which
covers bits 2–35 together with 61, 62 and 63, so the SYSTEM token holds
bit 62 present and enabled with no name attached to it and no gate
that consults it. <a id="cite-priv.create-job.present-in-system-token"></a>

Nothing validates a privilege mask against the allocated set. Token
creation checks only that the enabled set is a subset of the present
set, and adjustment accepts any bit index from 0 to 63. Bits 0, 1, and
36–60 — positions the catalogue does not allocate at all — can
therefore be set at creation and disabled or removed afterwards
without error, and are simply inert. <a id="cite-priv.bits.unallocated-accepted-and-inert"></a>

<a id="trm-3-4-2-8"></a>

## Default grants

`SeChangeNotifyPrivilege` is granted to every principal, as an authd
policy decision rather than a kernel one: the issuer's floor grants it
to Everyone. <a id="cite-priv.default.change-notify-to-everyone"></a> `SeCreateSymbolicLinkPrivilege`, the other traditional
default-grant privilege, is deliberately **not** in the floor: a
machine with no authd policy seed applied doesn't grant it. <a id="cite-priv.default.symlink-not-granted"></a> authd's
shipped policy seed grants it to Everyone, because build systems and
packaging tools assume it; a site can remove it there without
affecting the floor. Either can be removed from a specific token by
FilterToken.

---

# Impersonation

_Peios Kernel / Internals / KACS / Impersonation_

> Find the Peios kernel articles about impersonation.

Use these articles to understand impersonation in the Peios kernel.

- [Levels and admission](</kernel/internals/kacs/impersonation/levels-and-admission.md>)
- [State transitions](</kernel/internals/kacs/impersonation/state-transitions.md>)
- [Transport and per-message identity](</kernel/internals/kacs/impersonation/transport-and-per-message-identity.md>)

---

# Levels and admission

_Peios Kernel / Internals / KACS / Impersonation_

> The four levels at which a server thread may assume a client's identity, and what each permits.

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

Impersonation lets a server thread temporarily assume a client's
identity, so that access control decisions on that thread evaluate the
client's token instead of the server's.

The client controls how far its identity can travel by setting an
impersonation level on the connection before it is established, and
the server cannot escalate beyond the level the client chose. There is
no API that bypasses that choice.

**Anonymous.** The server cannot identify the caller at all. The
connection carries no identity information: both token inspection and
impersonation yield a token whose user SID is Anonymous (`S-1-5-7`),
which carries Everyone as an enabled group and does not carry
Authenticated Users. <a id="cite-imp.anonymous.no-identity-conveyed"></a>

**Identification.** The server can identify the caller — read SIDs,
query groups, inspect privileges — but cannot act as them. An
Identification-level token is barred from AccessCheck against
resources: a server thread impersonating one and attempting to open a
file simply fails the check, with `EACCES` — the same refusal the
`kacs_access_check` syscall reports for that token. <a id="cite-imp.identification.barred-from-accesscheck"></a>

**Impersonation.** The server can act as the caller for all local
operations, including ones that cross local IPC boundaries. If service
A impersonates client B at this level and connects to local service C,
C sees B's identity — identity cascades freely across local services. <a id="cite-imp.impersonation.cascades-across-local-services"></a>
This is the default.

**Delegation.** Locally identical to Impersonation. The distinction
activates at the network boundary, where a Delegation-level token
carries authorization for the server to forward the client's identity
to services on other machines through Kerberos. <a id="cite-imp.delegation.network-boundary-only"></a> KACS enforces the
level; authd is what acts on it.

The level is set by the client through a KACS syscall on the socket
before `connect()`, and defaults to Impersonation. <a id="cite-imp.level.socket-default-impersonation"></a>

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

## The level is a ratchet <a id="cite-imp.level.ratchet-only-down"></a>

Every token carries an impersonation level, and on every token it
means the same thing: *identity derived from this token may act at no
more than this level*. An impersonation token acts at its level. A
primary token's level is the ceiling on everything the process
carrying it can convey — what a peer captures at connect, what
`KACS_SO_PASS_TOKEN` attaches, what `KACS_IOC_DUPLICATE` produces in
either direction. <a id="cite-imp.level.primary-is-conveyance-ceiling"></a>

The level only ever goes down:

- Socket capture and `KACS_SCM_TOKEN` attach store the lower of the
  socket's level and the source token's own; <a id="cite-imp.level.capture-takes-lower"></a>
- DuplicateToken refuses a result above its source, whatever the types
  involved;
- fork, exec, `NEW_PROCESS_MIN`, FilterToken and primary installation
  copy it unchanged. <a id="cite-imp.level.derivation-copies-unchanged"></a>

The one way to a higher level is a fresh token from CreateToken, which
takes `SeCreateTokenPrivilege`. <a id="cite-imp.level.raise-only-via-create-token"></a> authd mints logon tokens at Delegation
and the bootstrap SYSTEM token is Delegation, so an identity starts at
the top and each hop can only lower it.

This is what makes the client's choice hold across any number of
hops and process boundaries. A client that connects at Impersonation
is captured at Impersonation; a server that converts that token to a
primary and launches a process with it ([Token Creation](</kernel/internals/kacs/tokens/token-creation.md#trm-3-2-4>)) produces a process
capped at Impersonation; and nothing that process captures, conveys
or duplicates can ever be Delegation — so authd, which reads the
level to decide whether to forward the client's credentials, is never
shown a Delegation flag the client did not grant. <a id="cite-imp.level.holds-across-hops"></a>

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

When a server thread attempts to impersonate a client's token, two
independent checks decide whether it proceeds at the requested level.
Both have to pass. If either fails the effective level is reduced to
Identification — the movement is only ever downward.

Both gates are evaluated against the server's **primary token**
(`real_cred`), never its effective token. <a id="cite-imp.gate.evaluated-against-primary-token"></a> A server already
impersonating another client has its gates judged against its own
service identity, so a previous impersonation cannot influence the
next one.

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

## The identity gate

The identity gate asks whether this server may impersonate this
particular user's identity. Impersonation at Impersonation or
Delegation level is permitted if either of two conditions holds.

**Same user, same restriction status** — the server's primary token
and the client's token carry the same user SID, and both are
restricted or both unrestricted. <a id="cite-imp.gate.same-user-same-restriction"></a>

**`SeImpersonatePrivilege`** — the server's primary token holds it,
enabled. <a id="cite-imp.gate.impersonate-privilege-enabled"></a>

If neither holds, the level is **silently capped to Identification**. <a id="cite-imp.gate.identity-failure-caps-silently"></a>
No error is returned: the call succeeds, and the resulting token is
merely at Identification level.

There is one hard denial. A **restricted** server impersonating an
**unrestricted** client of the same user is rejected outright with
`-EPERM` rather than capped, because that is precisely how a sandboxed
process would escape by impersonating its parent's unrestricted token. <a id="cite-imp.gate.restricted-to-unrestricted-eperm"></a>
The reverse direction, unrestricted server to restricted client, is a
harmless downgrade and takes the ordinary cap-to-Identification path. <a id="cite-imp.gate.unrestricted-to-restricted-caps"></a>

MS-DTYP includes a third condition — an origin LogonSession check
letting the session that created a token impersonate it without the
privilege. KACS drops it. A service needing to impersonate a different
user holds `SeImpersonatePrivilege`, and there are no hidden paths.

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

## The integrity ceiling <a id="cite-imp.gate.integrity-ceiling"></a>

The integrity ceiling asks whether the client's token sits at an
integrity level the server is allowed to assume. To act at
Impersonation or Delegation level, the client token's integrity level
has to be less than or equal to the server primary token's. A
Medium-integrity server can impersonate Low or Medium clients; against
a High-integrity client the level caps to Identification.

The installed token may keep the client's literal integrity label as
identity metadata after the cap, but that preserved label authorizes
nothing, because Identification-level tokens are barred from
AccessCheck entirely. <a id="cite-imp.gate.capped-token-keeps-label"></a>

The ceiling exists because MIC evaluates the *effective* token's
integrity level for tokens that can act. Without it, a server could
impersonate a higher-integrity token and gain write access to
higher-integrity objects — integrity escalation through impersonation.

The ceiling is enforced unconditionally, regardless of privilege.
`SeImpersonatePrivilege` bypasses the identity gate and never the
ceiling. <a id="cite-imp.gate.privilege-never-bypasses-ceiling"></a> MS-DTYP allows the privilege to bypass every check including
this one; KACS does not, because `mandatory_policy` is immutable here
([Token Structure](</kernel/internals/kacs/tokens/token-structure.md#trm-3-2-2>)) and MIC is consequently a real boundary. Letting a privilege
punch through would give back exactly what that immutability buys.

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

## Composition <a id="cite-imp.gate.composition-minimum"></a>

The two gates are independent, both are evaluated, and the effective
level is the minimum any constraint permits: start from the level the
client set on the socket, cap to Identification if the identity gate
fails, cap to Identification if the integrity ceiling fails, and the
result is the effective impersonation level.

---

# State transitions

_Peios Kernel / Internals / KACS / Impersonation_

> State transitions: behaviour and implementation of the Peios kernel.

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

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

## The sequence

**The client connects.** It optionally sets the maximum impersonation
level on the socket with `setsockopt(SOL_KACS,
KACS_SO_IMPERSONATION_LEVEL)` — the default is Impersonation; the
option may be changed at any time and bounds every capture made from
then on — and calls `connect()`. <a id="cite-imp.capture.level-changeable-bounds-later-captures"></a> The kernel's LSM hook fires on the
Unix stream connection.

**Identity is captured, both ways.** The hook examines the client
thread's effective credential together with the socket's maximum
level, derives the identity at the lower of that level and the
effective token's own ([Impersonation Levels](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-1>)), and stores the result on the accepted
end. It also stores, on
the connecting end, the identity the listener captured when `listen()`
was called — so a client can read `KACS_SO_PEER_TOKEN` on its own
socket immediately after `connect()` and verify who it reached, at
Identification level unless the listener set its own level. <a id="cite-imp.capture.listener-identity-to-connecting-end"></a> The
listener's identity is what `listen()` saw; a process that inherits a
listener it did not create (from a descriptor store after a restart,
or from a broker) replaces it with its own using `setsockopt(SOL_KACS,
KACS_SO_RESTAMP)`, which is self-gated and fails with `EINVAL` on a
socket that is not listening. <a id="cite-imp.restamp.listening-socket-only"></a> Clients that connect before the restamp
see the previous holder, which is honest: that is who was listening. <a id="cite-imp.restamp.not-retroactive"></a>
Squatting a name therefore buys nothing against a client that checks —
the squatter's own identity is what it conveys. At
Anonymous, a token whose user SID is `S-1-5-7`, whose enabled groups
include Everyone, and which does not carry Authenticated Users is
stored on the socket's LSM blob, and the client's real identity is
never recorded. <a id="cite-imp.capture.anonymous-records-no-real-identity"></a> At Impersonation or Delegation, the thread's effective
token is stored — and if the connecting thread is itself
impersonating, the impersonated identity is what flows through, which
is how identity cascades across local services. <a id="cite-imp.capture.stores-effective-token"></a> At Identification, the
effective token is stored but tagged at that level.

**The server reads the peer token** with `getsockopt(SOL_KACS,
KACS_SO_PEER_TOKEN)` on the accepted connection, which opens a token fd
carrying `TOKEN_QUERY | TOKEN_IMPERSONATE | TOKEN_DUPLICATE` for the
identity in that
end's conveyed-identity register — at this point, the identity captured
at connect (see *Per-message identity* below for how the register
moves). <a id="cite-imp.peer-token.fd-access-mask"></a>
**It impersonates** by installing that fd with `KACS_IOC_IMPERSONATE`:
the kernel evaluates both gates against the server thread's primary
token, computes the effective level, and constructs a new credential
carrying the impersonation token at that level. libpeios fuses the
two steps as `peios_token_impersonate_peer` for the handler that
impersonates, works and reverts on one thread.

**Access control follows the impersonation token.** Every subsequent
AccessCheck on the thread evaluates it, and MIC uses its integrity
level. PIP continues to read the PSB, unchanged.

**The server reverts** with `kacs_revert()`, restoring the thread's
credential to `real_cred` and its service identity with it. <a id="cite-imp.revert.restores-real-cred"></a>

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

## Anonymous

Any thread may impersonate the Anonymous identity without passing
either gate. <a id="cite-imp.anonymous.no-gates"></a> Assuming Anonymous is always a downgrade — the token has
no access beyond what is explicitly granted to `S-1-5-7` or Everyone —
so no privilege is needed, no identity gate runs, and no integrity
ceiling applies.

Anonymous tokens carry the Anonymous SID as the user SID, no
privileges, and Untrusted integrity. The socket path constructs that
minimal shape rather than preserving any part of the caller's real
identity. <a id="cite-imp.anonymous.socket-constructs-minimal-shape"></a>

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

## Double impersonation <a id="cite-imp.double.revert-then-reimpersonate"></a>

A thread already impersonating that installs another token with
`KACS_IOC_IMPERSONATE` causes the kernel to revert internally and then
re-impersonate.
Because the gates are evaluated against the primary token, the
previous impersonation has no bearing on the new one.

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

## Interaction with MIC and PIP

**MIC reads the effective token** for tokens permitted to act, which
is safe precisely because the integrity ceiling makes acting
impersonation safe. <a id="cite-imp.mic.reads-effective-token"></a> A thread cannot act at Impersonation or Delegation
level with a client token whose integrity exceeds the server primary
token's. When the ceiling caps the level to Identification, the
installed token may still preserve the client's literal label as
metadata, but it authorizes no resource access because
Identification-level tokens are barred from AccessCheck. An acting
impersonation token therefore preserves or lowers the server's
integrity, and a higher literal label can only ever exist on a
non-acting Identification-level token.

**PIP reads the PSB**, because there is no equivalent ceiling for it. <a id="cite-imp.pip.reads-psb-not-effective-token"></a>
PIP operates on `pip_type` and `pip_trust`, which are orthogonal to
integrity level. Reading them from the effective token would let a
process impersonate a token carrying higher PIP values and acquire
protection it has not earned.

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

## SeImpersonatePrivilege

The privilege permits a service to impersonate arbitrary clients —
those with different user SIDs. Without it a process can impersonate
only tokens matching its own user SID and restriction status.

It is checked against the server's primary token, so a thread already
impersonating one client is judged on its real service identity. It
has to be enabled at the moment of the call. And it bypasses the
identity gate only, never the integrity ceiling.

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

## Audit records

Every `KACS_IOC_IMPERSONATE` writes a `kacs.impersonation.started`
record through KMES ([Audit Event Schemas](</kernel/internals/kacs/auditing/event-families-and-delivery.md#trm-3-c>)). Its subject is the server's token, the one
that acted, and its object is the client token: `object.token.sid`,
`.type`, `.integrity`, `.auth-id` and `.restricted`, with the level the
client token offered as `object.token.impersonation` and the level the
gate allowed as `object.token.impersonation-permitted`. The thread that
took the identity on is `emitter.thread.tid`, since impersonation is per
thread. Where the gate needed `SeImpersonatePrivilege` and used it, the
record carries `privilege.name` and `privilege.held`. <a id="cite-imp.audit.started-record"></a>

A level the gate lowered is not a failure: the record says
`outcome.success` with `impersonation-permitted` below
`impersonation`. A lowered level installs a new token, and the record's
`object.token.guid` and `object.token.id` are always the installed
token's — the client's own when the level was not lowered, the new one
when it was — so they match the header of the records the thread writes
next. <a id="cite-imp.audit.started-permitted-level"></a>

A refused impersonation is recorded too, with `outcome.errno` and, where
the kernel knows why, `outcome.reason`: `primary-token` for a primary
token (`EINVAL`), `restriction-escape` for a restricted server reaching
for an unrestricted token of its own user (`EPERM`),
`no-impersonate-access` for a handle without `TOKEN_IMPERSONATE`
(`EACCES`), and `projection-failed` when the identity could not be
projected onto the thread's credentials. A refusal before the gate
answered carries no `impersonation-permitted`. <a id="cite-imp.audit.started-records-refusals"></a>

Ending an impersonation writes `kacs.impersonation.reverted`, a
`verbose` type, so only where the emission policy ([Emission Policy](</kernel/internals/kmes/emission-policy.md#trm-2-8>)) switches it on.
The record names the
token given up in `object.token.guid` and `object.token.sid`, with the
thread's token after the revert as subject. `operation.name` says why:
`revert` for `kacs_revert`, `exec` for the revert every exec performs,
and `replaced` when a second impersonation ends the first. A revert with
no impersonation in force writes nothing, nor does the revert and
re-apply around a primary-token install, which leaves the impersonation
in place, nor does a thread that exits while impersonating. <a id="cite-imp.audit.reverted-record"></a>
Both records are best effort: a record that cannot be built does not
change the outcome of the impersonation or the revert.

## Related explanations

- [Transport and per-message identity](</kernel/internals/kacs/impersonation/transport-and-per-message-identity.md>)

---

# Transport and per-message identity

_Peios Kernel / Internals / KACS / Impersonation_

> Transport and per-message identity: behaviour and implementation of the Peios kernel.

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

## Delegation and the network boundary

Locally, Impersonation and Delegation behave identically. The
distinction activates at the network boundary, where a
Delegation-level token carries authorization for Kerberos credential
forwarding to services on other machines.

KACS tracks the level on the token and the socket, and authd checks it
when it needs to perform Kerberos authentication for an impersonating
thread. KACS itself has no Kerberos awareness and no network
awareness: the level is a flag that authd interprets.

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

## Per-message identity

The connect-time capture is the first entry in a per-end
**conveyed-identity register**: the peer identity associated with the
data that end has consumed so far. <a id="cite-imp.register.connect-capture-is-first-entry"></a> Identity can also travel with the
data itself, as a `KACS_SCM_TOKEN` ancillary message under the
`SOL_KACS` level, and each such message the reader's position passes
advances the register. The anchor is the read position, never arrival:
a token still queued behind unread data is not yet visible, so a
handler can never be told an identity for a request it has not read. <a id="cite-imp.register.anchored-at-read-position"></a>
`KACS_SO_PEER_TOKEN` returns a fresh fd to an immutable snapshot each
time; two calls may name different tokens, but a token never changes. <a id="cite-imp.peer-token.immutable-snapshot"></a>

**Sending.** A sender conveys identity in one of two ways, and the
receiver cannot tell them apart, because both mean the same thing —
*the kernel verified that the sender could be this identity when it
sent these bytes*:

- Automatically, with `KACS_SO_PASS_TOKEN` set on the sending end:
  every send carries the sender's effective token, derived at the
  lower of the end's impersonation level and the token's own. <a id="cite-imp.pass-token.every-send-carries-effective"></a> The derivation is cached against the
  effective token it was made from, so a run of sends under one
  identity costs one derivation. <a id="cite-imp.pass-token.derivation-cached"></a> A thread that impersonates client A,
  writes to a pooled connection, reverts and writes again conveys A for
  the first write and its own identity for the second, with no change
  to the library doing the writing.
- Explicitly, by attaching a token fd in a `KACS_SCM_TOKEN` cmsg. The
  kernel gates the attach exactly as it would gate impersonating that
  token: the fd must carry `TOKEN_IMPERSONATE`, a primary token is
  first derived to an impersonation token at the lower of the end's
  level and its own, and the
  two-gate model runs with the sender as installer. <a id="cite-imp.scm-token.gated-as-impersonation"></a> An attach the gates
  would cap below the token's own level fails with `EPERM` — an
  explicit act fails loudly where an install would silently downgrade. <a id="cite-imp.scm-token.cap-fails-eperm"></a>
  Attaching a token is therefore never more than impersonating it,
  sending, and reverting; it just avoids the install. A router
  forwarding on behalf of many clients re-attaches each client's token
  to the messages it forwards, and each downstream receiver gets a
  kernel-verified identity through the router.

Anonymous-level tokens attach without a gate, as assuming Anonymous is
always a downgrade. <a id="cite-imp.scm-token.anonymous-attaches-ungated"></a> At most one token per message. <a id="cite-imp.scm-token.one-per-message"></a>

**Receiving.** Every skb a send produces carries the conveyed token, so
a large stream write conveys the same identity on all of its
fragments. <a id="cite-imp.receive.identity-on-every-fragment"></a> A stream read stops at an identity boundary rather than
gluing bytes conveyed under different identities into one return,
which keeps the register exact even on a byte stream; on
`SOCK_SEQPACKET` one send is one message and one identity, which is
why it is the recommended type for Peios-native protocols. <a id="cite-imp.receive.read-stops-at-identity-boundary"></a> As the
reader's position passes conveyed data, the register moves to that
identity. `MSG_PEEK` neither advances the register nor consumes; a
`read()` or `splice()` that consumes data advances it just as
`recvmsg` does, because the register is kept at the point of
consumption, not where ancillary data is copied out. <a id="cite-imp.register.advances-on-consumption-only"></a>

A `KACS_SCM_TOKEN` cmsg — carrying a fresh `TOKEN_QUERY |
TOKEN_IMPERSONATE | TOKEN_DUPLICATE` fd — is delivered with a read when
the receive call
supplied room for it and the read's identity differs from the register
the reader had before the read; otherwise nothing is delivered, and
`MSG_CTRUNC` is set only when a token was due and no room was
supplied. <a id="cite-imp.cmsg.delivered-on-identity-change"></a> A handler that never reads ancillary data still has the
register: `recvmsg`, then `getsockopt(KACS_SO_PEER_TOKEN)`, gives the
identity of what it just read. <a id="cite-imp.register.getsockopt-after-read"></a> Parsing the cmsg is the path for
pipelined or concurrent consumers that need the token bound to a
particular message.

`SOCK_DGRAM` sockets carry no register — many senders share one
receiving socket — so a datagram's token is delivered with every
datagram that carries one and is never retained. <a id="cite-imp.dgram.no-register"></a>

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

## Supported transports

Peer-token capture works on two AF_UNIX socket types. <a id="cite-imp.transport.stream-and-seqpacket"></a> `SOCK_STREAM`
is the connection-oriented byte stream, and `SOCK_SEQPACKET` is
connection-oriented with message boundaries and uses the same identity
capture model. Both follow the same lifecycle: capture at `connect()`,
read with `KACS_SO_PEER_TOKEN`, impersonate, revert — with per-message
identity layered on top as described above. `SOCK_DGRAM` supports
per-message identity only: `KACS_SO_PASS_TOKEN` and `KACS_SCM_TOKEN`
work, since a send needs no connection, and
`KACS_SO_IMPERSONATION_LEVEL` bounds them as on any socket, but there
is no register. <a id="cite-imp.dgram.per-message-identity-only"></a>

Where the register does not apply, `KACS_SO_PEER_TOKEN` reports which
case it is. On a datagram socket, or any non-Unix family, the option
fails with `EOPNOTSUPP`. <a id="cite-imp.peer-token.eopnotsupp-non-unix"></a> A `socketpair()` end is connected but starts
with an empty register — no connect happened to capture anything — so
the option fails with `ENODATA` until the peer conveys an identity,
after which the register works as on any connection. <a id="cite-imp.peer-token.socketpair-enodata"></a> A socket that is
not yet connected fails with `ENOTCONN`. <a id="cite-imp.peer-token.enotconn"></a> Pipes and FIFOs are not
sockets at all, so `getsockopt` itself fails with `ENOTSOCK` before
KACS is reached. <a id="cite-imp.peer-token.enotsock-pipes"></a>

For all of these, the universal fallback is explicit token fd
impersonation through `KACS_IOC_IMPERSONATE`, which works regardless
of how the token fd was obtained — the peer-token option, an
`SCM_RIGHTS` transfer, or any other path. <a id="cite-imp.impersonate.any-token-fd"></a>

---

# Executable trust

_Peios Kernel / Internals / KACS / Executable trust_

> Find the Peios kernel articles about executable trust.

Use these articles to understand executable trust in the Peios kernel.

- [Signature verification](</kernel/internals/kacs/executable-trust/signature-verification.md>)
- [Exec and library integrity](</kernel/internals/kacs/executable-trust/exec-and-library-integrity.md>)
- [Firmware verification](</kernel/internals/kacs/executable-trust/firmware-verification.md>)
- [Process integrity protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md>)

---

# Signature verification

_Peios Kernel / Internals / KACS / Executable trust_

> Signature verification: behaviour and implementation of the Peios kernel.

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

Binary signing is the foundation of PIP trust determination and of
Library Signature Verification. The kernel verifies cryptographic
signatures on executable files to establish their trust level, and
signing is the *only* mechanism by which a binary acquires PIP
protection — there is no runtime API that can confer it.

This section describes verification. The signature format itself, and
what a signer has to produce, are specified in PSPK's Binary Signing
and PIP chapter. The kernel only ever verifies; it holds no private
key and contains no signing primitive.

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

## The key table

The kernel carries its verification keys in a dedicated data section
of the kernel image, as an array of 1960-byte entries — a raw
1952-byte ML-DSA-65 public key, then a `u32` little-endian PIP type,
then a `u32` little-endian PIP trust — terminated by an all-zero
entry. <a id="cite-sig.key-table.entry-layout"></a>

Before any cryptographic work, the whole table is walked and
validated. A table with no all-zero terminator is rejected with
`EINVAL`, and so is a table containing any entry whose tier is not
exactly Protected (512) with `PeiosTcb` trust (8192). <a id="cite-sig.key-table.validation-einval"></a> Both rejections
fail *every* verification on the system, which is what makes the
single-tier constraint absolute rather than conventional: a key at any
other tier does not merely fail to be honoured, it disables signing
entirely. <a id="cite-sig.key-table.invalid-disables-all"></a>

The consequence is that a verified binary is always Protected/8192. <a id="cite-sig.verified-always-protected-tcb"></a>
The Isolated type (1024) is reserved and unreachable, and the
multi-key, multi-tier model the table layout anticipates would need a
change to the validator, not merely an added key. <a id="cite-sig.isolated-type-unreachable"></a>

A build configured for KUnit compiles in a different, hard-coded key
at the same tier, taken from the test vector header. <a id="cite-sig.kunit-test-key"></a> Such a kernel
trusts a publicly known key.

`/sys/kernel/security/kacs/signing_keys` lists the table: one line for
each entry before the terminator, in table order, reading

```
key_sha256=<hex> pip_type=<u32> pip_trust=<u32>
```

where the key is named by the SHA-256 of its raw 1952-byte public key, in
lowercase hexadecimal, and the type and trust are the entry's own, in
decimal. <a id="cite-sig.key-table.securityfs-listing"></a> Entries are listed as they
are, whether or not the validator would accept them, so a table that
disables signing shows why. The keys are public, so reading the file is
not access-checked; whoever can open it can read it. Like every
securityfs object, it can be opened only once the mount has a
synthesising policy, which on Peios lets Authenticated Users in.
<a id="cite-sig.key-table.securityfs-unchecked"></a>

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

## Finding a signature

Verification begins by recording the file's current size. Everything
that follows is bounded by that snapshot, and the size is re-read
before the attempt returns — a file that changed size mid-verification
invalidates the whole result. <a id="cite-sig.size-snapshot-revalidated"></a>

The first four bytes decide the path. A file matching `\x7fELF` takes
the ELF path; a file shorter than four bytes, or with different magic,
goes straight to the xattr. <a id="cite-sig.magic-selects-path"></a>

On the ELF path the kernel parses the header, locates the section
header table and the section-name string table, and scans sections in
index order for one named exactly `.peios.sig`. The match is over all
eleven bytes including the terminating NUL, so a longer name with that
prefix does not match. <a id="cite-sig.elf.section-name-exact-match"></a>

**Finding the section commits the ELF path.** The moment a section
header with that name is found, the xattr is no longer consulted —
whatever happens next. <a id="cite-sig.elf.section-commits-path"></a> A wrong section type, a size other than 3310, a
range outside the file, an allocation failure, a short read, a bad
version byte, or a hash failure all yield "unsigned" rather than
falling back. <a id="cite-sig.elf.section-failures-yield-unsigned"></a> This is deliberate: without it, an attacker could craft
a malformed ELF section to force fallback to whichever path they could
more easily control.

Several *structural* ELF failures commit the path too, before any
`.peios.sig` section has been seen: a file shorter than an ELF header,
a class other than `ELFCLASS64`, a byte order other than little-endian,
an unexpected ELF version, a section header entry size other than 64,
an absent or out-of-range section-name string table index, and a
section header table or string table lying outside the recorded size. <a id="cite-sig.elf.structural-failures-commit"></a>
A 32-bit or big-endian ELF therefore cannot carry an xattr signature
at all — it is committed to the ELF path and then fails on it. The one
structural case that does *not* commit is `e_shnum == 0`, so an ELF
with no section headers falls through to the xattr normally. <a id="cite-sig.elf.no-section-headers-falls-through"></a>

The xattr path reads `security.peios.sig` and requires exactly 3310
bytes; any other size is treated as unsigned. <a id="cite-sig.xattr.exact-size"></a> The read bypasses the
LSM xattr hooks, so FACS does not mediate the verifier's own read of
the signature. <a id="cite-sig.xattr.read-bypasses-lsm-hooks"></a>

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

## Hashing and verification

The message signed is a 32-byte SHA-256 content hash, computed
differently depending on where the signature was found. For an ELF
section source, the hash covers the file with the section's *contents*
replaced by zeros — the `Elf64_Shdr` entry describing it is hashed
verbatim, along with everything else. <a id="cite-sig.hash.elf-section-zeroed"></a> For an xattr source the hash
covers the entire file with no exclusions, and that applies to ELF
files reaching the xattr path as well as to non-ELF ones. <a id="cite-sig.hash.xattr-covers-whole-file"></a> Hashing
proceeds in 4 KB chunks, with the zero run emitted in
`SHA256_BLOCK_SIZE` pieces.

The kernel then verifies the 3309-byte signature against each key in
the table, in order, returning on the first success. <a id="cite-sig.verify.exhaustive-trial-in-order"></a> There is no key
identifier in the blob, so key selection is exhaustive trial and the
cost is one ML-DSA verification per key. The trust tier is a property
of *which key verified*, never of anything the signer encoded. <a id="cite-sig.tier-from-key-not-blob"></a>

Verification uses the kernel crypto signature API with the `mldsa65`
algorithm. That API exposes no context parameter, so the empty FIPS
204 context is structurally guaranteed rather than checked — a
signature made under a non-empty context simply fails to verify. <a id="cite-sig.empty-fips204-context"></a>

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

### When verification cannot be performed

"Did not verify" and "could not be verified" are different answers and
are kept apart. The per-key verifier is tri-state: verified, did not
verify, or a negative errno meaning the check could not be made — an
unavailable ML-DSA transform, or a key the transform will not accept. <a id="cite-sig.verifier.tri-state"></a>

A negative stops the search rather than trying the remaining keys: the
failure is in the machinery, and every remaining key would meet the same
one. It then propagates out of the exec path, which **refuses the exec**
with `EACCES`. <a id="cite-sig.unverifiable.exec-eacces"></a>

That asymmetry with the ordinary unsigned path is the point. An unsigned
binary runs with no integrity label, which is legitimate. Treating an
unverifiable one the same way removes PIP from every process the system
executes, and the result is indistinguishable from a correctly working
system that has no signed binaries — so nothing surfaces it until
signing is deployed, at which point it looks like the signing rollout
broke something.

On the LSV path the same condition denies the mapping, which already
fails closed. <a id="cite-sig.unverifiable.lsv-denies"></a>

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

### The boot-time probe <a id="cite-sig.boot-probe"></a>

A `late_initcall` allocates the transform once and, if it cannot,
emits `pr_err` and a `kacs.signature.crypto.failed` KMES event
carrying `signature.crypto-stage` `boot-probe` and the error as
`outcome.errno`, negative. The condition is then visible at boot rather than
inferred from every process running without an integrity label.

It cannot refuse to start, and two things rule that out rather than one:

- At LSM init the algorithm is not yet registered, so `crypto_alloc_sig`
  returns `ENOENT` on every boot. A probe there would fire always.
- A non-zero return from an LSM's init function is only `WARN`'d
  (`security/lsm_init.c`, `lsm_init_single`). The hooks are never added,
  so "refuse to initialise" means running with no KACS at all — worse
  than the failure it would be preventing.

Enforcement therefore lives at exec, where refusing one exec is
recoverable in a way losing the integrity boundary is not.

The probe is not `IS_ENABLED(CONFIG_CRYPTO_MLDSA)`. That option is an
unconditional `select` under `SECURITY_PKM`, which is a `bool`, so a
config test would always pass and catch nothing. Only calling the
allocator sees the ordering failure.

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

## Revocation <a id="cite-sig.no-revocation"></a>

There is none. A signed binary later found to be malicious cannot be
invalidated short of removing it from the filesystem or replacing the
kernel image with a different key. No hash blocklist, no per-key
revocation, and no revocation state of any kind exists.

## Related explanations

- [Exec and library integrity](</kernel/internals/kacs/executable-trust/exec-and-library-integrity.md>)
- [Firmware verification](</kernel/internals/kacs/executable-trust/firmware-verification.md>)

---

# Exec and library integrity

_Peios Kernel / Internals / KACS / Executable trust_

> Exec and library integrity: behaviour and implementation of the Peios kernel.

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

## PIP determination at exec

At `execve()` the kernel looks up and verifies the signature as above.
A verified binary takes `pip_type` and `pip_trust` from the matched
key; no signature, an invalid or unstable one, a bad signature, or no
matching key all yield None/0. <a id="cite-sig.exec.tier-from-matched-key"></a>

**Exec proceeds in every case where the question could be answered.** <a id="cite-sig.exec.proceeds-regardless"></a>
PIP is additive protection, not an execution gate: it determines trust
level, not permission to run. The one exception is a signature that
could not be verified at all, described above, which refuses the exec —
because there the question was not answered, so there is no basis on
which to assign a trust level. An
attacker who replaces a signed binary's signature with garbage costs
it PIP protection but can still execute it, subject to FACS. The
asymmetry with LSV — which *does* block unsigned libraries — is
intentional. Exec is permissive; `mmap(PROT_EXEC)` is restrictive.

Determination is transactional with exec success, in three phases. The
pending value is cleared at the top of every `bprm_creds_from_file`
invocation, staged into the task's security blob, and committed to the
process state only from `bprm_committed_creds`. <a id="cite-sig.exec.stage-then-commit"></a> An exec that fails
between staging and commit leaves the process state untouched, and the
stale pending value is cleared by the next exec or at task teardown. <a id="cite-sig.exec.failed-exec-leaves-state"></a>

Because the hook fires once per binfmt iteration and each iteration
re-stages, a `#!` script's PIP comes from the **interpreter** — the
last file processed — not from the script. <a id="cite-sig.exec.shebang-takes-interpreter"></a> A TCB-signed interpreter
runs at TCB level whatever script it executes. Symlinks need no
special handling either: the LSM hooks receive the already-resolved
target file, so a symlink inherits its target's level by construction. <a id="cite-sig.exec.symlink-resolves-to-target"></a>

Once committed, the values are fixed for the lifetime of the process
image, inherited at fork, and re-derived at the child's exec. <a id="cite-sig.exec.fixed-and-inherited"></a>

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

## Content pinning

A binary that verifies to a nonzero tier has its backing inode pinned
as KACS-verified executable content before the exec result is
committed, and LSV pins on success too, before allowing the mapping. <a id="cite-sig.pin.on-verified-exec-and-lsv"></a>
Pinning closes the gap between verifying one byte image and modifying
the same inode afterwards.

If pinning fails at exec, the PIP result is **downgraded to None/0**
rather than the exec being failed or the tier being kept — the process
runs unprotected. <a id="cite-sig.pin.failure-downgrades-to-none"></a> Under LSV a pin failure denies the mapping instead. <a id="cite-sig.pin.failure-denies-lsv-mapping"></a>

A pinned inode rejects in-place content mutation even when the size
would be preserved: ordinary, positioned and append writes;
`ftruncate()` and pathname `truncate()`; and every `fallocate` mode,
including allocation-only ones, because the pin check runs before and
independently of the mode-support test. <a id="cite-sig.pin.rejects-content-mutation"></a> File ioctls that mutate
content, ranges, or allocation are rejected, and so are ioctls the
kernel cannot classify — unknown ioctls fail closed on a pinned inode. <a id="cite-sig.pin.unknown-ioctl-fails-closed"></a>
Mutation or removal of the `security.peios.sig` xattr is rejected as
well. <a id="cite-sig.pin.rejects-sig-xattr-mutation"></a>

The pin is conservative and one-way. It is set once and cleared only
when the inode is allocated or freed, never while the inode is live. <a id="cite-sig.pin.cleared-only-at-inode-lifecycle"></a>
Updating verified executable content therefore means replacing the
inode — write a new file and `rename()` over it — rather than
modifying it in place.

Unsigned, invalid, unstable, bad-signature and no-match attempts never
pin. <a id="cite-sig.pin.only-on-verified"></a>

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

## Library Signature Verification

With the `lsv` mitigation enabled, `mmap()` with `PROT_EXEC` on a
file-backed mapping verifies the backing file. An unsigned file, an
invalid or unstable one, a bad signature, or no matching key all deny
the mapping with `EACCES`. <a id="cite-sig.lsv.denies-unsigned-eacces"></a> On success the library's tier is compared
against the loading process's: the image has to dominate the process,
so a Protected/PeiosTcb process can load only PeiosTcb-or-above
libraries. <a id="cite-sig.lsv.image-must-dominate-process"></a> With one key in the table this reduces to "is it signed
with the TCB key?"

The hash covers the **entire file**, not the mapped region — the whole
file is read and hashed even when only part of it is being mapped, so
the signature covers code in sections this particular mapping does not
touch. <a id="cite-sig.lsv.hashes-whole-file"></a>

`mprotect()` adding `PROT_EXEC` to a mapping that was not already
executable runs the same checks in a fixed order: WXP, then TLP, then
LSV. <a id="cite-sig.lsv.mprotect-check-order"></a> Anonymous mappings have neither a path nor a signature, so TLP
and LSV skip them and only WXP applies. <a id="cite-sig.lsv.anonymous-skips-tlp-lsv"></a>

Enabling `lsv` on a running process also re-validates its existing
executable mappings before the bit is committed ([PSB Fields](</kernel/internals/kacs/process-security/psb-fields.md#trm-3-3-2>)), so the
mitigation cannot be turned on over already-mapped unsigned code.

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

## Interaction with other mechanisms

**WXP** is orthogonal: it prevents pages being writable and executable
at once, while LSV prevents unsigned executable pages. A process with
both can execute only signed code in read-only pages.

**FACS** runs independently. A signed binary in a directory the caller
cannot reach is still unreachable — the open is denied before signing
is consulted. <a id="cite-sig.facs.open-denied-before-signing"></a> Signing determines the PIP level of a binary that is
already being executed; it never grants access to one.

**PIP object protection** consumes the result: once a process carries
a tier from its binary's signature, trust labels on objects are
enforced through the AccessCheck pipeline against the `pip_type` and
`pip_trust` held in the PSB ([Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)).

---

# Firmware verification

_Peios Kernel / Internals / KACS / Executable trust_

> Firmware verification: behaviour and implementation of the Peios kernel.

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

## Firmware verification

A firmware load is not an exec, so none of the above would see it —
and firmware is code that runs on a device with DMA into host memory,
which makes a tampered blob a complete compromise. KACS therefore
implements the `kernel_read_file` and `kernel_post_read_file` LSM
hooks for `READING_FIRMWARE` (`security/pkm/kacs/firmware.c`).

The signature is the ordinary PIP blob, found by the lookup above.
Firmware is never ELF, so in practice it is the `security.peios.sig`
xattr, which `peipkg` stamps at install from the `<file>.peios.sig`
sidecar the package carries ([PSPU payload entries](https://learn.peios.org/specifications/pspu/package-format-and-repository-protocol/payload-entries)). The bar is the **PeiosTcb**
tier — the same floor a usermodehelper exec must clear, since both are
the kernel choosing to run code it did not ship. A verified signature
at any other tier counts as no signature. <a id="cite-sig.firmware.peiostcb-floor"></a>

For a whole-file read, which is the common case, the post-read hook is
handed the exact bytes the loader will decompress and give to the
device, and those are what is hashed — no second read, no TOCTOU. <a id="cite-sig.firmware.post-read-hashes-loaded-bytes"></a> A
partial read (a driver pulling a window out of a large blob) only
passes through the pre-read hook, where nothing has been read yet, so
that path verifies the file through the reader probe instead. <a id="cite-sig.firmware.partial-read-uses-probe"></a> The
hash covers the compressed bytes as they sit on disk, so verification
precedes decompression. <a id="cite-sig.firmware.hashes-compressed-bytes"></a>

Policy is `CONFIG_SECURITY_PKM_FIRMWARE_SIG_ENFORCE`, overridable for
one boot with `kacs_fwsig=enforce` or `kacs_fwsig=log` on the kernel
command line; there is no runtime switch. <a id="cite-sig.firmware.cmdline-override"></a> Under `enforce` an unsigned,
tampered or under-tier file is refused with `-EPERM`; the loader logs
that against the path it was refused at, moves on to its remaining
search paths, and reports the driver an ordinary load failure. <a id="cite-sig.firmware.enforce-eperm"></a> Under `log` the
verdict goes to a rate-limited warning and the `kacs:kacs_firmware_load`
tracepoint and the load proceeds. <a id="cite-sig.firmware.log-mode"></a> **2026.8 ships in log mode**: the
firmware set is being signed for the first time, and a blob the
packaging missed has to show up as a warning rather than as a device
that silently stops probing. <a id="cite-sig.firmware.default-is-log"></a> Enforcement becomes the default once a
release has run clean.

`CONFIG_FW_UPLOAD` — a device's own sysfs update interface — is not
covered; it is `select`ed by several drivers and cannot be turned off,
and the drivers that expose it are the place to gate it if that ever
matters. The `test.fwsig` build stage exercises both modes through
`CONFIG_TEST_FIRMWARE`'s `trigger_request`, which pulls a named file
through the real loader path with no hardware.

---

# Process integrity protection

_Peios Kernel / Internals / KACS / Executable trust_

> PIP protects objects through trust label ACEs and processes through a dominance test — where it is enforced, and the limits of what it can do.

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

PIP protects **objects** from insufficiently trusted processes through
trust label ACEs evaluated inside AccessCheck ([PIP in AccessCheck](</kernel/internals/kacs/access-check/pip-in-accesscheck.md#trm-3-8-7>)). It also
protects **processes** — their memory, their execution, their metadata
— from other processes, which is what this section covers.

Every process-to-process operation passes two independent checks, and
both have to succeed. <a id="cite-pip.two-checks-both-required"></a>

The **process descriptor check** is an ordinary AccessCheck of the
caller's token against the target's process descriptor ([Process Security Descriptors](</kernel/internals/kacs/process-security/process-security-descriptors.md#trm-3-3-3>)). It
answers *who* may operate on the process, and it is where per-operation
granularity lives — different rights for signals, memory, and
metadata.

The **PIP dominance check** is a direct comparison of the two
processes' PSB fields. It answers *what trust level is required*. It
does not use AccessCheck, does not read a descriptor, and does not
involve the DACL pipeline at all: it is a standalone arithmetic test. <a id="cite-pip.dominance-independent-of-descriptor"></a>

The two are complementary. Object PIP protection stops a non-dominant
process opening authd's private key file; process PIP protection stops
the same process reading the key straight out of authd's memory with
ptrace, or killing authd with a signal.

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

## The dominance test <a id="cite-pip.dominance-both-axes"></a>

```
pip_dominates(caller_psb, target_psb) -> bool:
    if target_psb.pip_type == None:
        return true   // Unprotected target — any caller dominates.
    return caller_psb.pip_type  >= target_psb.pip_type
       AND caller_psb.pip_trust >= target_psb.pip_trust
```

Both axes are plain unsigned integers compared numerically, not closed
enumerations — the dominance layer would happily order tiers the
signing layer cannot currently produce ([PSB Fields](</kernel/internals/kacs/process-security/psb-fields.md#trm-3-3-2>)). The early return for
an unprotected target is what keeps ordinary processes universally
accessible whatever trust values a caller happens to carry. <a id="cite-pip.unprotected-target-always-dominated"></a>

Dominance is binary. A caller that does not dominate has no process
access at all, whichever operation was attempted; the descriptor
provides the granularity and PIP is the all-or-nothing gate above it. <a id="cite-pip.dominance-is-all-or-nothing"></a>

That asymmetry with the object model is deliberate. Object access has
natural categories — read, write, execute. Process access does not: a
caller that can ptrace a process can read its memory, inject code, and
effectively become it. Partial process access is not a meaningful
boundary.

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

## SeDebugPrivilege <a id="cite-pip.sedebug-bypasses-descriptor-only"></a>

`SeDebugPrivilege` bypasses the descriptor check and never the
dominance check. This holds at every enforcement point, and it is
enforced structurally in two independent places: inside the descriptor
evaluation a PIP-label denial short-circuits *before* the debug
rescue is reached, and the standalone dominance test runs afterwards
with no privilege escape of any kind.

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

## Where dominance is enforced

**ptrace**, in every mode. A single successful attach is equivalent to
full compromise of the target — read and write memory and registers,
single-step, inject signals, redirect execution — so a non-dominant
caller is refused whatever the mode. <a id="cite-pip.ptrace.all-modes"></a> The Linux `__ptrace_may_access`
path is patched to return the LSM's answer directly, so native UID and
capability rules no longer grant where KACS denies. <a id="cite-pip.ptrace.lsm-answer-final"></a> Direct memory
access through `/proc/<pid>/mem`, `process_vm_readv` and
`process_vm_writev` routes through the same check, so one hook covers
every memory-access vector. <a id="cite-pip.ptrace.covers-memory-vectors"></a> This is what makes in-memory secrets
genuinely unreachable: a compromised administrator cannot read an
HSM daemon's key material out of its address space.

`PTRACE_TRACEME` inverts the roles — the nominated tracer is the
subject and the caller is the target — and requires `PROCESS_VM_WRITE`
on the caller's own descriptor plus dominance by the nominated tracer. <a id="cite-pip.ptrace.traceme-inverted"></a>

Mode combinations are validated: the mutually exclusive
`PIDFD_OPEN`, `GETFD` and `PROC_QUERY` flags cannot be combined, and a
request that is neither a read nor an attach, or claims to be both, is
rejected as malformed. <a id="cite-pip.ptrace.mode-combinations-rejected"></a>

**Signal delivery**, uniformly regardless of signal type. <a id="cite-pip.signal.uniform-all-types"></a> Lifecycle
management of PIP-protected processes therefore has to go through a
process that dominates them — in practice peinit, which runs at the
highest tier.

Signalling within the same process security state is not a boundary
operation, and the exemption is **structural**: it is a pointer
comparison of the two processes' security state, tested before any
descriptor or dominance evaluation. <a id="cite-pip.signal.same-security-state-exempt"></a> It does not depend on the default
descriptor's self ACE, which is what makes `raise()`, `abort()` and
`pthread_kill()` work for restricted and confined tokens whose
AccessCheck against their own descriptor would fail. <a id="cite-pip.signal.self-signals-work-for-restricted"></a>

Multi-target sends are evaluated per target by Linux's own iteration,
so the signal reaches the permitted subset and the call succeeds if at
least one delivery happened. <a id="cite-pip.signal.multi-target-partial-success"></a> POSIX's same-session `SIGCONT` exception
is deliberately absent — the patched `check_kill_permission` returns
the KACS answer before reaching the switch that carried it — so
`SIGCONT` needs `PROCESS_SUSPEND_RESUME` plus dominance like every
other job-control signal, whatever the session. <a id="cite-pip.signal.sigcont-no-session-exception"></a>

Kernel-originated signals bypass the whole check, as described in
[Process Security Descriptors](</kernel/internals/kacs/process-security/process-security-descriptors.md#trm-3-3-3>).

**`pidfd_open()`**, a boundary information query rather than a memory
or attach operation, needs `PROCESS_QUERY_LIMITED` plus dominance. <a id="cite-pip.pidfd-open.query-limited"></a>
**`pidfd_getfd()`** maps to `PROCESS_DUP_HANDLE` plus dominance —
extracting a descriptor from another process is a boundary crossing in
its own right. <a id="cite-pip.pidfd-getfd.dup-handle"></a>

**`/proc` metadata.** Entries that are already ptrace-gated or
memory-open-gated are covered automatically by the ptrace hook. The
rest would leak information about a protected process, so the
non-ptrace-gated entries carry their own descriptor requirement plus
dominance; [Process Security Descriptors](</kernel/internals/kacs/process-security/process-security-descriptors.md#trm-3-3-3>) gives the mapping. <a id="cite-pip.proc.metadata-needs-descriptor-and-dominance"></a> The one exception is
`/proc/<pid>/psb`, which needs `PROCESS_QUERY_LIMITED` and no
dominance: a protected process's PIP type, trust and mitigations are
readable to whoever its descriptor lets query it ([PSB Fields](</kernel/internals/kacs/process-security/psb-fields.md#trm-3-3-2>)). <a id="cite-pip.proc.psb-exempt-from-dominance"></a> Entries stricter than a metadata
query, such as `/proc/<pid>/stack`, keep their native hardening and
are not brought under the metadata rule. <a id="cite-pip.proc.stricter-entries-keep-native"></a>

Denying access prevents reading inside `/proc/<pid>/` but does not
hide the PID: the directory name is still visible through `getdents`. <a id="cite-pip.proc.pid-visible-not-hidden"></a>
Visible-but-inaccessible is the accepted position.

`/proc` is not FACS-managed — it is a virtual filesystem with no
backing store and no xattrs — so enforcement there happens through
direct kernel checks rather than an object-backed FACS path.

**Capability metadata.** `capget()` on the current process, or on a
thread sharing its security state, is not a boundary operation. <a id="cite-pip.capget.self-and-sibling-exempt"></a>
Against another process it is a detailed information query needing
`PROCESS_QUERY_INFORMATION` plus dominance. <a id="cite-pip.capget.cross-process-query-information"></a>

**Resource limits, scheduler and placement.** Read-only `prlimit`
needs `PROCESS_QUERY_INFORMATION` plus dominance; a limit change needs
`PROCESS_SET_INFORMATION` plus dominance. <a id="cite-pip.prlimit.read-and-change"></a>

- `setpgid()` needs `PROCESS_SET_INFORMATION`; <a id="cite-pip.setpgid.set-information"></a>
- `getpgid()` and `getsid()` need `PROCESS_QUERY_LIMITED`; <a id="cite-pip.getpgid-getsid.query-limited"></a>
- the scheduler, affinity and I/O priority queries need
  `PROCESS_QUERY_INFORMATION`; <a id="cite-pip.sched-queries.query-information"></a>
- and the memory-placement mutations Linux routes through
  `task_movememory` need `PROCESS_SET_INFORMATION`. <a id="cite-pip.movememory.set-information"></a>

Setting nice, scheduler parameters and I/O priority all need
`PROCESS_SET_INFORMATION` too. <a id="cite-pip.sched-set.set-information"></a> Self-directed
versions of all of these are not boundary operations and skip both
checks. <a id="cite-pip.self-directed-skips-checks"></a>

**CPU affinity** is per-thread, so changing the caller's own thread or
a sibling in the same process is not a boundary operation. <a id="cite-pip.affinity.same-process-not-boundary"></a> Changing a
thread in a *different* process needs `PROCESS_SET_INFORMATION` plus
dominance plus `SeIncreaseBasePriorityPrivilege` — and the privilege
is checked and marked used *before* the descriptor and dominance call,
so the `SeDebugPrivilege` rescue cannot substitute for it. <a id="cite-pip.affinity.cross-process-privilege-first"></a> KACS does
not relax the kernel's native affinity validity rules: an invalid or
disallowed mask still fails. <a id="cite-pip.affinity.native-validity-preserved"></a>

**Token opens.** `kacs_open_process_token` and
`kacs_open_thread_token` need `PROCESS_QUERY_INFORMATION` plus
dominance. <a id="cite-pip.token-open.query-information"></a> Reading a process's security identity is as sensitive as
reading its memory.

**Performance monitoring.** Target-specific `perf_event_open()` on
another process can leak execution timing, branch prediction
behaviour, cache access patterns and instruction traces — side
channels that reveal cryptographic keys. It needs
`SeProfileSingleProcessPrivilege` plus `PROCESS_QUERY_INFORMATION`
plus dominance, with the privilege again checked first so the debug
rescue cannot stand in for it. <a id="cite-pip.perf.target-specific-requirements"></a> Own-task profiling is not a boundary
operation and needs no privilege. <a id="cite-pip.perf.own-task-exempt"></a> System-wide profiling, `pid == -1`,
samples every task on a CPU including protected ones, so it needs the
operator-class `SeSystemProfilePrivilege`. <a id="cite-pip.perf.system-wide-privilege"></a> Cgroup perf mode stays
under Linux's native model. <a id="cite-pip.perf.cgroup-native"></a> Because the target task is resolved after
the stock `security_perf_event_open` hook fires, this rule is enforced
through a target-resolved syscall patch rather than that hook — there
is no `security_perf_event_open` registration at all.

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

## The PeiosTcb floor on kernel-initiated execs

One place PIP gates execution rather than merely labelling it. It is
not a dominance test — there is no caller to compare against — but a
threshold: a binary the kernel execs *on its own behalf* must carry at
least PeiosTcb trust, or the exec fails with `EACCES`. <a id="cite-pip.umh.peiostcb-floor"></a>

The case that motivates it is `request_module()`. When the kernel needs
a module it does not have — `get_fs_type()` on a mount, `socket()` for
an unknown protocol family, the crypto API resolving a name — it spawns
`CONFIG_MODPROBE_PATH` as a usermode helper and runs it at the kernel's
own authority. That path is a writable sysctl, which makes redirecting
`/proc/sys/kernel/modprobe` a classic escalation: point it somewhere
attacker-controlled and the next module request executes it with the
kernel behind it. The floor makes the redirection worthless on its own,
because the attacker would also have to produce a TCB-signed binary.

This is the only exec KACS refuses on integrity grounds. Everywhere
else an unsigned binary runs and simply carries no tier, because a
requesting process's own authority bounds what it can do. A
kernel-initiated exec has no such process behind it, so there is no
lesser authority to fall back to.

The floor also refuses when no tier could be derived at all, not only
when one was derived and graded too low. <a id="cite-pip.umh.refuses-underivable-tier"></a> Treating "could not establish
trust" differently from "is not trusted" would leave the check
bypassable by whatever prevented the derivation from running.

Nothing upstream identifies such an exec by the time the LSM sees it.
The helper child is created by `user_mode_thread()`, so it never
carries `PF_KTHREAD` — `kernel_execve()` rejects kernel threads
outright — and `security_kernel_module_request()` fires in the
*requesting* task, before the child exists. So `kernel/umh.c` is
patched to mark the child after `commit_creds()` and before
`kernel_execve()`, and the mark is read in the `bprm_creds_from_file`
hook. It lives in the KACS task blob rather than costing a
`task_struct` flag.

The mark is never cleared. A helper that re-execs — an interpreter for
a `#!` helper — stays under the floor rather than escaping it on the
second exec; the task exists only to be that helper. <a id="cite-pip.umh.mark-never-cleared"></a>

A refusal emits `kacs_exec` with reason `umh-not-tcb`, so it is
visible rather than presenting as an unexplained module-load failure. <a id="cite-pip.umh.audit-reason"></a>

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

## Trust raising under a tracer or supervisor

Dominance is tested when a tracer attaches and when a seccomp filter is
installed, and not again. <a id="cite-pip.unsafe.dominance-tested-at-attach-only"></a> That leaves one way to end up controlling a
process one does not dominate: be attached to it, or supervising its
syscalls through seccomp user notification, when it execs a binary
whose signature would raise its label. Linux marks exactly these execs
— `LSM_UNSAFE_PTRACE` when the task is traced, `LSM_UNSAFE_NO_NEW_PRIVS`
under `no_new_privs`, which every unprivileged seccomp filter requires
— and uses them to withhold setuid gains. KACS applies the same rule to
the label: the exec goes ahead, but the staged label is **capped at
the process's current one** whenever the new label would not be
dominated by it. <a id="cite-pip.unsafe.label-capped"></a> The binary runs with the protection it can be given,
as a setuid binary runs without its setuid under `strace`.

There is no privilege exception. `SeDebugPrivilege` never bypasses
dominance, and a TCB tracer already dominates every label, so nothing
is lost by capping. An exec that does not raise the label — the common
case, and every unsigned binary — is untouched. <a id="cite-pip.unsafe.non-raising-exec-untouched"></a> A cap emits
`kacs_exec` with reason `pip-capped-unsafe` carrying the label that
was kept. <a id="cite-pip.unsafe.audit-reason"></a>

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

## Raw physical memory

A process able to read `/dev/mem` could map any process's physical
pages and bypass virtual memory protections entirely, PIP included.

The defence is `CONFIG_STRICT_DEVMEM`, which restricts `/dev/mem` to
I/O regions and denies RAM access. It is not merely a recommended
build option: the LSM **refuses to initialise** unless both
`CONFIG_STRICT_DEVMEM` and `CONFIG_MODULE_SIG_FORCE` are enabled, so a
kernel configured without them does not boot with KACS at all. <a id="cite-pip.devmem.required-configs"></a> The
same initialisation gate refuses to coexist with SELinux, AppArmor,
Smack, TOMOYO or the BPF LSM. <a id="cite-pip.init.refuses-other-lsms"></a>

Placing a restrictive descriptor on `/dev/mem` and `/dev/kmem` as a
secondary defence is not implemented; nothing in the kernel handles
those paths specially. <a id="cite-pip.devmem.no-descriptor-protection"></a>

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

## Limits of the guarantee

PIP operates inside the kernel's trust boundary, and three things sit
outside it.

**Kernel compromise.** A loaded module runs with unrestricted access
to all memory and kernel structures. PIP is enforced by the kernel, so
a compromised kernel voids it, and `SeLoadDriverPrivilege` is the
ceiling of every guarantee here. `CONFIG_MODULE_SIG_FORCE` is
hard-required as noted above, and module signing is itself ML-DSA-65.
Stripping `SeLoadDriverPrivilege` from every token but peinit's and the
device manager's is the other half of that defence, and is policy
rather than kernel behaviour — nothing in the kernel strips it. The
device manager holds it because loading drivers for the hardware that
appears is its job; module signature enforcement is what keeps the
privilege from meaning more than "load a module Peios built".

**Hardware access.** DMA-capable devices read and write physical
memory directly, bypassing the CPU's virtual memory system. An IOMMU
mitigates this, and configuring one is a kernel responsibility outside
KACS.

**Hypervisor-level isolation.** PIP does not offer guarantees
equivalent to hypervisor-based memory isolation. The threat model
ceiling is a non-compromised kernel.

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

## Impersonation

PIP reads the PSB, never the effective token. A Protected service
impersonating a client still evaluates its own PSB for every process
boundary check, so the client's identity has no bearing on it. <a id="cite-pip.impersonation.reads-psb-not-token"></a> In the
other direction, an unprotected process impersonating a token created
for a protected one gains nothing — its PSB is still None. Since
nothing constrains the PIP dimensions the way the integrity ceiling
constrains impersonation ([Impersonation Lifecycle](</kernel/internals/kacs/impersonation/state-transitions.md#trm-3-5-3>)), the PSB is the only safe source.

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

## Coredumps

A crashing PIP-protected process is a potential secret leak, so its
dumps must not be readable by non-dominant processes.

The implemented strategy is to disable them: a process with a nonzero
`pip_type` has its dumpable flag cleared at exec, and
`prctl(PR_SET_DUMPABLE, 1)` is refused for as long as the process
remains protected. <a id="cite-pip.coredump.disabled-for-protected"></a> Requests that keep or make it non-dumpable are
allowed, and no alternative dumpable-setting path is left ungated. <a id="cite-pip.coredump.non-dumpable-requests-allowed"></a> If
a later exec assigns None/0, normal Linux exec-time dumpability rules
apply to the new image. <a id="cite-pip.coredump.unprotected-exec-restores-rules"></a>

The alternative — a signed, high-trust crash handler receiving dump
data from the kernel and writing it under a restrictive descriptor, so
that diagnostics survive without bypassing isolation — is not
implemented. <a id="cite-pip.coredump.no-crash-handler"></a> The two are not mutually exclusive; disabling dumps is
the minimum viable position.

---

# Access check

_Peios Kernel / Internals / KACS / Access check_

> Find the Peios kernel articles about access check.

Use these articles to understand access check in the Peios kernel.

- [AccessCheck Overview](</kernel/internals/kacs/access-check/accesscheck-overview.md>)
- [The DACL Walk](</kernel/internals/kacs/access-check/the-dacl-walk.md>)
- [Mandatory Integrity Control](</kernel/internals/kacs/access-check/mandatory-integrity-control.md>)
- [Restricted Tokens](</kernel/internals/kacs/access-check/restricted-tokens.md>)
- [Object ACEs and Property-Level Access](</kernel/internals/kacs/access-check/object-aces-and-property-level-access.md>)
- [Application Confinement](</kernel/internals/kacs/access-check/application-confinement.md>)
- [PIP in AccessCheck](</kernel/internals/kacs/access-check/pip-in-accesscheck.md>)
- [Central Access and Auditing Policy](</kernel/internals/kacs/access-check/central-access-and-auditing-policy.md>)
- [Auditing in AccessCheck](</kernel/internals/kacs/access-check/auditing-in-accesscheck.md>)
- [The Algorithm](</kernel/internals/kacs/access-check/the-algorithm.md>)

---

# AccessCheck Overview

_Peios Kernel / Internals / KACS / Access check_

> The function that connects tokens to descriptors — its two API variants, and the three state values a right can hold during evaluation.

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

AccessCheck is the function that connects tokens to security
descriptors. Given a token — who is asking — a descriptor — what the
rules are — and a desired access mask — what they want to do — it
returns a verdict: which of the requested rights are granted, and
whether the request as a whole succeeds.

It is a pipeline, evaluating several layers of policy in a fixed
order. Each layer can grant or constrain access and the layers
interact: integrity policy can block what the DACL would allow,
privileges can override what the DACL denied, and confinement can
revoke what privileges granted. The order is not incidental — it is
the specification.

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

## Two API variants

**AccessCheck** is the common case. It returns the granted access
mask, whether the request succeeded, a continuous audit mask derived
from SACL alarm ACEs, and a CAAP staging mismatch flag. <a id="cite-check.accesscheck.returns"></a> When an object
type list is supplied, success requires every listed node to pass and
the returned mask is the intersection across them. The staging
mismatch flag is set when the staged scalar result differs from the
effective scalar result, when any per-node staged grant differs from
the effective per-node grant, or when staged auditing differs from
effective auditing. <a id="cite-check.staging-flag.accesscheck"></a>

**AccessCheckResultList** is the per-property variant and requires an
object type list. <a id="cite-check.result-list.requires-tree"></a> It returns a separate verdict for each node, so a
denial on one property fails that property alone rather than the whole
request. <a id="cite-check.result-list.returns"></a> It returns the same continuous audit mask and staging
mismatch flag, with the flag set when the staged scalar result differs
from the effective one, when any node's staged granted mask differs
from that node's effective granted mask, or when staged auditing
differs from effective auditing — the scalar comparison is not
mode-branched. <a id="cite-check.staging-flag.result-list"></a> Directory services use it,
because one operation there may touch several properties with
independent access rules. Privilege-use auditing in this variant takes
the same per-node view: a privilege counts as successfully used if its
contributed bits survive on *any* node's final granted mask.

Both variants share one evaluation pipeline. Only the collection of
results differs.

## A supplied subject without a token

The separate `kacs_access_check_subject` query evaluates caller-supplied SID,
group and typed-claim facts without creating, adopting or impersonating a
token. It reuses the DACL, conditional and object-ACE evaluators. Omitted
facts stay unknown; known-empty collections and explicit claim absences
are distinct. No access fact is inherited from the caller. Explicit integrity,
trust, scoped-policy and privilege requirements return missing execution
context rather than acquiring the caller's authority.

Syscall 1028 accepts a versioned request buffer and writes a granted, denied
or missing-context result. Missing context carries no provisional grant.
The kernel copies and validates one bounded buffer; internal offsets replace
nested userspace pointers. The UAPI access header specifies layout and limits.
Malformed or excessive inputs fail the entire query without truncating facts.

Matching SACL audit ACEs require enabled `SeAuditPrivilege` on the actual
caller. `KACS_SUBJECT_NO_AUDIT` suppresses this query's records; it does not bypass mandatory
SACL labels. Audit-only missing facts matter only while auditing is active.
Records use `kacs.audit.subject.checked`: `subject` is the real caller and
`source.supplied-subject.sid` is a hypothetical assertion. An optional generic `AuditContext`
labels the guarded object without influencing policy. Detected audit
preparation or submission errors fail the query. Records are submitted before
result writeback, so a bad output pointer cannot silence requested auditing.

<a id="trm-3-8-1-2"></a>

## The three state values

Every access check tracks three masks.

**`decided`** records which bits have been resolved. It enforces
first-writer-wins within the DACL walk: once a bit is decided, no
later ACE in the same walk changes its outcome. Pipeline layers that
operate on top of the DACL result — restricted token intersection,
confinement intersection, PIP revocation, CAAP intersection — may
still revoke granted bits. Those layers narrow the result; they do not
re-open decided bits for re-evaluation through the DACL. <a id="cite-check.state.narrow-not-reopen"></a>

**`granted`** records which bits resolved to yes. During the walk it
is a subset of `decided`. Afterwards the later layers may remove bits
from it, and the final value is what the caller receives.

**`privilege_granted`** records which bits in `granted` came from a
privilege rather than from the DACL. It exists for two reasons: audit
accuracy, so that privilege-granted access is distinguishable from
DACL-granted access, and the restricted token merge, where
privilege-granted bits are restored after the intersection so that
privileges bypass the restricted pass. PIP may revoke
privilege-granted bits.

With an object type list present, each node carries its own `decided`
and `granted` pair.

---

# The DACL Walk

_Peios Kernel / Internals / KACS / Access check_

> Walking the ACEs in order under first-writer-wins — SID matching, absent and empty DACLs, owner implicit rights and MAXIMUM_ALLOWED.

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

The DACL is an ordered list of ACEs, walked from first to last,
comparing each ACE's SID against the calling token's identity. The
governing principle is **first-writer-wins**: once a bit has been
resolved, granted or denied, no later ACE changes the outcome for that
bit. <a id="cite-check.dacl.first-writer-wins"></a>

An **allow** ACE whose SID matches the token grants the rights it
carries that have not yet been decided, leaving already-decided bits
untouched. <a id="cite-check.dacl.allow-grants-undecided"></a> A **deny** ACE whose SID matches denies its
not-yet-decided rights — marking them decided but not granted — and
likewise leaves decided bits alone. <a id="cite-check.dacl.deny-marks-decided"></a>

<a id="trm-3-8-2-1"></a>

## SID matching

An ACE's SID matches the token when it equals the user SID or a group
SID on the token, subject to attribute filtering.

For **allow** ACEs, only groups that are enabled and not deny-only
match. <a id="cite-check.dacl.allow-enabled-groups-only"></a> For **deny** ACEs, both enabled groups and deny-only groups
match: a deny-only group always participates in deny matching whatever
its enabled state. <a id="cite-check.dacl.deny-matches-deny-only"></a> A group with neither `SE_GROUP_ENABLED` nor
`SE_GROUP_USE_FOR_DENY_ONLY` participates in no matching at all. <a id="cite-check.dacl.inert-group"></a>

The user SID follows the same rule — when `user_deny_only` is set on
the token, it matches deny ACEs and not allow ACEs. <a id="cite-check.dacl.user-deny-only"></a>

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

## Skipping and mapping

ACEs carrying `INHERIT_ONLY` exist purely to propagate to child
objects and are skipped by the walk. <a id="cite-check.dacl.inherit-only-skipped"></a>

At the top of the walk each ACE's access mask is mapped through
`MapGenericBits` using the same GenericMapping applied to the caller's
request. <a id="cite-check.dacl.ace-mask-mapped"></a> The mapping works on a local copy — the ACE itself is never
mutated. Mapping ACE masks at evaluation time is a deliberate
departure from MS-DTYP, and it is what makes `GENERIC_ALL` work in
central access policy recovery ACEs ([Central Access and Auditing Policy](</kernel/internals/kacs/access-check/central-access-and-auditing-policy.md#trm-3-8-8>)).

Descriptors that KACS stores on its own objects reach the walk already
mapped. Every path that writes an object's descriptor — creation,
inheritance, the token's default DACL, and setting a descriptor on an
existing object — maps generic rights in the ACEs that apply to the
object, through that object type's GenericMapping. An ACE that applies
to the object and is also inherited is split, as at creation, into a
mapped ACE for the object and an inherit-only copy that keeps its
generic rights for the children it will reach. Inherit-only ACEs keep
theirs. <a id="cite-check.dacl.stored-descriptors-mapped"></a> A descriptor therefore reads back the same however it was
applied. The walk's own mapping remains for descriptors that never pass
through those paths, such as ones a caller hands to AccessCheck.

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

## Absent and empty DACLs

If the descriptor has no DACL — `SE_DACL_PRESENT` unset — every valid
right not already decided by an earlier pipeline stage is granted. <a id="cite-check.dacl.absent-grants-valid-rights"></a> The
valid rights are bounded by `MapGenericBits(GENERIC_ALL, mapping)`
rather than by a raw `0xFFFFFFFF`. <a id="cite-check.dacl.absent-bounded-by-generic-all"></a>

If the DACL is present but holds zero ACEs, the walk grants nothing. <a id="cite-check.dacl.empty-grants-nothing"></a>
The only access an owner gets in that case comes from the implicit
rights mechanism below.

<a id="trm-3-8-2-4"></a>

## Owner implicit rights

By default the owner of an object receives `READ_CONTROL` and
`WRITE_DAC` whatever the DACL says. <a id="cite-check.dacl.owner-implicit-rights"></a> These are granted **before** the
walk begins, as the first action inside `EvaluateDACL`, and because
first-writer-wins governs the walk, no deny ACE encountered later can
override them. <a id="cite-check.dacl.owner-implicit-before-walk"></a>

`EvaluateDACL` takes a `skip_owner_implicit` parameter. The
confinement pass sets it, because confinement is an absolute
intersection with no owner bypass.

The grant is suppressed entirely if any non-inherit-only
access-control ACE in the DACL targets the `OWNER RIGHTS` SID
(`S-1-3-4`). <a id="cite-check.dacl.owner-rights-suppresses-implicit"></a> This is a pre-scan performed at the start of
`EvaluateDACL`, before the main loop, and it checks only for the SID's
presence — it does not evaluate any conditional expression on the ACE. <a id="cite-check.dacl.owner-rights-prescan-presence-only"></a>

During the walk proper, `S-1-3-4` is treated as an ordinary SID
matching the owner, at both allow and deny polarity. <a id="cite-check.dacl.owner-rights-ordinary-sid"></a> It obeys the same
rules as any other SID: an allow ACE matches only through an enabled,
non-deny-only group, and not through the user SID of a
`user_deny_only` token; a deny ACE matches through a group that is
enabled or deny-only, and through the user SID unconditionally.

Note that the *implicit* grant above is a separate rule and remains
presence-based. It is bounded by the pre-scan rather than by polarity.

The implicit grant is also bounded twice over: by the object type's
valid rights, and by what has already been decided. A pre-decision
from MIC, PIP or a privilege therefore suppresses it — a non-dominant
owner does not receive `WRITE_DAC` through this route. <a id="cite-check.dacl.owner-implicit-bounded-by-decided"></a>

<a id="trm-3-8-2-5"></a>

## MAXIMUM_ALLOWED

When the caller includes `MAXIMUM_ALLOWED` (bit 25), AccessCheck runs
the full pipeline and returns the complete set of rights that would be
granted. The bit is stripped from the desired mask before evaluation
begins. <a id="cite-check.dacl.max-allowed-stripped"></a>

Two things change. The walk runs to completion with no short-circuit,
and the returned mask is whatever the pipeline accumulated rather than
being filtered to the requested bits. <a id="cite-check.dacl.max-allowed-returns-accumulated"></a>

`MAXIMUM_ALLOWED` can be combined with specific rights:
`MAXIMUM_ALLOWED | READ_CONTROL` asks both "can I read the
descriptor?" as a success or failure and "what else could I get?" as a
mask. A pure `MAXIMUM_ALLOWED` request carrying no specific bits
always succeeds. <a id="cite-check.dacl.max-allowed-alone-succeeds"></a>

Otherwise — when the desired mask is fully decided — the walk may stop
early.

First-writer-wins applies to `MAXIMUM_ALLOWED` requests exactly as it
does to targeted ones. <a id="cite-check.dacl.max-allowed-first-writer-wins"></a> MS-DTYP treats the two differently; KACS does
not, which is what stops "what can I do?" and "can I do this?"
disagreeing on a DACL that is not in canonical order.

---

# Mandatory Integrity Control

_Peios Kernel / Internals / KACS / Access check_

> MIC restricts what the DACL is allowed to grant along a vertical trust hierarchy — the labels, the policy bits, and the algorithm.

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

MIC is a mandatory constraint that restricts which rights the DACL is
allowed to grant, along a vertical trust hierarchy. It is evaluated
**before** the DACL walk, in the pre-SACL phase. <a id="cite-check.mic.before-dacl"></a>

Every token carries an integrity level, and every object may carry a
mandatory label — a `SYSTEM_MANDATORY_LABEL_ACE` in its SACL. MIC
compares the two: a caller below the object's level is blocked from
whole categories of access whatever the DACL says.

The default is **no-write-up**. A lower-integrity process can read and
execute a higher-integrity object but cannot write to it, and the
object's label may additionally block reads or execution for callers
beneath it. <a id="cite-check.mic.default-no-write-up"></a>

An object with no mandatory label ACE in its SACL — or no SACL at all
— is treated as Medium integrity with no-write-up, so Low and
Untrusted processes cannot write to unlabelled objects. <a id="cite-check.mic.unlabelled-is-medium"></a>

A caller whose level is greater than or equal to the object's label
**dominates** it, and MIC pre-decides nothing: the DACL handles
authorization normally. <a id="cite-check.mic.dominant-no-effect"></a>

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

## What MIC does and does not touch

MIC constrains what the DACL can grant. It does not revoke what
privileges have already granted, because it mutates only `decided` and
never touches `granted` or `privilege_granted`. <a id="cite-check.mic.never-revokes-privileges"></a>

`ACCESS_SYSTEM_SECURITY` is outside its reach for a structural reason:
the bits MIC can decide are bounded by
`MapGenericBits(GENERIC_ALL, mapping)`, which does not include it. The
right is privilege-granted rather than DACL-granted, so MIC never
blocks it. <a id="cite-check.mic.access-system-security-untouched"></a> PIP is stricter and does revoke it for non-dominant callers
— explicitly ORing it into the set of bits it can take away — which is
the mechanism by which objects stay protected even from
administrators.

`SeRelabelPrivilege` has one specific interaction: it lets the DACL
grant `WRITE_OWNER` even when an integrity mismatch would otherwise
block it, so a privileged administrator can take ownership of a
higher-integrity object as the first step in modifying it. <a id="cite-check.mic.relabel-allows-write-owner"></a> The bit
granted this way is recorded under its own provenance and is
deliberately **not** part of `privilege_granted`, so it is not
restored after the restricted merge and is not preserved by the CAAP
error escape hatch. <a id="cite-check.mic.relabel-not-privilege-granted"></a>

Enforcement is gated on the token's `mandatory_policy`: with
`NO_WRITE_UP` set — the default — the rule applies, and with it clear
MIC is effectively disabled for that token. <a id="cite-check.mic.mandatory-policy-gate"></a> The field is fixed at
creation ([Token Structure](</kernel/internals/kacs/tokens/token-structure.md#trm-3-2-2>)), which is what makes MIC a boundary rather than a
suggestion.

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

## Labels

An object's SACL may carry more than one mandatory label ACE. Only the
first non-inherit-only one is used; inherit-only labels do not apply
to the object carrying them. <a id="cite-check.mic.first-non-inherit-only-label"></a>

The SID in a mandatory label ACE has the Mandatory Label authority
(`S-1-16`) and exactly one sub-authority, and that sub-authority value
*is* the integrity level, compared as an unsigned integer. <a id="cite-check.mic.label-sid-shape"></a> Any
`S-1-16-X` is therefore valid.

| SID | Level | Name |
|---|---:|---|
| `S-1-16-0` | 0 | Untrusted |
| `S-1-16-4096` | 4096 | Low |
| `S-1-16-8192` | 8192 | Medium |
| `S-1-16-12288` | 12288 | High |
| `S-1-16-16384` | 16384 | System |

Peios tooling and authd use these five, but intermediate values such
as `S-1-16-2048` or `S-1-16-8448` are valid and compared numerically,
which is what allows Windows-originated descriptors carrying
non-standard levels to be evaluated without translation. <a id="cite-check.mic.nonstandard-levels-accepted"></a>

A label ACE whose SID falls outside the `S-1-16` authority — wrong
identifier authority, or the wrong sub-authority count — is
malformed, and so is one that is not a plain single-SID ACE. Either
causes AccessCheck to reject the whole descriptor with an error rather
than ignore the label. <a id="cite-check.mic.malformed-label-rejects-descriptor"></a>

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

## Policy bits

| Bit | Value | Meaning |
|---|---|---|
| `SYSTEM_MANDATORY_LABEL_NO_READ_UP` | 0x00000001 | Non-dominant callers receive no read-mapped rights from the DACL. <a id="cite-check.mic.policy.no-read-up"></a> |
| `SYSTEM_MANDATORY_LABEL_NO_WRITE_UP` | 0x00000002 | Non-dominant callers receive no write-mapped rights from the DACL. <a id="cite-check.mic.policy.no-write-up"></a> |
| `SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP` | 0x00000004 | Non-dominant callers receive no execute-mapped rights from the DACL. <a id="cite-check.mic.policy.no-execute-up"></a> |

Unknown bits in a label mask are ignored. <a id="cite-check.mic.unknown-policy-bits-ignored"></a>

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

## The algorithm <a id="cite-check.mic.algorithm"></a>

```
EnforceMIC(ace, token, mapping, &decided):

    if not (token.mandatory_policy & NO_WRITE_UP):
        return

    token_dominates = (token.integrity_level >= ace.integrity_level)

    if token_dominates:
        return

    // Non-dominant: start with read + execute, strip per label policy.
    allowed = MapGenericBits(GENERIC_READ, mapping)
            | MapGenericBits(GENERIC_EXECUTE, mapping)

    if ace.mask & SYSTEM_MANDATORY_LABEL_NO_READ_UP:
        allowed &= ~MapGenericBits(GENERIC_READ, mapping)
    if ace.mask & SYSTEM_MANDATORY_LABEL_NO_WRITE_UP:
        allowed &= ~MapGenericBits(GENERIC_WRITE, mapping)
    if ace.mask & SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP:
        allowed &= ~MapGenericBits(GENERIC_EXECUTE, mapping)

    // READ_CONTROL and SYNCHRONIZE are always allowed regardless of the
    // object type's GenericMapping and the label's up-strip policy — a
    // non-dominant caller can always read the descriptor and synchronize
    // on the object. Applied after the strips because a file GENERIC_READ
    // mapping folds these bits in, so NO_READ_UP would otherwise take them.
    allowed |= READ_CONTROL | SYNCHRONIZE

    // SeRelabelPrivilege: let WRITE_OWNER through MIC.
    if token.privilege_enabled(SeRelabelPrivilege):
        allowed |= WRITE_OWNER

    all_bits = MapGenericBits(GENERIC_ALL, mapping)
    decided |= all_bits & ~allowed
```

---

# Restricted Tokens

_Peios Kernel / Internals / KACS / Access check_

> The second pass a restricted token forces — when it runs, how privileges bypass it, and how owner rights and virtual groups behave in it.

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

A restricted token carries a secondary SID list, the restricting SIDs.
The second pass runs whenever that list or the restricted device group
list is non-empty, and AccessCheck evaluates the DACL twice. <a id="cite-check.restricted.second-pass-trigger"></a>

The **normal pass** evaluates the DACL against the token's ordinary
identity — user SID and group SIDs — exactly as usual. The
**restricted pass** evaluates the same DACL again with SID matching
drawn only from the restricting SID list; the token's normal groups
are invisible to it. <a id="cite-check.restricted.only-restricting-sids-match"></a> Conditional membership operators — `Member_of`,
`Member_of_Any`, and their device variants — take the same restricted
view, seeing only the restricting SIDs plus any virtual groups
injected from that list. <a id="cite-check.restricted.conditional-membership-restricted"></a>

The restricting SID list is **presence-based**. A SID participates
whenever it appears in the list, and `SE_GROUP_ENABLED` and
`SE_GROUP_USE_FOR_DENY_ONLY` on those entries are ignored both for
restricted-pass SID matching and for restricted-pass non-device
conditional membership. <a id="cite-check.restricted.presence-based"></a> This matches Windows restricted-token
behaviour, where restricting SIDs are always enabled for access
checks.

Access is granted only for rights **both passes agree on** — the
intersection. <a id="cite-check.restricted.intersection"></a> The restricting list acts as a ceiling: the principal
can never receive more access than the restricting SIDs would
independently justify.

<a id="trm-3-8-4-1"></a>

## Write-restricted tokens <a id="cite-check.restricted.write-restricted"></a>

In the write-restricted variant the intersection applies only to
write-category bits, and read and execute access comes from the normal
pass alone. What counts as write is whatever the object type's
GenericMapping maps `GENERIC_WRITE` onto.

<a id="trm-3-8-4-2"></a>

## Privileges bypass the restricted pass <a id="cite-check.restricted.privileges-bypass"></a>

Rights granted by privileges are added back after the intersection.
Privileges are system-level grants from security policy rather than
from the object's DACL: token restriction reduces the identity-based
access surface, and privilege-based grants are orthogonal to it. The
bits restored are the post-PIP privilege-granted set together with the
take-ownership grant. <a id="cite-check.restricted.restored-set"></a>

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

## Owner rights and virtual groups in the restricted pass

The restricted pass evaluates owner implicit rights independently. If
the object's owner SID appears in the restricting SID list, the pass
grants `READ_CONTROL` and `WRITE_DAC`, subject to the same `OWNER
RIGHTS` suppression pre-scan as the normal pass; if the owner SID is
not a restricting SID, no implicit rights are granted. <a id="cite-check.restricted.owner-implicit"></a>

Two virtual groups are injected on the same basis. `S-1-3-4` (`OWNER
RIGHTS`) is injected when the object's owner SID is among the
restricting SIDs, and `S-1-5-10` (`PRINCIPAL_SELF`) when `self_sid`
is. <a id="cite-check.restricted.virtual-groups"></a> This keeps the restricted pass consistent in its handling of these
well-known SIDs rather than letting them leak the unrestricted
identity.

Restricted device groups, when the token has them, are swapped in for
the restricted pass so that `Device_Member_of` and its relatives
evaluate against the restricted set rather than the unrestricted
device groups. <a id="cite-check.restricted.device-groups-swapped"></a>

## Choosing a restriction

Removing privileges without supplying restricting SIDs reduces privilege
presence without adding a restricted-SID intersection. Supplying restricting
SIDs adds another identity-based ceiling; it does not remove existing
privileges by itself. Review both choices when launching reduced-authority
work.

Write restriction limits the intersection to mapped write rights, but its
required `user_deny_only` state also changes ordinary user-SID matching.
Do not describe it as an unconditional promise that all previous reads
remain available. The user SID can match denies rather than grants.

A capability SID in a restricting list is still an ordinary SID in this
mechanism. It is not the dedicated confinement pass, which has separate
semantics and does not allow privileges to bypass its ceiling. Test the
complete intended token and object policy rather than treating either
restriction as a universal sandbox recipe.

---

# Object ACEs and Property-Level Access

_Peios Kernel / Internals / KACS / Access check_

> Per-property access control through GUID-scoped ACEs — object type lists, propagation, PRINCIPAL_SELF, and per-node results.

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

An object ACE carries a GUID identifying the property or property set
its rule applies to, which is what enables per-property access control
on objects with internal structure — Active Directory objects, most
obviously. An object ACE with no GUID, meaning
`ACE_OBJECT_TYPE_PRESENT` is unset, behaves exactly like a basic ACE. <a id="cite-check.object-ace.no-guid-is-basic"></a>

<a id="trm-3-8-5-1"></a>

## Object type lists

To request property-level access the caller supplies an object type
list: a tree of GUIDs representing the properties being asked for.
Each node carries its own `decided` and `granted` pair and is resolved
independently. <a id="cite-check.object-ace.per-node-state"></a>

With no list supplied, object ACEs with GUIDs apply globally, as if
they were basic ACEs. <a id="cite-check.object-ace.no-list-applies-globally"></a> With a list supplied, every ACE that behaves
like a basic ACE — ordinary basic ACEs, and object ACEs without an
`ObjectType` GUID — applies to every node in the tree. <a id="cite-check.object-ace.basic-applies-to-all-nodes"></a> An object ACE
whose GUID does not appear anywhere in the supplied tree is silently
skipped. <a id="cite-check.object-ace.unmatched-guid-skipped"></a>

<a id="trm-3-8-5-2"></a>

## Propagation

Decisions move through the tree in four ways.

**Downward from grants.** A grant on a property set flows to every
attribute within it, each child node still applying first-writer-wins
for itself. <a id="cite-check.object-ace.grant-propagates-down"></a>

**Upward from grants.** When every attribute within a property set has
been granted the same right, that right propagates up to the set's
node. <a id="cite-check.object-ace.grant-propagates-up"></a> The propagation is a per-bit intersection, so a right reaches
the parent only if all siblings share it.

**Upward from denials.** A denial on an attribute propagates to every
ancestor regardless of what its siblings hold, and siblings are
themselves unaffected. <a id="cite-check.object-ace.denial-propagates-up"></a> Ancestors still apply first-writer-wins to the
propagated bits, so a denial cannot overturn something an ancestor had
already decided. <a id="cite-check.object-ace.denial-up-first-writer-wins"></a>

**Downward from denials.** A denial on a property set flows to every
attribute within it, again subject to first-writer-wins. <a id="cite-check.object-ace.denial-propagates-down"></a>

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

## PRINCIPAL_SELF

`PRINCIPAL_SELF` (`S-1-5-10`) is a placeholder for the object's
associated principal. An ACE targeting it matches the caller when the
caller's token represents the same principal as the object, which the
caller establishes by passing the object's principal SID as the
`self_sid` parameter. <a id="cite-check.object-ace.principal-self-matches-self-sid"></a> With a null `self_sid`, `PRINCIPAL_SELF` ACEs
match nothing. <a id="cite-check.object-ace.principal-self-null-matches-nothing"></a>

It follows the ordinary deny-only rules: if the caller's matching SID
is deny-only, `PRINCIPAL_SELF` matches deny ACEs but not allow ACEs. <a id="cite-check.object-ace.principal-self-deny-only"></a>

<a id="trm-3-8-5-4"></a>

## Scalar and per-node results

`AccessCheck` requires every node to pass, so a denial on any one
property fails the whole request. <a id="cite-check.object-ace.scalar-requires-all-nodes"></a> `AccessCheckResultList` returns a
separate verdict per node.

The scalar result `AccessCheck` returns is the root node's granted
mask. <a id="cite-check.object-ace.scalar-is-root-mask"></a> That is equivalent to the intersection across all nodes, but by
construction rather than by computation: upward denial propagation
forces every descendant's denial into all of its ancestors' `decided`
sets, which guarantees the root's granted mask is a subset of every
node's.

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

## Validation

Object type lists are validated strictly, at parse time.

- A supplied list is non-empty. <a id="cite-check.object-ace.list-non-empty"></a>
- Its first node is at level 0. <a id="cite-check.object-ace.list-first-node-level-zero"></a>
- There is exactly one level-0 node. <a id="cite-check.object-ace.list-one-root"></a>
- There are no level gaps, meaning no node at level N+2 following one
  at level N. <a id="cite-check.object-ace.list-no-level-gaps"></a>
- No GUID appears twice. <a id="cite-check.object-ace.list-no-duplicate-guid"></a>

These checks are stricter than MS-DTYP, which does not specify them.
They exist because a duplicate GUID makes node lookup return the wrong
node, and a level gap makes propagation undefined.

---

# Application Confinement

_Peios Kernel / Internals / KACS / Access check_

> An absolute boundary a confined token cannot cross whatever the DACL says — normal and strict confinement, and where it sits in the order.

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

Confinement restricts a token's effective access to what is explicitly
granted to its confinement identity. Even where the normal DACL walk
grants access through the user SID or a group SID, the confinement
pass intersects that with what the confinement SIDs would receive on
their own, and revokes anything they cannot independently justify. <a id="cite-check.confinement.intersects-confinement-identity"></a>

A confined token carries `confinement_sid`, its confinement identity;
`confinement_capabilities`, the capability SIDs the application
declares; and `confinement_exempt`, an escape hatch that skips
confinement evaluation entirely. <a id="cite-check.confinement.exempt-skips-evaluation"></a>

The confinement SID set is `confinement_sid` together with every SID
in `confinement_capabilities`. <a id="cite-check.confinement.sid-set"></a> Capabilities are **presence-based**
identities rather than ordinary ACE-matching groups: a capability SID
participates whenever it is present, and disabling an entry or marking
it deny-only does not remove it from the confinement identity. <a id="cite-check.confinement.capabilities-presence-based"></a>

The pass also injects two confinement-scoped virtual groups.
`S-1-5-10` (`PRINCIPAL_SELF`) is injected only when `self_sid` equals
the confinement SID or one of the capability SIDs, and `S-1-3-4`
(`OWNER RIGHTS`) only when the object's owner SID does. <a id="cite-check.confinement.virtual-groups"></a> Both apply to
ACE SID matching during the confinement walk *and* to the conditional
membership operators — `Member_of`, `Member_of_Any`, and their device
and negated variants — evaluated during that pass. <a id="cite-check.confinement.virtual-groups-in-conditionals"></a>

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

## An absolute boundary

Confinement is not overridable. Privileges do not bypass it: the
confinement merge takes no privilege-granted input at all, so backup,
restore, `SeTakeOwnershipPrivilege` and `SeSecurityPrivilege` are
alike unable to grant access the confinement check denies. <a id="cite-check.confinement.privileges-do-not-bypass"></a> Owner
implicit rights are skipped entirely, because the pass runs with
`skip_owner_implicit` set. <a id="cite-check.confinement.skips-owner-implicit"></a>

One thing does pass through: an object with a **null DACL** grants in
the confinement pass exactly as it does in the normal pass. <a id="cite-check.confinement.null-dacl-grants"></a> A null
DACL means "no discretionary restrictions", and the confinement pass
follows standard evaluation, granting all valid bits.

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

## Strict confinement

A normal confined token carries both `ALL_APPLICATION_PACKAGES` and
`ALL_RESTRICTED_APPLICATION_PACKAGES` among its capabilities. Omitting
`ALL_APPLICATION_PACKAGES` gives strict confinement: far fewer system
objects grant to `ALL_RESTRICTED_APPLICATION_PACKAGES`, so the access
surface is much narrower. <a id="cite-check.confinement.strict-omits-all-app-packages"></a>

Strict confinement is not a separate kernel mode bit. It is derived
purely from the SID set supplied at token creation — if
`ALL_APPLICATION_PACKAGES` is absent, AccessCheck simply evaluates the
remaining confinement SIDs. The kernel never synthesises it, and never
rejects an otherwise valid confined token for carrying it. <a id="cite-check.confinement.strict-never-rejected"></a> Deciding
which capabilities a package token receives belongs to authd and
policy tooling.

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

## Consequences worth stating

**SACL access is unreachable.** `ACCESS_SYSTEM_SECURITY` is only ever
privilege-granted, and privileges do not bypass confinement, so a
confined token cannot reach a SACL unless a confinement ACE grants the
right outright. <a id="cite-check.confinement.sacl-unreachable"></a>

**`OWNER RIGHTS` is confinement-scoped.** `S-1-3-4` matches in the
confinement pass only when the owner SID is part of the confinement
SID set.

**`PRINCIPAL_SELF` is isolated from user identity.** `S-1-5-10` is
injected only when `self_sid` matches a confinement SID — the package
SID or one of its capabilities — not when it matches the user.

**Conditional expressions still see the full token.** The confinement
pass isolates ordinary SID matching to the confinement identity, but
conditional expressions inside ACEs continue to evaluate against the
user's real groups and claims. <a id="cite-check.confinement.conditionals-see-full-token"></a> The two confinement-scoped virtual
groups are the only exception, and they follow the confinement rules
during conditional membership evaluation.

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

## Ordering

Confinement runs **after** the restricted token merge and after its
privilege restoration. <a id="cite-check.confinement.after-restricted-merge"></a> The order is load-bearing: privileges bypass
the restricted pass but must not bypass confinement, and if
confinement ran first the privilege restoration would resurrect bits
that confinement had already blocked.

---

# PIP in AccessCheck

_Peios Kernel / Internals / KACS / Access check_

> How a trust label ACE is evaluated — the label SID, the privileges it revokes, the algorithm, and where the compared values come from.

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

An object opts in to PIP protection by carrying a
`SYSTEM_PROCESS_TRUST_LABEL_ACE` in its SACL. <a id="cite-check.pip.opt-in-via-sacl-ace"></a> The ACE's SID encodes
the required type and trust, and its access mask names exactly the
rights a non-dominant caller may still have.

A caller that **dominates** — `pip_type` and `pip_trust` both greater
than or equal to the ACE's — is unrestricted by PIP. <a id="cite-check.pip.ace-dominance-test"></a> A caller that
does not dominate is limited to the ACE mask, and everything else is
denied. <a id="cite-check.pip.non-dominant-limited-to-ace-mask"></a>

Unlike MIC, PIP has **no default**. An object with no trust label is
unrestricted, reachable by any process whatever its PIP identity. <a id="cite-check.pip.no-default"></a>

<a id="trm-3-8-7-1"></a>

## The label SID

A trust label SID has the form `S-1-19-{type}-{trust}` — the Process
Trust authority, exactly two sub-authorities. <a id="cite-check.pip.label-sid-shape"></a> Both axes are compared
numerically. The conventional type values are 0 (None), 512
(Protected) and 1024 (Isolated), but they are labels rather than a
closed enum: any other numeric type is valid and compared by the same
dominance rule. <a id="cite-check.pip.nonstandard-type-accepted"></a>

A trust label SID of any other shape — wrong authority, wrong
sub-authority count — makes the descriptor malformed, and AccessCheck
rejects it outright rather than guessing. <a id="cite-check.pip.malformed-label-rejects-descriptor"></a>

Where a SACL carries more than one trust label ACE, only the first
non-inherit-only one is used; inherit-only labels do not apply to the
object carrying them. <a id="cite-check.pip.first-non-inherit-only-label"></a>

<a id="trm-3-8-7-2"></a>

## Privilege revocation

This is the critical difference from MIC. PIP does not merely
constrain what the DACL may grant — it **revokes rights privileges
already granted**. <a id="cite-check.pip.revokes-privilege-granted"></a> A non-dominant caller who used `SeBackupPrivilege`
to obtain read has those bits stripped; `SeTakeOwnershipPrivilege`'s
`WRITE_OWNER` is stripped; `SeSecurityPrivilege`'s
`ACCESS_SYSTEM_SECURITY` is stripped.

The last of those is the point. Without privilege revocation, a
non-dominant administrator holding `SeSecurityPrivilege` could read
the SACL of a PIP-protected object — and remove the trust label from
it. PIP would be self-defeating.

There is no escape hatch. PIP has no `SeRelabelPrivilege` equivalent,
and no privilege compensates for insufficient trust. It is an absolute
boundary, which is why the enforcement step explicitly ORs
`ACCESS_SYSTEM_SECURITY` into the set of bits it can take away —
that right is outside the generic mapping and would otherwise escape. <a id="cite-check.pip.revokes-access-system-security"></a>

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

## The algorithm <a id="cite-check.pip.algorithm"></a>

```
EnforcePIP(ace, pip_type, pip_trust, mapping, &decided,
           &granted, &privilege_granted):

    // pip_type and pip_trust are the subject's process-trust context,
    // not a token field. See "Where the values come from" below.

    ace_type  = ace.sid.pip_type
    ace_trust = ace.sid.pip_trust

    caller_dominates = (pip_type  >= ace_type
                    and pip_trust >= ace_trust)

    if caller_dominates:
        return

    // Non-dominant: the ACE mask IS the allowed set.
    allowed = MapGenericBits(ace.mask, mapping)

    // Everything not explicitly allowed is denied, including
    // ACCESS_SYSTEM_SECURITY.
    all_bits = MapGenericBits(GENERIC_ALL, mapping)
             | ACCESS_SYSTEM_SECURITY
    pip_denied = all_bits & ~allowed

    decided |= pip_denied

    // Revoke privilege-granted rights.
    granted           &= ~pip_denied
    privilege_granted &= ~pip_denied
```

<a id="trm-3-8-7-4"></a>

## Where the values come from

`pip_type` and `pip_trust` are the subject's process trust context and
are never derived from a token field — the token structure has no PIP
field at all. They are passed into AccessCheck as explicit parameters
by whichever layer is enforcing. <a id="cite-check.pip.values-are-parameters"></a>

During enforcement — FACS file access, process boundaries — the values
are the subject process's PSB, set at exec from the binary's signature
([Binary Signature Verification](</kernel/internals/kacs/executable-trust/signature-verification.md#trm-3-6>), [Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)). <a id="cite-check.pip.enforcement-uses-psb"></a>

The `kacs_access_check` query may instead supply them through its
arguments, per axis: zero means "use the calling process's PSB value"
and a nonzero value evaluates against the supplied context. <a id="cite-check.pip.query-supplies-values-per-axis"></a> This lets
a userspace broker evaluate access under a client's trust level, in
the same way the query's token argument lets it evaluate a token other
than its own. The query is advisory and gates nothing in the kernel;
enforcement always uses the PSB. The same effective values are used
for the verdict and for the event the check emits, so an audit record
never disagrees with the decision it describes. <a id="cite-check.pip.same-values-for-verdict-and-event"></a>

The enforcement step also computes a record of which bits PIP decided.
Nothing currently consumes it — it is threaded through three
structures and exported, and no caller reads it.

---

# Central Access and Auditing Policy

_Peios Kernel / Internals / KACS / Access check_

> Policy defined once and referenced by objects — the policy structure, access and audit evaluation, the cache, and the recovery policy.

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

CAAP separates policy definition from the objects it governs. A policy
is defined once, centrally; objects reference it by SID through a
`SYSTEM_SCOPED_POLICY_ID_ACE` in their SACL. <a id="cite-check.cap.reference-by-scoped-policy-ace"></a> When the policy changes,
every future AccessCheck against a referencing object uses the new
rules — already-open handles are unaffected, because the model is
check-at-open. <a id="cite-check.cap.check-at-open"></a>

It extends the Windows Central Access Policy model by adding an audit
component: each rule carries both an access restriction and an audit
requirement.

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

## Policy structure

A policy is a named collection of rules identified by a policy SID.
Each rule carries:

An optional **applies-to condition**, a conditional expression
determining whether the rule governs this decision. It may reference
the `@Resource`, `@User`, `@Device` and `@Local` claim namespaces, but
it cannot inspect SID or device-group membership: `Member_of`,
`Member_of_Any`, `Device_Member_of`, `Device_Member_of_Any` and their
negated forms all evaluate to UNKNOWN inside `applies_to`. <a id="cite-check.cap.applies-to-membership-unknown"></a> A rule with
no condition applies to every object referencing the policy. <a id="cite-check.cap.no-condition-applies-always"></a>

A mandatory **effective DACL** — a real DACL evaluated through the
full pipeline. An optional **effective SACL**, whose audit ACEs merge
with the object's own during the audit walk. And optional **staged**
DACL and SACL, proposed replacements used for testing.

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

## Access evaluation

The DACL result is ANDed with the normal evaluation. CAAP can only
restrict, never expand: if the object's DACL grants read and write but
the applicable rule's effective DACL grants only read, the result is
read. <a id="cite-check.cap.intersects-only"></a>

A SACL may carry several scoped policy ACEs, which makes policies
composable — and the AND semantics are what make composition safe,
since each additional policy can only narrow. <a id="cite-check.cap.multiple-scoped-policy-aces"></a> Inherit-only scoped
policy ACEs do not apply to the object carrying them and are ignored
during lookup. <a id="cite-check.cap.inherit-only-policy-ace-ignored"></a> MS-DTYP allows one scoped policy ACE per SACL; KACS
allows several.

For each scoped policy ACE, AccessCheck looks the policy up in the
kernel cache, then for every rule whose `applies_to` is TRUE or absent
evaluates the rule's effective DACL through the full pipeline —
privilege grants, MIC, PIP, the DACL walk, restricted tokens,
confinement — and intersects the result with the running total, which
starts at the normal evaluation's granted mask. <a id="cite-check.cap.rule-dacl-full-pipeline"></a>

A rule whose condition evaluates FALSE **or UNKNOWN** is skipped. <a id="cite-check.cap.unknown-condition-skips-rule"></a> That
is deliberately the opposite of the deny-ACE UNKNOWN rule: skipping is
the conservative choice here, because a rule's DACL can only narrow
what the normal DACL already granted.

If no rules apply — every condition false or unknown, or the policy
has no rules — CAAP has no effect and the normal result stands. <a id="cite-check.cap.no-applicable-rules-no-effect"></a>

The rule's DACL is evaluated with backup and restore intent **not**
passed: intent is a caller concern, not a policy concern. <a id="cite-check.cap.no-backup-restore-intent"></a> And CAAP
never recurses. A rule's synthetic descriptor has scoped policy ACEs
stripped before evaluation, so nested CAAP evaluation cannot occur
even when the original SACL carried more of them. <a id="cite-check.cap.no-recursion"></a> The synthetic
descriptor keeps the original owner and group, and preserves the MIC
and PIP labels, so a rule is evaluated against the same mandatory
constraints as the object itself. <a id="cite-check.cap.synthetic-preserves-labels"></a>

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

## Audit evaluation

For each applicable rule carrying an effective SACL, the rule's audit
ACEs are evaluated alongside the object's own during the audit walk.
They are treated identically — if either says to audit an operation,
it is audited. <a id="cite-check.cap.sacl-merged-with-object"></a>

The SACL component is purely additive. A CAAP SACL can add audit
coverage and can never suppress auditing the object's own SACL asks
for. <a id="cite-check.cap.sacl-additive-only"></a>

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

## The policy cache

The kernel keeps a map from policy SID to policy object, empty at
boot. Policies are pushed in through `kacs_set_caap`, which requires
`SeTcbPrivilege` — and marks it used. <a id="cite-check.cap.set-requires-tcb"></a> A non-null spec for an existing
SID replaces the policy; a null spec or zero length removes it. <a id="cite-check.cap.set-replaces-or-removes"></a>
Every call that passes the privilege gate writes a
`kacs.caap.policy.changed` record ([Audit Event Schemas](</kernel/internals/kacs/auditing/event-families-and-delivery.md#trm-3-c>)) naming the caller, the policy
SID as `caap.policy.sid`, and `operation.name` `set` or `remove`, with
`outcome.success` and, when the change did not apply, `outcome.errno`. <a id="cite-check.cap.set-recorded"></a> The
policy SID's length is bounded to 8–68 bytes before parsing begins,
and until the cache has been initialised both setting and evaluating
fail with `EACCES`. <a id="cite-check.cap.uninitialised-eacces"></a>

The wire format is:

```
[version:u8 = 0x01]
[rule_count:u32le]
per rule:
  [applies_to_len:u32le][applies_to_expr bytes]     (0 = no condition)
  [effective_dacl_len:u32le][effective_dacl bytes]  (MUST NOT be 0)
  [effective_sacl_len:u32le][effective_sacl bytes]  (0 = no audit rules)
  [staged_dacl_len:u32le][staged_dacl bytes]        (0 = no staged DACL)
  [staged_sacl_len:u32le][staged_sacl bytes]        (0 = no staged SACL)
```

All lengths are little-endian `u32`. ACLs use the standard binary
format, and every ACE type valid in a DACL or SACL is permitted inside
a policy ACL. <a id="cite-check.cap.any-ace-type-permitted"></a> The `applies_to` expression is conditional ACE bytecode,
carrying the same `artx` prefix as callback ACE application data. <a id="cite-check.cap.applies-to-artx-bytecode"></a>

The limits are a spec of at most 256 KB, at most 256 rules, an
`applies_to` of at most 64 KB, and an individual ACL of at most 64 KB. <a id="cite-check.cap.limits"></a>
The version byte has to be `0x01`. <a id="cite-check.cap.version-byte"></a> Trailing bytes after the declared
rules are rejected. <a id="cite-check.cap.trailing-bytes-rejected"></a>

Validation is strict and total. Malformed or truncated `applies_to`
bytecode fails the whole call with `EINVAL` at ingestion rather than
being admitted and later treated as a runtime UNKNOWN — the structural
check happens once, at the boundary. <a id="cite-check.cap.malformed-applies-to-einval"></a> A rule with a zero-length
effective DACL fails the same way, as do truncated fields, lengths
exceeding the buffer, and invalid ACL headers. <a id="cite-check.cap.zero-length-dacl-einval"></a> `SeTcbPrivilege` is
checked before any parsing begins. <a id="cite-check.cap.tcb-checked-before-parsing"></a>

The cache is a kernel mechanism. The maintained authd implementation does
not populate it from registry or directory policy. A deployment needs an
explicit privileged loader and distribution process; the existence of
`kacs_set_caap` does not establish that either is installed. Policies loaded
after services start do not retroactively affect already-open handles.

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

## The recovery policy

When a scoped policy ACE names a SID that is not in the cache — the loader
did not install it or the policy was removed — a hardcoded recovery policy
is used instead: `GENERIC_ALL`
to BUILTIN\Administrators, to SYSTEM, and to `OWNER RIGHTS`. <a id="cite-check.cap.recovery-policy"></a>

Those masks are stored as the literal `GENERIC_ALL` bit rather than
pre-mapped object-specific bits, and are expanded through the caller's
GenericMapping at evaluation time, so the recovery policy works
correctly for every object type. <a id="cite-check.cap.recovery-generic-all-mapped"></a>

Because CAAP is an intersection, recovery does not widen access beyond
the object's own DACL: it limits missing-policy access to callers who
also satisfy the recovery DACL. This is a fail-closed recovery mode
with administrator, SYSTEM and owner escape hatches — not a no-effect
fallback.

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

## Errors

A rule whose DACL evaluation errors denies everything except rights
granted by privileges — in the effective and the staged evaluation
alike, and in the scalar total exactly as on every node of a
result-list check. <a id="cite-check.cap.rule-error-denies-except-privileges"></a> Preserving those is the escape hatch: an
administrator with `SeSecurityPrivilege` keeps the ability to read and
modify the SACL and remove the offending scoped policy ACE.

The escape hatch is conditional, though, and the ordering is why. PIP
runs before CAAP and may already have stripped
`ACCESS_SYSTEM_SECURITY` from the privilege-granted set for a
non-dominant caller. The hatch therefore only works for callers who
are PIP-dominant, or where the object carries no trust label. <a id="cite-check.cap.error-hatch-requires-pip-dominance"></a>

Rule evaluation swallows every error kind, including allocation
failure, so an out-of-memory condition inside a rule is reported as
"this rule denied all except privileges" rather than as `ENOMEM`. <a id="cite-check.cap.rule-error-swallowed"></a>

A rule whose SACL evaluation errors has its audit contribution
skipped, and a diagnostic event is emitted. <a id="cite-check.cap.sacl-error-skipped-diagnostic"></a>

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

## Staging

A rule may carry staged DACLs and SACLs alongside its effective ones,
and AccessCheck evaluates both in parallel. The staged result affects
neither access nor audit; where effective and staged differ, the
difference is reported through a staging mismatch flag returned to the
caller and a diagnostic event. <a id="cite-check.cap.staged-no-effect-reports-mismatch"></a>

A rule with no staged DACL contributes its effective result to both
running totals, and a rule with no staged SACL contributes its
effective SACL to both. <a id="cite-check.cap.no-staged-uses-effective"></a>

## Planning a staged rollout

Staging supplies comparison data, not an automatic rollout service. The
following procedure requires a deployment-specific loader and observation
path; authd does not provide that workflow.

1. Preserve the effective policy and its object references. Author proposed
   staged DACL/SACL fields without replacing the effective ones.
2. Load and verify the policy on each intended machine through the privileged
   kernel interface. Distribution and object-side scoped-policy ACEs are
   separate responsibilities.
3. Exercise representative access paths and collect mismatch evidence with
   subject, object, requested rights, and effective result. Check auditing
   and observation limits before treating silence as agreement.
4. Review unexpected differences. A mismatch is neither a denial caused by
   the staged policy nor a complete list of which ACEs differ.
5. When the change is approved, replace the effective fields and verify fresh
   opens. Remove or replace staging fields deliberately. Retain the prior
   effective policy for an explicit restoration if necessary.

Staging does not version policy or revoke existing handles. The cache starts
empty at boot; a restart requires loading the intended policy again. Removing
a cached policy while objects still reference its SID activates recovery
policy rather than removing all restriction. Recovery remains an intersection
with the preceding grant, not guaranteed administrator access to everything.
The actual recovery DACL, including Owner Rights matching, is evaluated by
the pipeline; it must not be inferred from a simplified audience label.

---

# Auditing in AccessCheck

_Peios Kernel / Internals / KACS / Access check_

> Auditing is purely observational and never changes a decision — access, continuous and privilege-use auditing, and per-token policy.

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

Auditing is purely observational. No audit rule affects the access
decision, and audit ACEs are evaluated after the decision is final. <a id="cite-check.auditing.observational"></a>

Three mechanisms operate inside the pipeline, emitting two families of
KMES record: `kacs.audit.access.checked` for object-access events from the SACL
walk and from token audit-policy forcing, and `kacs.audit.privilege.used` for
privilege-use events. <a id="cite-check.auditing.event-families"></a> A third family is
emitted for the CAAP conditions of [Central Access and Auditing Policy](</kernel/internals/kacs/access-check/central-access-and-auditing-policy.md#trm-3-8-8>): `kacs.caap.sacl.skipped` for
a rule SACL that would not parse or evaluate, and
`kacs.caap.staging.diverged` for a staged-versus-effective mismatch. <a id="cite-check.auditing.caap-diagnostic-family"></a> The event type strings and
payload schemas are in [Audit Event Schemas](</kernel/internals/kacs/auditing/event-families-and-delivery.md#trm-3-c>).

Event delivery happens before any result is written back to the
caller, and a failure to deliver fails the call. <a id="cite-check.auditing.delivery-before-result"></a> An audit event cannot
be suppressed by handing the syscall a bad output pointer.

<a id="trm-3-8-9-1"></a>

## Access auditing

`SYSTEM_AUDIT` ACEs in the SACL define which attempts to log. Each
carries a SID, an access mask, and success and failure flags —
`SUCCESSFUL_ACCESS_ACE_FLAG` (0x40) and `FAILED_ACCESS_ACE_FLAG`
(0x80).

An event is emitted when the ACE's SID matches the caller, its mask
overlaps the requested access, and its flags match the outcome. <a id="cite-check.auditing.audit-ace-conditions"></a>

<a id="trm-3-8-9-1-1"></a>

### On the AccessCheck syscall

Through `kacs_access_check` and `kacs_access_check_list` the descriptor
is the caller's own, SACL included. So that no process can write
kernel-origin audit records at will by supplying a SACL that matches
itself, the records a SACL generates there are written only when the
calling process's effective token holds `SeAuditPrivilege`, enabled.
Without it the check runs and answers exactly as it would otherwise,
and its SACL records are withheld; the privilege is marked used when it
admits them. <a id="cite-check.auditing.syscall-sacl-needs-audit-privilege"></a> The
privilege is the caller's, not the subject's: a daemon checking a
client through `token_fd` needs it on its own token. This is Windows'
rule for `AccessCheckAndAuditAlarm`.

The records the checked token's own audit policy forces, and
privilege-use and CAAP records, are not gated: the policy belongs to
the token, not to the caller. <a id="cite-check.auditing.syscall-policy-records-ungated"></a>

Two details matter. The SID is matched with **deny polarity** — the
broadest identity view, in which deny-only groups are visible —
because auditing should capture the widest possible picture rather
than the narrowest. <a id="cite-check.auditing.deny-polarity-matching"></a> And the overlap is tested against the
generic-mapped **requested** mask, not the final granted mask, so a
failed request is still auditable for the rights it actually asked
for. <a id="cite-check.auditing.overlap-against-requested"></a>

Conditional audit ACEs gate the event on an expression, using the same
deny-side membership polarity. An expression evaluating to UNKNOWN
emits the event: when in doubt, audit. <a id="cite-check.auditing.unknown-condition-emits"></a>

<a id="trm-3-8-9-2"></a>

## Continuous auditing

Access auditing fires once, where AccessCheck runs. Continuous
auditing covers per-operation monitoring.

`SYSTEM_ALARM` ACEs configure it. When AccessCheck evaluates an alarm
ACE whose SID matches, the ACE's mask is accumulated into a
**continuous audit mask** returned to the caller, which stores it on
the open handle and enforces it per operation. <a id="cite-check.auditing.alarm-accumulates-mask"></a> Conditional alarm ACEs
use the same deny-side polarity as conditional audit ACEs. The alarm
branch deliberately performs no overlap test against the requested
mask — an alarm ACE contributes its mask on a SID match alone. <a id="cite-check.auditing.alarm-no-overlap-test"></a>

On each later operation the enforcement point emits a
`kacs.audit.handle.used` event when the operation's normalised
required-access mask overlaps the stored mask. <a id="cite-check.auditing.continuous-event-on-overlap"></a> For FACS handles that
is the same mask used by the use-time check ([Use-Time Semantics](</kernel/internals/kacs/file-security/use-time-semantics.md#trm-3-9-4>)). Where an
operation's authorization accepts any one of several rights — append
or write data, say — the required mask holds the accepted set and the
event records the subset that overlapped, as `access.matched`, beside
the whole stored mask as `access.audit-mask`. <a id="cite-check.auditing.continuous-records-overlapping-subset"></a>

Events are emitted after the per-operation decision is known, for
successful and denied attempts alike. <a id="cite-check.auditing.continuous-both-outcomes"></a> The subject and process recorded
are the **operation-time** effective token and current task, not
necessarily the ones that opened the handle. <a id="cite-check.auditing.continuous-operation-time-subject"></a> That keeps attribution
correct after a handle is passed between processes, while still using
the opener-computed mask to decide whether the handle is audited at
all.

An enforcement point that cannot construct a required continuous-audit
event fails closed. <a id="cite-check.auditing.continuous-fails-closed"></a> Transport buffering and drop accounting remain
KMES's concern ([Failure Modes](</kernel/internals/kmes/failure-modes.md#trm-2-7>)).

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

## Privilege-use auditing

When a privilege is exercised to grant access the DACL would not have
granted independently, a privilege-use event may be emitted. This runs
after the complete pipeline — after integrity policy, confinement and
central access policy — so it reflects the final result rather than an
intermediate one. <a id="cite-check.auditing.privilege-use-after-pipeline"></a>

**Successful** privilege use means the privilege's contributed bits
survive into the final granted result. The privilege is marked used,
and an event is emitted when the token's `audit_policy` carries
`PRIVILEGE_USE_SUCCESS` (0x04). <a id="cite-check.auditing.privilege-use-success"></a> **Failed** privilege use means the
privilege contributed bits during evaluation that did not survive. The
privilege is *not* marked used, and an event is emitted under
`PRIVILEGE_USE_FAILURE` (0x08). <a id="cite-check.auditing.privilege-use-failure"></a> A privilege that contributed nothing
to the requested access produces no event either way. <a id="cite-check.auditing.privilege-use-no-contribution"></a>

With an object type list, the test is per-node: a privilege counts as
successfully used if its bits survive on *any* node's final mask. <a id="cite-check.auditing.privilege-use-per-node"></a>

A `MAXIMUM_ALLOWED` request short-circuits this stage entirely,
recording no used bits and emitting no privilege-use events at all. <a id="cite-check.auditing.max-allowed-skips-privilege-use"></a>

How counterfactual the accounting really is varies by privilege, as
[The Privilege Model](</kernel/internals/kacs/privileges/the-privilege-model.md#trm-3-4-1>) describes: `SeSecurityPrivilege` and `SeTakeOwnershipPrivilege`
contribute only where the DACL had not already granted the right,
while backup and restore seed their bits unconditionally and so also
report use for accesses the DACL alone would have permitted. <a id="cite-check.auditing.backup-restore-overreport"></a>

<a id="trm-3-8-9-4"></a>

## Per-token audit policy

A token's `audit_policy` can force events regardless of SACL content.
This runs after the SACL walk and before result computation: if the
access succeeded and the policy carries `OBJECT_ACCESS_SUCCESS`
(0x01), a success event is emitted; if it failed and the policy
carries `OBJECT_ACCESS_FAILURE` (0x02), a failure event is. <a id="cite-check.auditing.forced-events"></a>

Success here means every requested bit was granted, or that nothing
was requested at all. <a id="cite-check.auditing.forced-success-definition"></a>

These events are additive — they fire even when no SACL ACE matched —
and they carry the object identity from the audit context the caller
supplied, exactly as a SACL-triggered record does. <a id="cite-check.auditing.forced-additive"></a> The
policy is per-token, fixed at creation, and follows impersonation,
since it is read from the effective token. <a id="cite-check.auditing.policy-from-effective-token"></a>

<a id="trm-3-8-9-5"></a>

## Event contents

An event carries the **subject**, the calling token's identity —
`subject.token.sid`, `.groups` with their parallel `.group-attributes`,
`.integrity`, the token's own LUID as `.id`, its logon session as
`.auth-id`, `.type`, `.impersonation` and the projected `.uid` — and
the PIP state as `subject.pip.type` and `subject.pip.trust`; the
**object**, as `object.kind` and the fields beneath it; the **access**,
as `access.requested` and `access.granted`, with `outcome.success`;
the **trigger**, `trigger.kind` (`sacl` or `policy`) and, for `sacl`,
the matched ACE as `trigger.ace`, or for a privilege record the
`privilege.*` fields; and the **process**, as
`emitter.process.pid`, `.name` and `.executable`. <a id="cite-check.auditing.event-contents"></a>

An access record also says what the mandatory checks withheld, since
that is often the whole reason a check the DACL would allow was denied:
`access.denied-integrity` is the requested bits the object's mandatory
label denied, and `access.denied-trust` the requested bits its
process-trust label denied — every bit each denied, for a
`MAXIMUM_ALLOWED` request — and each is absent when it denied none. <a id="cite-check.auditing.mandatory-denials-recorded"></a>

The pipeline itself produces only the object-and-access half — the
matched ACE bytes, the requested and granted masks, the outcome,
whether the event was policy-forced, the privilege, and the audit
context. The subject and process halves are attached at emission time
from the resolved call context, which is also where the effective PIP
values used for the verdict are reused for attribution.

<a id="trm-3-8-9-5-1"></a>

### The object

Where the kernel makes the check itself it knows the kind of object
and writes `object.kind`: `file`, `process`, `token`, `socket` (which
covers port-reservation binds) or `ipc`. A token check also writes the
target's `object.token.id` and `object.token.guid`. Some identity is
not yet reachable where the record is built, and is absent rather than
invented: `object.file.path` on file checks, `object.process.pid` and
`object.process.guid` on process checks. A mount-namespace check writes
`object.kind` `mount-namespace` and nothing beneath it: a namespace has
no name or identifier to carry. <a id="cite-check.auditing.mount-namespace-object-kind"></a>

A check made through `kacs_access_check` names its object through the
**audit context** (`audit_context_ptr`, `audit_context_len`), the
PGSS [The event stream](</kernel/internals/ntfe/event-ring-and-delivery.md#trm-6-7>) map:

```text
{kind: "service", service: {name: "jellyfin"}}
```

The kernel validates it before running the check and fails the call
with `EINVAL` unless it is well-formed msgpack no deeper than KMES's
default nesting depth less one; its root is a map of one or two
entries with string keys; it has exactly one `kind`, a string matching
the PGSS [The snapshot](</kernel/internals/ntfe/the-snapshot.md#trm-6-3>) segment grammar `[a-z][a-z0-9]*(-[a-z0-9]+)*`; and its
only other entry is keyed by that kind and holds a non-empty map whose
keys match the same grammar. The kernel copies it into the record as
`object.kind` and `object.<kind>.*` — `object.service.name` above. A
call without an audit context writes no `object`: the kernel does not
know what was checked.

These values are the caller's claim, which the kernel copied but did
not observe. So is everything else on the syscall path: the descriptor,
and with it `trigger.ace`, is the caller's, as is any PIP type or trust
it passes. Every record of `kacs_access_check` and
`kacs_access_check_list` therefore carries `fields.attestation.userspace`
set to `true`, with or without an audit context, and a record of a check
the kernel makes itself never does. <a id="cite-check.auditing.syscall-records-asserted"></a>
A context that is anything other than this map, such as the free-form
strings earlier components passed, fails with `EINVAL`.

---

# The Algorithm

_Peios Kernel / Internals / KACS / Access check_

> How every layer composes — the definitive statement of the evaluation order, from EvaluateSecurityDescriptor down through AccessCheckCore.

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

The preceding sections describe what each layer of AccessCheck does.
This one describes how they compose, and is the definitive statement
of the evaluation order.

<a id="trm-3-8-10-1"></a>

## Pipeline overview <a id="cite-check.algorithm.pipeline-order"></a>

Before the pipeline proper, two things are checked and can fail the
call outright.

- The token's own invariants are validated — a `write_restricted`
  token without `user_deny_only` is rejected as invalid. <a id="cite-check.algorithm.write-restricted-needs-deny-only"></a>
- In the orchestrator, a null descriptor is rejected and
  `AccessCheckResultList` is required to have been given an object
  type list. <a id="cite-check.algorithm.null-descriptor-rejected"></a>

A null descriptor presented by an Identification-level token
therefore fails as an invalid parameter rather than as access denied,
because the null check runs first. <a id="cite-check.algorithm.null-check-runs-first"></a>

The pipeline then runs in this order:

0. **Impersonation level gate.** An impersonation token at
   Identification level is denied immediately. <a id="cite-check.algorithm.identification-denied"></a> Anonymous tokens
   proceed through the full pipeline. <a id="cite-check.algorithm.anonymous-allowed"></a>
1. **Input validation.** Reject a descriptor with no owner. <a id="cite-check.algorithm.no-owner-rejected"></a> A null
   group SID is valid and has no direct effect on the decision. <a id="cite-check.algorithm.null-group-valid"></a>
2. **Generic mapping.** Map generic bits in the desired mask to
   object-specific bits; strip `MAXIMUM_ALLOWED`. <a id="cite-check.algorithm.desired-mask-mapped"></a>
3. **Effective privileges.** Clear the backup and restore bits when
   the corresponding intent flag is absent. <a id="cite-check.algorithm.intent-gates-backup-restore"></a> Callers of the
   userspace AccessCheck can give only these two intents.
4. **Privilege grants.** Resolve `ACCESS_SYSTEM_SECURITY`, backup and
   restore. Seed `decided`, `granted` and `privilege_granted`. <a id="cite-check.algorithm.privilege-seeding"></a>
5. **Pre-SACL walk.** Extract the mandatory integrity label, the PIP
   trust label, resource attributes and scoped policy SIDs from the
   SACL, then enforce MIC and PIP. <a id="cite-check.algorithm.pre-sacl-walk"></a>
6. **Virtual group resolution.** `S-1-3-4` and `S-1-5-10` become
   matchable where the caller is the owner or the object's principal.
7. **Tree initialisation.** Seed each node from the scalar state. <a id="cite-check.algorithm.tree-seeded-from-scalar"></a>
8. **Normal DACL evaluation.** Owner implicit rights, then the walk.
   Under the kernel-internal creator-grant intent, which only a file
   open that creates its object carries, the walk instead grants every
   right not already decided ([KACS-Native Open](</kernel/internals/kacs/file-security/kacs-native-open.md#trm-3-9-2-10>)). Every later step
   still applies. <a id="cite-check.algorithm.creator-grant"></a>
9. **Post-DACL WRITE_OWNER override.** `SeTakeOwnershipPrivilege`
   grants `WRITE_OWNER` if the DACL did not and no mandatory
   mechanism blocked it. <a id="cite-check.algorithm.take-ownership-override"></a>
10. **Restricted token pass**, with intersection and privilege
    restoration.
11. **Confinement pass**, with absolute intersection.
12. **CAAP.** Evaluate each applicable rule's DACL through the full
    per-descriptor pipeline and intersect; collect SACLs.
13. **Privilege-use auditing.**
14. **Audit emission**, over the object's SACL and any CAAP SACLs.
15. **Result computation.**

Object type lists are validated at parse time rather than at step 1 —
non-empty, one level-0 node first, no level gaps, no duplicate GUIDs —
so a malformed list never reaches the pipeline. <a id="cite-check.algorithm.list-validated-before-pipeline"></a> Step 1 re-checks only
emptiness.

Reserved access-mask bits (`0x0CE0_0000`) are rejected wherever a mask
is mapped. <a id="cite-check.algorithm.reserved-bits-rejected"></a> That applies to the caller's desired mask *and* to every
ACE mask, so a single ACE carrying a reserved bit aborts the entire
check rather than being skipped. <a id="cite-check.algorithm.reserved-bit-ace-aborts-check"></a>

<a id="trm-3-8-10-2"></a>

## EvaluateSecurityDescriptor

Steps 0–11, called once for the normal evaluation and once per CAAP
rule with a synthetic descriptor.

```
EvaluateSecurityDescriptor(
    sd, token, pip_type, pip_trust, desired, mapping,
    object_tree, self_sid, local_claims, privilege_intent
) -> (decided, granted, privilege_granted,
      max_allowed_mode, mapped_desired, resource_attributes,
      policy_sids) | error

    // Step 0: Impersonation level gate.
    if token.token_type == Impersonation
       and token.impersonation_level == Identification:
        return ERROR_ACCESS_DENIED

    // Step 1: Input validation.
    if sd.owner is null:
        return ERROR_INVALID_SECURITY_DESCR

    // Step 2: Generic mapping.
    desired = MapGenericBits(desired, mapping)
    max_allowed_mode = (desired & MAXIMUM_ALLOWED) != 0
    desired = desired & ~MAXIMUM_ALLOWED

    // Step 3: Effective privileges.
    effective_privileges = token.privileges_enabled
    if not (privilege_intent & BACKUP_INTENT):
        effective_privileges &= ~SeBackupPrivilege
    if not (privilege_intent & RESTORE_INTENT):
        effective_privileges &= ~SeRestorePrivilege

    // Step 4: Privilege-based grants.
    decided = 0; granted = 0; privilege_granted = 0

    // ACCESS_SYSTEM_SECURITY is always decided by privilege.
    decided |= ACCESS_SYSTEM_SECURITY
    if (effective_privileges & SeSecurityPrivilege):
        granted           |= ACCESS_SYSTEM_SECURITY
        privilege_granted |= ACCESS_SYSTEM_SECURITY

    if (effective_privileges & SeBackupPrivilege):
        backup_bits = MapGenericBits(GENERIC_READ, mapping)
        decided |= backup_bits; granted |= backup_bits
        privilege_granted |= backup_bits

    if (effective_privileges & SeRestorePrivilege):
        restore_bits = MapGenericBits(GENERIC_WRITE, mapping)
                     | WRITE_DAC | WRITE_OWNER | DELETE
                     | ACCESS_SYSTEM_SECURITY
        decided |= restore_bits; granted |= restore_bits
        privilege_granted |= restore_bits

    // Restore already includes WRITE_OWNER, so when it is active
    // step 9 has nothing left to do. Step 9 is the fallback for
    // when restore is inactive and the DACL did not grant it.

    // Step 5: Pre-SACL walk. mandatory_decided records bits decided
    // by MIC and PIP, so step 9 cannot override them.
    resource_attributes = {}; policy_sids = []; mandatory_decided = 0
    PreSACLWalk(sd, token, pip_type, pip_trust, mapping,
                &decided, &granted, &privilege_granted,
                &mandatory_decided, &resource_attributes,
                &policy_sids)

    // Steps 6-8: owner implicit rights are granted first, inside
    // EvaluateDACL, and the tree is seeded from the already
    // augmented scalar state. Virtual groups are resolved per
    // lookup rather than by building an enriched token.
    EvaluateDACL(sd, token, mapping, object_tree,
                 SidMatchesToken, desired, max_allowed_mode,
                 resource_attributes, local_claims,
                 skip_owner_implicit=false,
                 &decided, &granted)

    // Step 9: Post-DACL WRITE_OWNER override.
    if (desired & WRITE_OWNER) != 0 or max_allowed_mode:
        if (effective_privileges & SeTakeOwnershipPrivilege):
            if not (mandatory_decided & WRITE_OWNER)
               and not (granted & WRITE_OWNER):
                decided |= WRITE_OWNER
                granted |= WRITE_OWNER
                privilege_granted |= WRITE_OWNER
                for each node with WRITE_OWNER ungranted:
                    node.decided |= WRITE_OWNER
                    node.granted |= WRITE_OWNER

    // Step 10: Restricted token pass.
    if token.restricted_sids or token.restricted_device_groups:
        // Restricted identity view: only restricting SIDs, plus
        // S-1-3-4 if the owner is among them and S-1-5-10 if
        // self_sid is. Restricted device groups swap in.
        // Fresh tree, zeroed state.
        EvaluateDACL(sd, restricted_view, mapping, r_tree,
                     SidInRestrictingSids, desired,
                     max_allowed_mode, resource_attributes,
                     local_claims, skip_owner_implicit=false,
                     &r_decided, &r_granted)
        if token.write_restricted:
            write_bits = MapGenericBits(GENERIC_WRITE, mapping)
            granted = (granted & ~write_bits)
                    | (granted & r_granted & write_bits)
        else:
            granted = granted & r_granted
        granted |= privilege_granted        // privileges bypass
        // Same intersection and restoration per node.

    // Step 11: Confinement pass.
    if token.confinement_sid and not token.confinement_exempt:
        // Confinement SID set: confinement_sid plus every
        // capability, presence-based. S-1-3-4 and S-1-5-10 are
        // injected only if the owner or self_sid is in that set.
        EvaluateDACL(sd, token, mapping, c_tree,
                     SidInConfinementSids, desired,
                     max_allowed_mode, resource_attributes,
                     local_claims, skip_owner_implicit=true,
                     &c_decided, &c_granted)
        granted = granted & c_granted       // no privilege bypass
        // Same absolute intersection per node.

    return (decided, granted & root-consistent state,
            privilege_granted narrowed to what survived,
            max_allowed_mode, desired, resource_attributes,
            policy_sids)
```

The returned `privilege_granted` is **narrowed** by what actually
survived the pass — it is intersected with the root's granted mask on
return, and the orchestrator narrows it again against the CAAP result. <a id="cite-check.algorithm.privilege-granted-narrowed"></a>
A privilege-granted bit that the write-restricted merge or the
confinement intersection removed is therefore no longer part of it,
which matters in two places: the CAAP error escape hatch ([Central Access and Auditing Policy](</kernel/internals/kacs/access-check/central-access-and-auditing-policy.md#trm-3-8-8>)) has
fewer bits to preserve, and the audit provenance masks reflect the
narrowed set.

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

## AccessCheckCore

The orchestrator runs steps 12 through 15.

**Step 12, CAAP.** For each scoped policy SID, look the policy up —
falling back to the recovery policy when it is absent — and for each
rule whose `applies_to` is TRUE or absent, evaluate the rule's
synthetic descriptor through `EvaluateSecurityDescriptor` and
intersect. A rule that errors denies everything except the (already
narrowed) privilege-granted bits. Staged DACLs are evaluated in
parallel into a separate running total; a rule with no staged DACL
contributes its effective result to both.

After all policies, the staged and effective totals are compared and
any difference sets the staging mismatch flag. In result-list mode a
per-node delta sets it too — and so does a scalar delta, since the
comparison is not mode-branched. <a id="cite-check.algorithm.scalar-delta-sets-flag"></a>

**Step 13, privilege-use auditing.** For each of the five provenance
masks — security, backup, restore, take-ownership and relabel:

```
success_bits = provenance & mapped_desired & granted
failure_bits = provenance & mapped_desired & ~granted
```

Nonzero `success_bits` means the privilege was load-bearing: mark it
used on the token, and emit a success event under
`PRIVILEGE_USE_SUCCESS`. Otherwise nonzero `failure_bits` means it was
exercised but did not survive: do **not** mark it used, and emit a
failure event under `PRIVILEGE_USE_FAILURE`. Both zero means no event.
In result-list mode the comparison folds across nodes — success if the
bits survive on any node, failure only if they survive on none. <a id="cite-check.algorithm.privilege-use-folds-across-nodes"></a>

The event is `kacs.audit.privilege.used`. Its `privilege.contributed`
is `provenance & mapped_desired`, its `privilege.surviving` is
`success_bits` (empty on a failure event), and its `access.requested`
and `access.granted` are the whole check's `mapped_desired` and final
`granted`, not this privilege's share of them.

The whole step is skipped in `MAXIMUM_ALLOWED` mode, so such a request
marks nothing used and emits nothing.

Note that `relabel_granted` is tracked as provenance but is
deliberately excluded from `privilege_granted` itself, so a
relabel-loosened `WRITE_OWNER` is neither restored after the
restricted merge nor preserved by the CAAP error hatch.

**Step 14, audit emission.** Walk the object's SACL, then each CAAP
effective SACL, accumulating audit events and ORing alarm masks into
the continuous audit mask. <a id="cite-check.algorithm.sacl-walk-order"></a> This is read-only with respect to
`granted`.

The staged comparison then walks the object's SACL again followed by
the staged SACLs. That second walk is driven by the **staged** granted
total rather than the effective one, so the success and failure
classification of staged audit events reflects the staged access
result — which is what makes the flag sensitive to descriptors whose
staged and effective grants differ. <a id="cite-check.algorithm.staged-audit-walk-uses-staged-grant"></a>

**Step 14b, forced auditing.** With
`success = (granted & mapped_desired) == mapped_desired or
mapped_desired == 0`, the token's `audit_policy` forces a success or
failure event additively, regardless of what the SACL matched.

**Step 15** returns the accumulated state.

<a id="trm-3-8-10-4"></a>

## The wrappers

`AccessCheck` takes the **root node's** granted mask when a tree is
present, then computes `allowed` as `mapped_desired == 0` or every
requested bit granted. <a id="cite-check.algorithm.allowed-computation"></a> The root's mask equals the intersection across
all nodes by construction rather than by computation: upward denial
propagation ([Object ACEs and Property-Level Access](</kernel/internals/kacs/access-check/object-aces-and-property-level-access.md#trm-3-8-5>)) forces every descendant's denial into all of its
ancestors, so the root can never grant what a descendant denies.

`AccessCheckResultList` requires a tree and returns a per-node granted
mask and status, each node judged against `mapped_desired`
independently.

Neither wrapper filters the returned `granted` to the requested mask. <a id="cite-check.algorithm.granted-not-filtered"></a>
Privilege seeding at step 4 ORs bits in regardless of what was asked
for, so a caller that requested only `READ_CONTROL` while holding
backup can see read bits it never requested. The file enforcement path
does filter its result; the generic query path does not. <a id="cite-check.algorithm.file-path-filters-result"></a>

<a id="trm-3-8-10-5"></a>

## Helpers

```
SidMatchesToken(sid, token, for_allow) -> bool
    if sid == token.user_sid:
        if for_allow and token.user_deny_only:
            return false
        return true
    for group in token.groups:
        if not group.enabled and not group.deny_only:
            continue
        if for_allow and group.deny_only:
            continue
        if sid == group.sid:
            return true
    return false
```

```
MapGenericBits(mask, mapping) -> ACCESS_MASK
    if mask & RESERVED_BITS: reject
    mapped = mask & ~(GENERIC_READ | GENERIC_WRITE
                    | GENERIC_EXECUTE | GENERIC_ALL)
    if mask & GENERIC_READ:    mapped |= mapping.read
    if mask & GENERIC_WRITE:   mapped |= mapping.write
    if mask & GENERIC_EXECUTE: mapped |= mapping.execute
    if mask & GENERIC_ALL:     mapped |= mapping.all
    return mapped
```

All four generic bits are cleared before any is expanded, so a mask
naming several generics maps every one of them. <a id="cite-check.algorithm.all-generics-expand"></a>

**Virtual group resolution.** There is no enrichment step producing a
modified token. `S-1-3-4` and `S-1-5-10` are resolved at each lookup
instead, in the DACL walk, the SACL walk and conditional membership
alike. <a id="cite-check.algorithm.virtual-groups-per-lookup"></a> `S-1-5-10` resolves through the ordinary polarity rules against
`self_sid`, and `S-1-3-4` through the ordinary polarity rules against
the object's owner SID. Both are computed once per walk — the owner is
fixed while the polarity is per ACE — so each carries its allow and
deny answers together.

**`EvaluateSACL`** walks in a fixed order per ACE: SID match with deny
polarity, then object-type scoping against the tree, then the
condition, then the mask overlap against `mapped_desired`. <a id="cite-check.algorithm.sacl-ace-check-order"></a> Audit ACEs
need all four; alarm ACEs deliberately skip the overlap test and
contribute their mask on a SID match alone. Inherit-only ACEs are
skipped throughout. <a id="cite-check.algorithm.sacl-inherit-only-skipped"></a>

**`synthetic_sd`** builds a CAAP rule's descriptor from the original's
owner and optional group with the rule's DACL substituted, and the
SACL copied with every scoped policy ACE stripped — which is what
prevents recursion. The MIC and PIP labels are preserved, so a rule is
evaluated under the same mandatory constraints as the object. The
control bits and the stripped SACL's revision are recomputed rather
than copied. <a id="cite-check.algorithm.synthetic-recomputes-control-bits"></a>

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

## Provenance masks

| Variable | Set at | Meaning |
|---|---|---|
| `security_granted` | Step 4 | `SeSecurityPrivilege` granted `ACCESS_SYSTEM_SECURITY`. <a id="cite-check.algorithm.provenance.security"></a> |
| `backup_granted` | Step 4 | `SeBackupPrivilege` granted read bits. <a id="cite-check.algorithm.provenance.backup"></a> |
| `restore_granted` | Step 4 | `SeRestorePrivilege` granted write and metadata bits. <a id="cite-check.algorithm.provenance.restore"></a> |
| `take_ownership_granted` | Step 9 | `SeTakeOwnershipPrivilege` granted `WRITE_OWNER`. <a id="cite-check.algorithm.provenance.take-ownership"></a> |
| `relabel_granted` | Step 5 | `SeRelabelPrivilege` added `WRITE_OWNER` to the MIC allowed set. <a id="cite-check.algorithm.provenance.relabel"></a> |

Each records which bits that privilege contributed, and step 13
compares each against the requested mask and the final result.

---

# File security

_Peios Kernel / Internals / KACS / File security_

> Find the Peios kernel articles about file security.

Use these articles to understand file security in the Peios kernel.

- [The Handle Model](</kernel/internals/kacs/file-security/the-handle-model.md>)
- [KACS-Native Open](</kernel/internals/kacs/file-security/kacs-native-open.md>)
- [Legacy Open Compatibility](</kernel/internals/kacs/file-security/legacy-open-compatibility.md>)
- [Use-Time Semantics](</kernel/internals/kacs/file-security/use-time-semantics.md>)
- [Descriptor storage and caching](</kernel/internals/kacs/file-security/descriptor-storage-and-caching.md>)
- [Mount classes and bootstrap descriptors](</kernel/internals/kacs/file-security/mount-classes-and-bootstrap-descriptors.md>)
- [The Set-Security Interface](</kernel/internals/kacs/file-security/the-set-security-interface.md>)
- [Sharing and Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md>)
- [Byte-Range Locks](</kernel/internals/kacs/file-security/byte-range-locks.md>)
- [Leases](</kernel/internals/kacs/file-security/leases.md>)
- [Special Attributes](</kernel/internals/kacs/file-security/special-attributes.md>)

---

# The Handle Model

_Peios Kernel / Internals / KACS / File security_

> FACS is the file-specific enforcement surface of KACS — mount policy, scope, how a handle is acquired, and stacked backing files.

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

FACS, the File Access Control Shim, is the file-specific enforcement
surface of KACS. It replaces Linux DAC — UID, GID and mode-bit checks
— with security-descriptor evaluation on files.

Enforcement follows the handle pattern. AccessCheck runs once at open
time, the granted mask is cached on the file description, and later
operations test the cached mask:

```
(fd.granted & required) == required ? allow : deny
```

The mask is set once and never modified, and it is immutable for the
descriptor's whole lifetime regardless of any later descriptor change. <a id="cite-facs.handle.mask-immutable"></a>
A file's DACL can be rewritten while a process holds it open, and that
process keeps the rights it was granted. A few operations use a live
AccessCheck instead; [Use-Time Semantics](</kernel/internals/kacs/file-security/use-time-semantics.md#trm-3-9-4>) lists them.

A second immutable mask is stamped alongside it: the **continuous
audit mask** ([Auditing in AccessCheck](</kernel/internals/kacs/access-check/auditing-in-accesscheck.md#trm-3-8-9>)), which every use-time operation consults to
decide whether to emit a per-operation audit event. It travels with
the granted mask through every path described below. <a id="cite-facs.handle.audit-mask-stamped"></a>

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

## Mount policy

Every mounted filesystem exposes exactly one FACS mount-policy class,
scoped to the kernel superblock object rather than to a pathname or a
bind mount — several paths or bind mounts over one superblock all
observe the same class. <a id="cite-facs.handle.policy-per-superblock"></a>

**`unmanaged`** puts the mount outside the handle model entirely: no
granted mask is stamped on its file descriptions. <a id="cite-facs.handle.unmanaged-no-mask"></a> **`facs_deny_missing`**
is FACS-managed and denies access where a descriptor is missing.
**`facs_synthesize_ephemeral`** synthesises missing descriptors and
caches them in memory only. **`facs_synthesize_persistent`**
synthesises them and writes them back immediately. The three `facs_*`
classes are the only managed ones.

The default classifier is conservative. Hardcoded pseudo-filesystems —
`/proc`, `/sys`, nullfs — are `unmanaged`. Filesystems that cannot
reliably store the canonical descriptor xattr are
`facs_synthesize_ephemeral`: ramfs, FAT, exFAT, NFS client mounts,
ISO9660, and cgroup2. StrataFS is fixed at `facs_deny_missing`. Everything else
— tmpfs, squashfs, ext4, btrfs — defaults to `facs_deny_missing`
unless a trusted policy agent adopts it.

Userspace cannot set a superblock to `unmanaged` through the public
ABI; the class is reserved for the kernel classifier and the hardcoded
rules. Attempting to set a policy on a magic-derived `unmanaged`
superblock fails with `EOPNOTSUPP`, and so does attempting to change
StrataFS's. <a id="cite-facs.handle.unmanaged-not-settable"></a>

<a id="trm-3-9-1-2"></a>

## Scope

The sole-authority claim covers local FACS-managed filesystems. It
does not cover:

- `O_PATH` descriptors, which are not managed;
- NFS client mounts, which are ephemeral-synthesising and retain dual
  authority with the server;
- `/proc`, which is unmanaged and PIP-protected; or
- `/sys`, which is unmanaged and carries a hardcoded rule instead —
  writes there require Administrators or SYSTEM, enforced against a
  built-in descriptor. <a id="cite-facs.handle.sysfs-write-builtin-descriptor"></a>

Descriptors for processes obtained through `pidfd` bypass FACS at open
as well. <a id="cite-facs.handle.pidfd-bypasses-open"></a>

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

## Handle acquisition

A descriptor carries its granted mask through every acquisition path,
and transfer is an intentional capability-delegation mechanism.

- `dup`/`dup3` and `fork` produce the same open file description and
  therefore the same rights; <a id="cite-facs.handle.dup-fork-same-rights"></a>
- descriptors without `FD_CLOEXEC` survive exec unchanged; <a id="cite-facs.handle.exec-preserves-mask"></a>
- `SCM_RIGHTS` transfers the descriptor as a capability token, with
  possession as authorization and no re-check of the receiver's
  identity; and <a id="cite-facs.handle.scm-rights-capability"></a>
- `pidfd_getfd()` is gated by an AccessCheck for `PROCESS_DUP_HANDLE`
  against the target process, after which the caller receives the
  descriptor with its full mask. <a id="cite-facs.handle.pidfd-getfd-gate"></a>

The security boundary is at open time. Every subsequent transfer
carries the mask unchanged.

This means mandatory subject policy — MIC and PIP — is evaluated once,
at open, against the opener. <a id="cite-facs.handle.mic-pip-at-open"></a> A high-integrity process that opens a
file and passes the descriptor to a low-integrity one has effectively
delegated its access. That is the handle model: authority is on the
handle, not on the holder.

<a id="trm-3-9-1-4"></a>

## Stacked backing files

When a stacking filesystem creates a kernel-private backing file for a
managed user-visible file, the outer file's granted and continuous
audit masks are captured into the backing-file blob, and the backing
file's ordinary blob receives that exact snapshot when the provider is
opened. <a id="cite-facs.handle.backing-snapshot-captured"></a> No new AccessCheck runs against the task executing the
stacking filesystem. <a id="cite-facs.handle.backing-no-new-accesscheck"></a>

The inheritance is deliberately narrow. It is admitted only through
the kernel's typed backing-file allocation path, only from a managed
non-`O_PATH` outer file, and it retains no reference to that outer
file — only the values. <a id="cite-facs.handle.backing-admission-narrow"></a> It is not a general snapshot-cloning
mechanism.

An active StrataFS copy-up context takes precedence: a backing open
that does not match its exact object and phase does not fall back to
inherited authority. <a id="cite-facs.handle.copy-up-context-precedence"></a> When an exactly-bound copy-up backing file is
adopted by the outer descriptor, the outer snapshot is installed into
both blobs as a single transition, after which the backing file
behaves like any other stacked open.

For an OverlayFS provider, this handoff also reaches the exact private
backing files opened beneath the staged file. KACS validates the bounded
chain before changing any snapshot, then copies the original outer handle's
granted and continuous-audit masks into both blobs of every admitted file.
The handoff runs after the staged open and before publication. It does not
relax the active copy-up context's object and phase checks.

The user-visible operation is checked and continuously audited once,
against the outer handle. Immediate provider re-entry through
`security_file_permission` or `security_mmap_file` neither repeats the
caller authorization nor emits a second caller audit event. <a id="cite-facs.handle.no-duplicate-provider-check"></a> The
backing file keeps the snapshot for later descriptor-local
enforcement, including `mprotect()` after a stacked mmap, and the
`mmap_backing_file` handoff verifies that the outer, backing and
captured snapshots still agree before the provider mapping is
installed. <a id="cite-facs.handle.mmap-backing-verifies-agreement"></a>

This suppresses duplicate *KACS* authorization only. It bypasses
nothing else — not another LSM, not filesystem errors, not read-only
mounts, immutable state, quota, space, I/O, or format validation. <a id="cite-facs.handle.backing-suppresses-kacs-only"></a>

## Operational consequences

Treat a transferred descriptor as a capability carrying its established
rights. Passing it to a less privileged process does not rerun the original
open against the receiver's token. Fork can retain those open descriptions;
exec retains descriptors without close-on-exec. Review descriptor inheritance
as part of a launcher or request broker's authority design.

Changing a descriptor, token, or central policy does not retrospectively
revoke that cached file-handle grant. Conversely, losing a token privilege
does not prove an old descriptor lost its usable rights. Test changed policy
with fresh opens. Mappings have their own creation-time checks and page
permissions, not a fresh policy decision for every memory access.

An `O_PATH` handle does not carry ordinary data-access authority; descriptor
management uses its documented live checks. Append-only authority does not
authorize truncation or shared writable mapping. A remote filesystem can also
apply server-side authority after the local check. These boundaries belong
to [use-time semantics](/kernel/internals/kacs/file-security/use-time-semantics.md)
and [legacy-open compatibility](/kernel/internals/kacs/file-security/legacy-open-compatibility.md),
not a general promise that every operation consults only one immutable mask.

---

# KACS-Native Open

_Peios Kernel / Internals / KACS / File security_

> Opening a file by naming every right up front — handle modes, rights granted through the parent, share access, create dispositions, the creator's access and what the open reports.

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

> [!IMPORTANT]
> The [open-interface comparison](/kernel/userspace/native/kacs/abi-status-and-naming-differences.md#trm-3-d-6) records unresolved differences and the [limited pinned-source findings](/kernel/userspace/native/kacs/abi-status-and-naming-differences.md#trm-3-d-6-1) applied here. Creator-SD rejection, the accepted create-option bits, and native-open versus SD-query no-follow behavior were checked in source; the other differences remain unresolved. No runtime test or historical release boundary is established.

`kacs_open` takes an explicit desired access mask. The caller names
every right it will need — `FILE_READ_DATA`, `FILE_WRITE_DATA`,
`WRITE_DAC`, `READ_CONTROL`, any combination — and AccessCheck
evaluates the whole requested mask at open. If every requested right
is granted the descriptor's mask is set to the requested mask; if any
is denied, the open fails. <a id="cite-facs.open.strict-all-or-nothing"></a> This is the **strict** mode, in contrast to
the legacy path's subset behaviour ([Legacy Open Compatibility](</kernel/internals/kacs/file-security/legacy-open-compatibility.md#trm-3-9-3>)).

`MAXIMUM_ALLOWED` asks for everything the caller may have. Any
concrete bits named with it have to be granted; the cached mask is
then the full computed maximum rather than the requested set. <a id="cite-facs.open.maximum-allowed-computes-max"></a>
`MAXIMUM_ALLOWED` may also be named alone. <a id="cite-facs.open.maximum-allowed-alone"></a> The maximum includes
the rights granted through the parent directory, described below, and
excludes the rights a read-only file withholds ([Special
Attributes](</kernel/internals/kacs/file-security/special-attributes.md#trm-3-9-13>)).

A caller reads back what an open was granted with `kacs_query_open`,
which reports the cached mask, the open's share access, and whether the
file is delete-pending. <a id="cite-facs.open.query-open"></a> It is how a caller learns the result of a
`MAXIMUM_ALLOWED` open. The query needs no right: it reveals only what
the descriptor already carries. It fails with `EOPNOTSUPP` on an
unmanaged descriptor, including an `O_PATH` one.

<a id="trm-3-9-2-1"></a>

## Handle modes <a id="cite-facs.open.handle-modes"></a>

A Linux open file has a mode — readable, writable, or neither — which
the VFS uses for its own accounting, such as write access to an
executable and file leases. A native open derives that mode from the
rights it is granted: `FILE_READ_DATA` gives `FMODE_READ`, either
write right gives `FMODE_WRITE`, and `FILE_EXECUTE` gives `FMODE_EXEC`,
which enables `execveat(fd, "", ..., AT_EMPTY_PATH)`. <a id="cite-facs.open.execute-only-handle"></a>

An open granted none of these is a **control handle**: a managed
descriptor with no data mode, carrying only metadata, security or
delete rights. <a id="cite-facs.open.control-handle"></a> It can read attributes, read and change the
security descriptor, set a delete disposition, rename, and take part in
share checks. It cannot read or write the file's contents. No native
open needs to name a data right to obtain a descriptor. <a id="cite-facs.open.no-required-data-right"></a>

The mode is chosen **before** the file is opened, so that the VFS never
takes write access, read accounting or a lease break for an open that
does not hold the matching right. For an explicit mask the mode follows
the requested bits. For `MAXIMUM_ALLOWED`, KACS first evaluates the
maximum against the file's current descriptor and takes the mode from
the data rights that maximum contains. <a id="cite-facs.open.mode-before-open"></a>

The open hook then runs the authoritative check, as for every open. If
the descriptor changed between the two evaluations, the hook's result
stands. A strict request that is now denied fails as any denied open
does. A `MAXIMUM_ALLOWED` open is stamped with the new maximum, less
any data right its mode cannot exercise, so that `kacs_query_open`
never reports a right the descriptor cannot use. <a id="cite-facs.open.hook-authoritative"></a>

A `MAXIMUM_ALLOWED` open granted a write right takes write access like
any writer. Such an open of a file being executed fails with `ETXTBSY`,
and it breaks other holders' read leases.

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

## Directories

Directory rights share bit positions with file data rights:
`FILE_LIST_DIRECTORY` is `FILE_READ_DATA` (0x0001), `FILE_ADD_FILE` is
`FILE_WRITE_DATA` (0x0002), and `FILE_ADD_SUBDIRECTORY` is
`FILE_APPEND_DATA` (0x0004). A directory open with `FILE_LIST_DIRECTORY`
is opened `FMODE_READ`; a directory open without it is a control
handle. <a id="cite-facs.open.dir-list-mode"></a>

The two write aliases are not cacheable directory handle rights,
though. `kacs_open` rejects a desired mask naming `FILE_ADD_FILE`,
`FILE_ADD_SUBDIRECTORY` or `FILE_DELETE_CHILD` on a directory with
`EOPNOTSUPP`. <a id="cite-facs.open.dir-write-aliases-eopnotsupp"></a> Those are parent-directory authorization rights for
namespace operations, evaluated live at the operation, not rights a
handle carries.

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

## Special nodes and symlinks

Existing FIFOs, pathname socket nodes, and character and block device
nodes on managed mounts are ordinary filesystem file objects for
authorization: the file object type, the file right mapping, and the
file GenericMapping for metadata, standard and generic rights. <a id="cite-facs.open.special-nodes-are-file-objects"></a>

A special node still has to be opened with a data right, because its
driver decides what an open without one means; a FIFO refuses it. A
native open of a special node granted no data right fails with
`EINVAL`. <a id="cite-facs.open.special-nodes-need-data-right"></a> `FILE_EXECUTE` is not a valid data substitute for them — a
`kacs_open` naming it on such a node fails closed. <a id="cite-facs.open.execute-not-valid-on-special-nodes"></a> The Linux object
implementation may still impose its own device- or
filesystem-specific denial after KACS has authorized the file object.

Symlink objects are file objects for `kacs_get_sd`, `kacs_set_sd` and
`readlink`, but they are not opened as terminal objects by
`kacs_open`. Following is the default resolution behaviour, and
`AT_SYMLINK_NOFOLLOW` fails with `ELOOP`. <a id="cite-facs.open.symlink-nofollow-eloop"></a> This differs deliberately
from `kacs_get_sd` and `kacs_set_sd`, where the same flag resolves the
symlink object itself.

<a id="trm-3-9-2-8"></a>

## Rights granted through the parent <a id="cite-facs.open.parent-grants"></a>

Two rights may be granted by the parent directory when the file's own
descriptor withholds them, as NTFS grants them (MS-FSA 2.1.5.1.2.1):

- **`DELETE`** is granted if the parent grants `FILE_DELETE_CHILD`. <a id="cite-facs.open.delete-through-parent"></a>
- **`FILE_READ_ATTRIBUTES`** is granted if the parent grants
  `FILE_LIST_DIRECTORY`. A caller who may list a directory may already
  see what its entries' attributes would show. <a id="cite-facs.open.read-attributes-through-parent"></a>

AccessCheck runs first against the file. For each of these two rights
that it does not grant, it runs again against the parent directory for
the parent right. The parent is the directory the open resolved the
file through, so for a file with several hard links it is the parent
of the link that was opened. <a id="cite-facs.open.parent-is-opened-link"></a> A `MAXIMUM_ALLOWED` open includes
whichever of the two the parent grants.

The same pair of checks governs every other operation that deletes or
reads attributes by name: unlink, rmdir and rename by path, delete on
close, superseding a file, and `stat` by path ([Use-Time
Semantics](</kernel/internals/kacs/file-security/use-time-semantics.md#trm-3-9-4-2>)). <a id="cite-facs.open.delete-fallback"></a>

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

## Share access <a id="cite-facs.open.share-access"></a>

Every open of a regular file or directory on a managed mount takes part
in NT share-mode checking ([Sharing and Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md#trm-3-9-10>)). A native open
states the sharing it allows in `kacs_open_how.share_access`, read only
when `flags` carries `KACS_OPEN_SHARE_ACCESS`:

| Value | Name | Others may open with |
|---|---|---|
| 0x1 | `KACS_FILE_SHARE_READ` | `FILE_READ_DATA` or `FILE_EXECUTE` |
| 0x2 | `KACS_FILE_SHARE_WRITE` | `FILE_WRITE_DATA` or `FILE_APPEND_DATA` |
| 0x4 | `KACS_FILE_SHARE_DELETE` | `DELETE` |

Without the flag the open shares all three, as a legacy open does, and
`share_access` has to be zero. <a id="cite-facs.open.share-default-all"></a> An open that conflicts with
another fails with `EBUSY` and the status `KACS_STATUS_SHARING_VIOLATION`.

<a id="trm-3-9-2-4"></a>

## Create dispositions <a id="cite-facs.open.create-dispositions"></a>

| Value | Name | If it exists | If it does not |
|---|---|---|---|
| 0 | `FILE_SUPERSEDE` | Delete and recreate | Create |
| 1 | `FILE_OPEN` | Open | Fail |
| 2 | `FILE_CREATE` | Fail | Create |
| 3 | `FILE_OPEN_IF` | Open | Create |
| 4 | `FILE_OVERWRITE` | Truncate to zero | Fail |
| 5 | `FILE_OVERWRITE_IF` | Truncate to zero | Create |

`FILE_SUPERSEDE` deletes the existing name and creates a new file
under it, requiring `DELETE` on the existing file — or
`FILE_DELETE_CHILD` on the parent — together with `FILE_ADD_FILE` on
the parent. <a id="cite-facs.open.supersede-rights"></a> The existing file's other opens have to share `DELETE`,
and a read-only or delete-pending file cannot be superseded. The new
file gets a new inode and a new descriptor, inherited or
caller-supplied. The superseded pathname is broken away from the old
hardlink set and names the new inode; other pre-existing hardlinks
continue to name the old inode, and already-open descriptors still
reference it. <a id="cite-facs.open.supersede-new-inode"></a>

`FILE_OVERWRITE` truncates in place — same inode, same descriptor,
hardlinks preserved — and requires `FILE_WRITE_DATA`. <a id="cite-facs.open.overwrite-in-place"></a>

On an `unmanaged` mount, `FILE_OPEN` and `FILE_OPEN_IF` succeed and
return an unmanaged descriptor with no stamped mask rather than
failing; the creating dispositions fail with `EOPNOTSUPP`. <a id="cite-facs.open.unmanaged-create-eopnotsupp"></a>

<a id="trm-3-9-2-5"></a>

## Create options

| Value | Name | Description |
|---|---|---|
| 0x0001 | `KACS_CREATE_OPT_DIRECTORY` | The target has to be a directory. When creating, create a directory rather than a regular file; when opening an existing non-directory, fail with `ENOTDIR`. <a id="cite-facs.open.create-opt-directory"></a> |
| 0x0002 | `KACS_CREATE_OPT_DELETE_ON_CLOSE` | Mark the file for deletion when this open closes. Requires `DELETE`, which may come through the parent. |

All other bits are reserved and have to be zero; a nonzero reserved
bit fails with `EINVAL`. <a id="cite-facs.open.reserved-create-option-einval"></a>

Delete-on-close is NT's: the obligation belongs to the open, and when
the open closes the file becomes **delete-pending**. The name is removed
at the last close of any open of the file, from any process
([Sharing and Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md#trm-3-9-10-3>)). <a id="cite-facs.open.delete-on-close-nt"></a> `dup()`, `fork()` and `SCM_RIGHTS`
preserve the obligation because they preserve the open file
description; it is discharged when the description's last reference
closes. <a id="cite-facs.open.delete-on-close-lineage"></a> `kacs_set_disposition` with `KACS_DISPOSITION_ON_CLOSE` sets or
clears it on an open that has `DELETE`.

Delete-on-close applies to regular files and directories. A directory
is removed only if it is empty when it is deleted. <a id="cite-facs.open.delete-on-close-directories"></a> A read-only
regular file cannot be opened with delete-on-close: the open fails with
`EPERM` and the status `KACS_STATUS_CANNOT_DELETE`.

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

## Caller-supplied descriptors

The descriptor format and size bound are defined in [SD Structure](https://learn.peios.org/specifications/pcds/security-descriptor/structure#binary-format).

When a disposition results in a new file the caller may supply a
descriptor. A null pointer with zero length means the new file's
descriptor is inherited from the parent directory through the
inheritance algorithm. <a id="cite-facs.open.null-descriptor-inherits"></a>

Supplying one on a branch that opens an *existing* object is invalid
input rather than something silently ignored. `FILE_OPEN_IF`
resolving to an existing object fails with `EINVAL`, and so do
`FILE_OVERWRITE` and the existing-object branch of
`FILE_OVERWRITE_IF`, since those retain the existing inode and its
descriptor. <a id="cite-facs.open.supplied-on-existing-einval"></a> `FILE_OPEN` with a descriptor supplied fails with
`EOPNOTSUPP`. <a id="cite-facs.open.supplied-with-file-open-eopnotsupp"></a>

Creator-supplied descriptors are validated at create time. An owner
SID has to be the caller's own or a token group marked
`SE_GROUP_OWNER`, unless `SeRestorePrivilege` is enabled, in which
case any owner is allowed. <a id="cite-facs.open.supplied-owner-constraint"></a> A supplied SACL is treated as a full SACL
input rather than a label-only fragment, and therefore requires
`SeSecurityPrivilege`. <a id="cite-facs.open.supplied-sacl-requires-privilege"></a> If that SACL carries an explicit mandatory
label ACE, the label also has to satisfy the ordinary label-write
constraint: at or below the caller's integrity level, unless
`SeRelabelPrivilege` is held. <a id="cite-facs.open.supplied-label-constraint"></a>

Generic rights in the descriptor's ACEs are mapped to file rights when
the descriptor is stored, whether it was supplied, inherited or taken
from the token's default DACL ([The Set-Security Interface](</kernel/internals/kacs/file-security/the-set-security-interface.md#trm-3-9-6-7>)).

<a id="trm-3-9-2-10"></a>

## The creator's access <a id="cite-facs.open.creator-access"></a>

The parent's create rights authorize the creation: `FILE_ADD_FILE` or
`FILE_ADD_SUBDIRECTORY`, together with the supersede rules above. The
handle a creating open returns is then granted the access it asked
for, as in Windows, even where the new file's descriptor would not
grant it to its creator. <a id="cite-facs.open.creator-granted-requested"></a> A creator can therefore create a file with a
restrictive descriptor and still write it, in one step, and a folder
can accept files whose inherited permissions exclude the people who put
them there.

The grant replaces only the **normal discretionary pass**. The kernel
computes the new object's descriptor first, then runs the strict check
against it, with the normal DACL walk treated as granting the creator
everything. <a id="cite-facs.open.creator-normal-pass-only"></a> Every other layer still evaluates the new descriptor and
can refuse:

- the mandatory integrity label and PIP;
- the restricted-token pass;
- confinement, which stays absolute ([Application Confinement](</kernel/internals/kacs/access-check/application-confinement.md#trm-3-8-6>));
- central access and auditing policy; and
- privilege-only rights, such as `ACCESS_SYSTEM_SECURITY`.

So a low-integrity creator under an inherited high-integrity label
cannot write what it created, and a confined application cannot write
outside what its confinement identity is granted. A `MAXIMUM_ALLOWED`
creating open is granted every right of the object type that those
layers allow. A refused check rolls the creation back — the newly
created file or directory is removed — and the syscall fails. <a id="cite-facs.open.failed-check-rolls-back"></a>

The grant belongs to the creating open alone. `FILE_OPEN_IF` or
`FILE_OVERWRITE_IF` that finds an existing object is an ordinary open,
and every later open of the new object is checked against its
descriptor as normal. <a id="cite-facs.open.creator-grant-only-when-creating"></a>

<a id="trm-3-9-2-11"></a>

## Ancestor pinning

`KACS_OPEN_PIN_ANCESTORS` pins the opened file's ancestor directories:
while the open lasts, none of them can be renamed or removed by anyone
([Sharing and Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md#trm-3-9-10-6>)). It requires `SeLockParentagePrivilege` enabled;
without it the open fails with `EPERM`. <a id="cite-facs.open.pin-requires-privilege"></a>

<a id="trm-3-9-2-12"></a>

## Lease keys

With `KACS_OPEN_LEASE_KEY`, `kacs_open_how.lease_key` and `lease_fd`
identify the opener to the lease manager given by `lease_fd`. Opening a
file does not break leases that the same manager holds under the same
key ([Leases](</kernel/internals/kacs/file-security/leases.md#trm-3-9-12>)). <a id="cite-facs.open.lease-key-exemption"></a> `lease_fd` has to be a lease-manager
descriptor, or the open fails with `EBADF`.

<a id="trm-3-9-2-7"></a>

## Modes and status

`kacs_open_how` carries no POSIX mode field, so the raw Linux inode
mode for native creation is fixed: `0600` for regular files, `0700`
for directories. <a id="cite-facs.open.fixed-create-modes"></a> These are compatibility metadata only — and if Linux
DAC ever denies an operation KACS would have authorized, the operation
fails closed.

Native creation does not create FIFOs, socket nodes, device nodes or
symlinks. <a id="cite-facs.open.no-native-special-creation"></a> Those stay on the Linux namespace APIs — `mknod()`,
`mkfifo()`, Unix `bind()` to a path — governed by the namespace hooks.
NTFS is excluded from native creation entirely. <a id="cite-facs.open.ntfs-excluded"></a>

`kacs_open_how` is size-versioned. A caller passes the size it was
built with — 32 bytes for the original layout, 56 bytes with the lease
fields — and fields beyond that size read as zero. A size below 16
bytes fails with `EINVAL`. <a id="cite-facs.open.how-size-versioned"></a> New fields are added at the end, behind a
flag, so that an existing caller's meaning never changes.

The syscall reports what happened through `status_out`: created,
opened, overwritten, or superseded. `KACS_STATUS_SUPERSEDED` is used
only when an existing object was actually replaced — a
`FILE_SUPERSEDE` that finds no target and simply creates one reports
`KACS_STATUS_CREATED`. <a id="cite-facs.open.status-superseded-only-if-replaced"></a>

When the open fails for a reason one errno cannot tell apart,
`status_out` also names the NT condition: <a id="cite-facs.open.failure-status"></a>

| Status | Errno | Condition |
|---|---|---|
| `KACS_STATUS_SHARING_VIOLATION` | `EBUSY` | Another open's share access conflicts with this one. |
| `KACS_STATUS_DELETE_PENDING` | `EBUSY` | The file is delete-pending. |
| `KACS_STATUS_CANNOT_DELETE` | `EPERM` | Delete-on-close on a read-only file. |

On any other failure `status_out` is left unwritten.

---

# Legacy Open Compatibility

_Peios Kernel / Internals / KACS / File security_

> Linux open flags cannot express WRITE_DAC or READ_CONTROL — how FACS maps them to core and compat rights, and what O_PATH does.

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

> [!IMPORTANT]
> The open-interface references contain [unresolved documentation differences](/kernel/userspace/native/kacs/abi-status-and-naming-differences.md#trm-3-d-6). Read that note alongside this page; no runtime behavior or release boundary has been established for those differences.

Linux's `open()` and `openat()` cannot express rights like `WRITE_DAC`
or `READ_CONTROL`. FACS maps the open flags to a **core** set of
required rights plus a **compat** set of POSIX-expected ones, and
evaluates both in a single AccessCheck.

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

## Core rights <a id="cite-facs.legacy.core-rights"></a>

The core set is the minimum for a usable descriptor, and the open
fails if any of it is denied.

For regular files, device nodes, FIFOs and pathname sockets:

| Flags | Core rights |
|---|---|
| `O_RDONLY` | `FILE_READ_DATA \| FILE_READ_ATTRIBUTES` |
| `O_WRONLY` | `FILE_WRITE_DATA \| FILE_READ_ATTRIBUTES` |
| `O_RDWR` | `FILE_READ_DATA \| FILE_WRITE_DATA \| FILE_READ_ATTRIBUTES` |

For directories, `O_RDONLY` gives
`FILE_READ_ATTRIBUTES | FILE_TRAVERSE`. Directory core deliberately
excludes `FILE_LIST_DIRECTORY`, so a directory opened `O_RDONLY` can
be used for `fchdir()` and `fstat()` without listing permission;
listing is a compat right. <a id="cite-facs.legacy.directory-core-excludes-list"></a>

Two modifiers apply in order. `O_APPEND` replaces `FILE_WRITE_DATA`
with `FILE_APPEND_DATA`, and `O_TRUNC` adds `FILE_WRITE_DATA`. Given
both, the replacement happens first and the re-addition second, so
core ends up with `FILE_APPEND_DATA` and `FILE_WRITE_DATA` together. <a id="cite-facs.legacy.append-trunc-order"></a>

`FILE_READ_ATTRIBUTES` is always core: a descriptor granting data
access but denying attribute reads is not openable through the legacy
APIs at all. <a id="cite-facs.legacy.read-attributes-always-core"></a>

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

## Compat rights <a id="cite-facs.legacy.compat-rights"></a>

Requested alongside core and silently omitted where denied:
`FILE_READ_EA` for `fgetxattr()`; `READ_CONTROL` for reading the
descriptor; `FILE_WRITE_ATTRIBUTES` for `futimens()`; `FILE_WRITE_EA`
for `fsetxattr()`; `FILE_WRITE_DATA` on `O_APPEND` opens so
`ftruncate()` works where the descriptor allows it; `WRITE_DAC`,
because POSIX permits `fchmod()` on any descriptor; `WRITE_OWNER`, for
`fchown()` on the same grounds; `SYNCHRONIZE`;
`FILE_LIST_DIRECTORY`, enabling `readdir()` on directory descriptors;
and `FILE_EXECUTE`, enabling `fexecve()` on regular files.

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

## The flow

The full requested mask is core plus compat. AccessCheck returns the
subset the descriptor allows. If every core right is present the
actual granted mask — which may include all, some or none of compat —
is stamped on the descriptor; otherwise the open fails with `EACCES`. <a id="cite-facs.legacy.core-missing-eacces"></a>

Both open paths run the same pipeline with different success
criteria. Native open is **strict**: everything requested has to be
granted. Legacy open is **subset**: only core has to be fully present.

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

## Sharing, deletion and read-only <a id="cite-facs.legacy.share-participation"></a>

A legacy open of a regular file or directory on a managed mount takes
part in NT share-mode checking. It shares read, write and delete, so
legacy opens never conflict with each other, but it fails with `EBUSY`
where a native open has denied its class of access ([Sharing and
Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md#trm-3-9-10-1>)). It also fails with `EBUSY` if the file is delete-pending,
as an `O_PATH` open of a delete-pending file does. <a id="cite-facs.legacy.delete-pending-ebusy"></a>

A legacy open for writing of a read-only regular file fails with
`EACCES`, and the compat write rights are omitted from a read-only
open of one ([Special Attributes](</kernel/internals/kacs/file-security/special-attributes.md#trm-3-9-13-2>)). <a id="cite-facs.legacy.readonly"></a>

`FILE_READ_ATTRIBUTES`, which every legacy open requires, may be
granted through the parent's `FILE_LIST_DIRECTORY` ([KACS-Native
Open](</kernel/internals/kacs/file-security/kacs-native-open.md#trm-3-9-2-8>)).

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

## O_PATH

`O_PATH` descriptors are not FACS-managed. The VFS opens them without
calling the open hook, so they carry no granted mask and are left
unmanaged. KACS checks one thing as they open: an `O_PATH` open of a
delete-pending file fails with `EBUSY`. <a id="cite-facs.legacy.o-path-unmanaged"></a> They serve as namespace
anchors for the `*at()` syscalls.

`fstat()` and `fstatfs()` on them are allowed unconditionally. <a id="cite-facs.legacy.o-path-fstat-unconditional"></a>
`fchdir()` runs a live `FILE_TRAVERSE` check at use time. <a id="cite-facs.legacy.o-path-fchdir-live"></a> `fchmod()`,
`fchown()`, `fgetxattr()`, `fsetxattr()`, `ioctl()` and `mmap()` are
denied with `EBADF` — though `futimens()` currently has no such guard. <a id="cite-facs.legacy.o-path-ebadf"></a>
`execveat(fd, "", ..., AT_EMPTY_PATH)` has exec permission enforced by
a live AccessCheck in the bprm hook, and `kacs_get_sd` and
`kacs_set_sd` with `AT_EMPTY_PATH` likewise run live, which gives
race-free object identity without snapshot authorization. <a id="cite-facs.legacy.o-path-live-checks"></a>

That `fstat()` is unconditional means `FILE_READ_ATTRIBUTES` is not
authoritative for attribute confidentiality. In practice size,
timestamps and inode number are rarely confidential. The descriptor
itself *is* protected: `kacs_get_sd` on an `O_PATH` handle performs a
live check.

---

# Use-Time Semantics

_Peios Kernel / Internals / KACS / File security_

> Every operation on an open descriptor is a mask check against the granted mask — data, metadata, traversal, append-only, fcntl and ioctl.

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

Every operation on an open descriptor is a mask check against the
granted mask, with one exception: `execveat(AT_EMPTY_PATH)` uses a
live AccessCheck. <a id="cite-facs.use.mask-check-per-operation"></a>

<a id="trm-3-9-4-1"></a>

## Data operations <a id="cite-facs.use.data-operations"></a>

| Operation | Required right |
|---|---|
| Read | `FILE_READ_DATA` |
| Sequential write, no append intent | `FILE_WRITE_DATA` |
| Append-intent write (`O_APPEND` descriptor or `RWF_APPEND`) | `FILE_APPEND_DATA` or `FILE_WRITE_DATA` |
| Positioned write, or a no-append override | `FILE_WRITE_DATA` — denied on append-only descriptors |
| Directory listing | `FILE_LIST_DIRECTORY` |
| `ftruncate` | `FILE_WRITE_DATA` |
| `fallocate` allocation (`ALLOCATE_RANGE`, with or without `KEEP_SIZE`) | `FILE_APPEND_DATA` or `FILE_WRITE_DATA` |
| `fallocate` mutation (`PUNCH_HOLE`, `ZERO_RANGE`, `COLLAPSE_RANGE`, `INSERT_RANGE`, `UNSHARE_RANGE`, `WRITE_ZEROES`) | `FILE_WRITE_DATA` |
| `mmap PROT_READ` | `FILE_READ_DATA` |
| `mmap PROT_WRITE \| MAP_SHARED` | `FILE_WRITE_DATA` — `FILE_APPEND_DATA` alone is insufficient <a id="cite-facs.use.mmap-shared-write-needs-write-data"></a> |
| `mmap PROT_WRITE \| MAP_PRIVATE` | `FILE_READ_DATA` — copy-on-write, no write to the file <a id="cite-facs.use.mmap-private-needs-read"></a> |
| `mmap PROT_EXEC` | `FILE_EXECUTE` |
| `mprotect` | As `mmap`, for the new protection flags |
| `flock LOCK_SH` / `F_RDLCK` | `FILE_READ_DATA` |
| `flock LOCK_EX` / `F_WRLCK` | `FILE_WRITE_DATA` or `FILE_APPEND_DATA` |
| `fsync` / `fdatasync` | `SYNCHRONIZE` <a id="cite-facs.use.fsync-requires-synchronize"></a> |

A `fallocate` mode outside the supported set fails closed, and
`PUNCH_HOLE` additionally requires `KEEP_SIZE`. <a id="cite-facs.use.fallocate-unsupported-mode-fails"></a>

Reads, writes, truncation and content-changing `fallocate` on a
regular file are also checked against other opens' byte-range locks
when they are issued, and fail with `EAGAIN` on a conflict ([Byte-Range
Locks](</kernel/internals/kacs/file-security/byte-range-locks.md#trm-3-9-11-2>)). Memory-mapped access is not.

<a id="trm-3-9-4-2"></a>

## Metadata operations <a id="cite-facs.use.metadata-operations"></a>

| Operation | Required right |
|---|---|
| `stat` / `lstat` / path `statx` | `FILE_READ_ATTRIBUTES`, or `FILE_LIST_DIRECTORY` on the parent <a id="cite-facs.use.stat-through-parent"></a> |
| `fstat` / descriptor `statx` | `FILE_READ_ATTRIBUTES` |
| `fstatfs` | `FILE_READ_ATTRIBUTES` |
| path and descriptor `file_getattr` | `FILE_READ_ATTRIBUTES`; by path, also through the parent |
| path and descriptor `file_setattr` | `FILE_WRITE_ATTRIBUTES` |
| `truncate` by pathname | `FILE_WRITE_DATA` |
| `chmod` / `fchmodat` / `fchmod` | `WRITE_DAC` <a id="cite-facs.use.chmod-requires-write-dac"></a> |
| `chown` / `lchown` / `fchownat` / `fchown` | `WRITE_OWNER` <a id="cite-facs.use.chown-requires-write-owner"></a> |
| `utimensat` / `utimes` / `futimens` | `FILE_WRITE_ATTRIBUTES` |
| `getxattr` / `lgetxattr` / `fgetxattr` | `FILE_READ_EA` |
| `setxattr` / `lsetxattr` / `removexattr` / `fsetxattr` / `fremovexattr` | `FILE_WRITE_EA` |
| `listxattr` / `llistxattr` / `flistxattr` | none <a id="cite-facs.use.listxattr-needs-no-right"></a> |
| get `security.peios.sattr` | `FILE_READ_ATTRIBUTES` |
| set or remove `security.peios.sattr` | `FILE_WRITE_ATTRIBUTES` |
| `access` / `faccessat` `F_OK` | `FILE_READ_ATTRIBUTES`, or `FILE_LIST_DIRECTORY` on the parent |
| `access` / `faccessat` `R_OK` | `FILE_READ_DATA` |
| `access` / `faccessat` `W_OK` | `FILE_WRITE_DATA` |
| `access` / `faccessat` `X_OK` | `FILE_EXECUTE` |

Descriptor-based `file_getattr` and `file_setattr` with `AT_EMPTY_PATH`
retain the open file through the operation and metadata cleanup. A concurrent
close cannot invalidate an operation that has already acquired its file
reference. This also covers unsupported-operation and other error paths.

Reads and writes of the canonical descriptor xattr are denied
unconditionally through the xattr hooks — `security.peios.sd`, or
`system.ntfs_security` on NTFS. All descriptor access goes through
`kacs_get_sd` and `kacs_set_sd`. POSIX ACL xattr writes are denied
unconditionally too, with `EOPNOTSUPP` rather than `EACCES` so that
probe-then-tolerate callers behave sensibly. <a id="cite-facs.use.posix-acl-write-eopnotsupp"></a>

The special-attributes xattr, `security.peios.sattr`, is not raw
storage either: KACS answers reads and writes of it itself, with the
attribute rights above and the value format in [Special
Attributes](</kernel/internals/kacs/file-security/special-attributes.md#trm-3-9-13-1>). The signature xattr, `security.peios.sig`, is governed by
[Binary Signature Verification](</kernel/internals/kacs/executable-trust/signature-verification.md#trm-3-6>).

Path-based attribute reads may be granted through the parent:
a caller who may list a directory may read the attributes of its
entries, as a native open may ([KACS-Native Open](</kernel/internals/kacs/file-security/kacs-native-open.md#trm-3-9-2-8>)).

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

## Directory traversal <a id="cite-facs.use.directory-traversal"></a>

Path resolution checks `FILE_TRAVERSE` on managed directory
components. A token holding `SeChangeNotifyPrivilege` bypasses the
intermediate checks, including on directories whose descriptor is
missing. <a id="cite-facs.use.change-notify-bypasses-traverse"></a>

Explicit changes of the current or root directory are not intermediate
resolution: `chdir()` and `chroot()` take a live `FILE_TRAVERSE` check
on the final directory, and the privilege bypass does not apply
([Privilege Catalogue](</kernel/internals/kacs/privileges/privilege-catalogue.md#trm-3-4-2>)). <a id="cite-facs.use.chdir-chroot-live-check"></a> An ordinary `fchdir()` checks the descriptor's cached mask;
an `O_PATH` `fchdir()` runs live. <a id="cite-facs.use.fchdir-cached-mask"></a>

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

## Watch placement <a id="cite-facs.use.watch-placement"></a>

Placing a watch — `inotify_add_watch()`, `fanotify_mark()` on an
inode, `F_NOTIFY` — is a read of the object by other means: a watch on
a directory reveals the names of its children as they come and go, a
watch on a file reports its activity. Linux gates it on read
permission, but under KACS a bare `MAY_READ` never reaches a
descriptor (read rights are decided at open), so the `path_notify`
hook checks the read-class right live against the object's own
descriptor: `FILE_LIST_DIRECTORY` for a directory, `FILE_READ_DATA`
for anything else. A denial is `EACCES`, and `SeChangeNotifyPrivilege`
does not bypass it — that privilege covers traversal, not reading. <a id="cite-facs.use.watch-change-notify-no-bypass"></a>

Mount, filesystem and mount-namespace marks are not object watches and
have no single descriptor to check. Linux requires `CAP_SYS_ADMIN` for
them, and for the fanotify permission classes (`FAN_CLASS_CONTENT`,
`FAN_CLASS_PRE_CONTENT` — the ones whose holder can veto or delay
opens and reads system-wide); the capability switchboard ([DAC Neutralisation](</kernel/internals/kacs/linux-credentials/dac-neutralisation.md#trm-3-10-2>))
resolves that to `SeTcbPrivilege`, so these are TCB-only. <a id="cite-facs.use.fanotify-mount-marks-tcb"></a> PIP
dominance is not part of the decision: a permission-event holder
intercepts opens of the *object*, never the opening process, and a
holder that is by construction TCB dominates every process anyway.

<a id="trm-3-9-4-5"></a>

## Append-only enforcement <a id="cite-facs.use.append-only-enforcement"></a>

A handle carrying `FILE_APPEND_DATA` but not `FILE_WRITE_DATA` allows
only true append-intent writes. Append intent means the effective
write position is forced to end-of-file by `O_APPEND` or per-I/O
`RWF_APPEND`, and is not negated by `RWF_NOAPPEND` on the same
operation. <a id="cite-facs.use.append-intent-definition"></a> Requesting both `RWF_APPEND` and `RWF_NOAPPEND` together
fails with `EACCES`. <a id="cite-facs.use.append-noappend-conflict-eacces"></a>

Denied on such a handle: positioned writes without effective append
intent — `pwrite64`, `pwritev`, `pwritev2` with an explicit offset,
io_uring writes with an explicit offset, and AIO writes with an
offset; any write using `RWF_NOAPPEND`, since it can negate append
semantics inherited from `O_APPEND`; shared writable `mmap` and
`mprotect` upgrades to `PROT_WRITE`; and the `fallocate` mutation
modes. <a id="cite-facs.use.append-only-denied-set"></a>

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

## fcntl <a id="cite-facs.use.fcntl"></a>

For `F_SETFL`, KACS evaluates the mutable status flags Linux accepts —
`O_APPEND`, `O_NONBLOCK`/`O_NDELAY`, `O_DIRECT`, `O_NOATIME`.
Clearing `O_APPEND` is denied on a handle with `FILE_APPEND_DATA` but
not `FILE_WRITE_DATA`; setting it is always allowed, being a privilege
reduction. <a id="cite-facs.use.setfl-clear-append-denied"></a> Adding `O_NOATIME` requires `FILE_WRITE_ATTRIBUTES` and
clearing it is always allowed. <a id="cite-facs.use.setfl-noatime"></a> Changing only `O_NONBLOCK`, `O_NDELAY`
or `O_DIRECT` needs no KACS right, though ordinary Linux validation
still applies. <a id="cite-facs.use.setfl-flags-need-no-right"></a>

These commands are descriptor-local and require no KACS right, and
none of them widens the cached mask: `F_CREATED_QUERY`; `F_DUPFD`,
`F_DUPFD_CLOEXEC` and `F_DUPFD_QUERY`, which preserve the same file
description and mask; `F_GETFD` and `F_SETFD`; `F_GETFL`; and the
async-notification set `F_GETOWN`, `F_GETOWN_EX`, `F_GETOWNER_UIDS`,
`F_GETSIG`, `F_SETOWN`, `F_SETOWN_EX` and `F_SETSIG`, where Linux pid
and signal validation still applies. <a id="cite-facs.use.fcntl-descriptor-local"></a>

These are object-state queries or mutations, checked against the
cached mask before Linux-specific validation:

| Command | Required right |
|---|---|
| `F_GETLK` / `F_GETLK64` / `F_OFD_GETLK` | Any data right |
| `F_GETLEASE` / `F_GETDELEG` | `FILE_READ_ATTRIBUTES` |
| `F_GETPIPE_SZ` | `FILE_READ_ATTRIBUTES` |
| `F_SETPIPE_SZ` | `FILE_WRITE_ATTRIBUTES` |
| `F_GET_SEALS` | `FILE_READ_ATTRIBUTES` |
| `F_ADD_SEALS` | `FILE_WRITE_ATTRIBUTES` |
| `F_GET_RW_HINT` / `F_GET_FILE_RW_HINT` | `FILE_READ_ATTRIBUTES` |
| `F_SET_RW_HINT` / `F_SET_FILE_RW_HINT` | `FILE_WRITE_ATTRIBUTES` |

Lock, lease and delegation commands — `F_SETLK`, `F_SETLKW`,
`F_SETLK64`, `F_SETLKW64`, `F_OFD_SETLK`, `F_OFD_SETLKW`,
`F_SETLEASE`, `F_SETDELEG` — pass through the fcntl hook so that the
later file-lock hook can enforce them against normalised `F_RDLCK`,
`F_WRLCK` or `F_UNLCK` values. <a id="cite-facs.use.fcntl-lock-passthrough"></a> An unknown lock type fails closed
there.

For `F_NOTIFY`, removing a watch — a zero event mask, ignoring
`DN_MULTISHOT` — requires nothing. Installing one with any known `DN_*`
event requires `FILE_LIST_DIRECTORY`. <a id="cite-facs.use.fcntl-notify-install"></a> Unknown `DN_*` bits on a managed
descriptor fail closed. <a id="cite-facs.use.fcntl-notify-unknown-bits"></a>

Unmanaged descriptors sit outside the handle check entirely, and an
unknown fcntl command on a managed one fails closed. <a id="cite-facs.use.unknown-fcntl-fails-closed"></a>

<a id="trm-3-9-4-7"></a>

## ioctl <a id="cite-facs.use.ioctl-classification"></a>

Known ioctls are classified by required right; an unclassified one is
allowed if the descriptor carries at least one data right. The 32-bit
compat aliases take the same right as their native command, including
`FS_IOC32_GETFLAGS`, `FS_IOC32_SETFLAGS`, `FS_IOC32_GETVERSION`,
`FS_IOC32_SETVERSION` and the compat preallocation commands. <a id="cite-facs.use.ioctl-compat-aliases"></a>

**Descriptor-local**, requiring nothing: `FIOCLEX` and `FIONCLEX`,
which change close-on-exec state; `FIONBIO`, which changes nonblocking
state; and `FIOASYNC`, which changes async notification state with
Linux and fops validation still applying. <a id="cite-facs.use.ioctl-descriptor-local"></a>

**Common VFS:**

| ioctl | Required right |
|---|---|
| `FIBMAP` | `FILE_READ_DATA` |
| `FIGETBSZ` | `FILE_READ_ATTRIBUTES` |
| `FIFREEZE` / `FITHAW` | `FILE_WRITE_ATTRIBUTES` |
| `FITRIM` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_GETFSUUID` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_GETFSSYSFSPATH` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_GETLBMD_CAP` | `FILE_READ_ATTRIBUTES` |

`FIFREEZE`, `FITHAW` and `FITRIM` mutate filesystem operational
state, and Linux's own `CAP_SYS_ADMIN` checks still apply on top. <a id="cite-facs.use.ioctl-freeze-cap-sys-admin"></a>

**File and object:**

| ioctl | Required right |
|---|---|
| `FS_IOC_FIEMAP` | `FILE_READ_DATA` |
| `FIONREAD` | `FILE_READ_DATA` on a regular file; any data right otherwise |
| `FS_IOC_GETFLAGS` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_SETFLAGS` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_GETVERSION` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_SETVERSION` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_RESVSP` / `FS_IOC_RESVSP64` | `FILE_APPEND_DATA` or `FILE_WRITE_DATA` |
| `FS_IOC_UNRESVSP` / `FS_IOC_UNRESVSP64` | `FILE_WRITE_DATA` |
| `FS_IOC_ZERO_RANGE` | `FILE_WRITE_DATA` |
| `FICLONE` / `FICLONERANGE` | `FILE_WRITE_DATA` |
| `FIDEDUPERANGE` | `FILE_WRITE_DATA` |
| `FIOQSIZE` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_FSGETXATTR` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_FSSETXATTR` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_GETFSLABEL` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_SETFSLABEL` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_GET_ENCRYPTION_PWSALT` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_GET_ENCRYPTION_POLICY` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_GET_ENCRYPTION_POLICY_EX` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_SET_ENCRYPTION_POLICY` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_ADD_ENCRYPTION_KEY` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_REMOVE_ENCRYPTION_KEY` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_GET_ENCRYPTION_KEY_STATUS` | `FILE_READ_ATTRIBUTES` |
| `BLKGETSIZE64` | `FILE_READ_ATTRIBUTES` |
| `BLKFLSBUF` | `FILE_WRITE_DATA` |

On directories, `FS_IOC_GETFLAGS` and `FS_IOC_SETFLAGS` take the same
rights as on files. <a id="cite-facs.use.ioctl-flags-on-directories"></a>

Anything unclassified is allowed on any data right. For device nodes,
pipes and sockets, device-specific ioctl semantics are outside FACS
scope: the node's descriptor is the authorization boundary, and
Linux's device-specific validation may still deny. <a id="cite-facs.use.ioctl-device-semantics-out-of-scope"></a>

A pinned inode ([Binary Signature Verification](</kernel/internals/kacs/executable-trust/signature-verification.md#trm-3-6>)) narrows all of this. Every content-, range- or
allocation-mutating ioctl is rejected on one, and so is every ioctl
the classifier does not recognise — unknown ioctls fail closed there
rather than falling back to the data-right rule.

<a id="trm-3-9-4-8"></a>

## Execution <a id="cite-facs.use.execution"></a>

Execution is nominally a two-layer check. The **mode execute bit** is
the prerequisite meaning "this file is a program", set by package
managers and `chmod +x`, applying to `execve` and `execveat` but not
to `mmap(PROT_EXEC)`. The **descriptor's `FILE_EXECUTE`** is the
access control, gating both.

KACS enforces only the second. Nothing in the kernel module tests the
execute mode bit; the prerequisite survives because Linux's own
`generic_permission()` refuses `MAY_EXEC` on a file with no execute
bit set, by way of `capable_wrt_inode_uidgid(CAP_DAC_OVERRIDE)`. <a id="cite-facs.use.exec-mode-bit-from-linux"></a> The
`+x` requirement is therefore a Linux DAC property that KACS inherits
rather than a FACS rule, and it is one of the few decisions where mode
bits still matter ([DAC Neutralisation](</kernel/internals/kacs/linux-credentials/dac-neutralisation.md#trm-3-10-2>)).

For descriptor-based exec — `execveat` with `AT_EMPTY_PATH`, including
on `O_PATH` handles — a live AccessCheck for `FILE_EXECUTE` runs
against the re-opened file rather than the cached mask being consulted. <a id="cite-facs.use.execveat-live-check"></a>

---

# Descriptor storage and caching

_Peios Kernel / Internals / KACS / File security_

> Descriptor storage and caching: behaviour and implementation of the Peios kernel.

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

<a id="trm-3-9-5-1"></a>

## Xattr protection <a id="cite-facs.storage.xattr-protection"></a>

FACS intercepts every raw xattr operation on the canonical descriptor
xattr — `security.peios.sd`, or `system.ntfs_security` on NTFS — and
denies all three directions. An NTFS inode with no `$Secure` entry,
whose descriptor is an inline attribute the driver never reads, counts
as carrying no descriptor: the mount's missing-descriptor policy
decides for it, as it does for a file with no `security.peios.sd`.

**Writes** are denied: all modification goes through the set-security
interface. **Removal** is denied: a descriptor is never detached from
a file. And **reads** are denied, which is the least obvious of the
three and the most important. <a id="cite-facs.storage.xattr-read-denied"></a> The raw xattr holds the entire
descriptor including the SACL, so allowing a read under
`READ_CONTROL` alone would leak SACL content that properly requires
`ACCESS_SYSTEM_SECURITY`. All reads go through `kacs_get_sd`, which
distinguishes the two.

<a id="trm-3-9-5-2"></a>

## Caching

A validated, parsed descriptor object is cached in the inode's LSM
blob, holding immutable self-relative bytes together with a
prevalidated component layout — enough for AccessCheck readers never
to reparse untrusted storage bytes. <a id="cite-facs.storage.cache-parsed-in-inode-blob"></a>

**Readers** on the AccessCheck path use the RCU-published pointer.
Once a current entry exists, a reader does not take the inode mutex
merely to run AccessCheck. <a id="cite-facs.storage.readers-rcu-no-mutex"></a> It either completes the evaluation inside
an RCU read-side critical section, or pins the object with a refcount
while still under RCU and drops the RCU lock before doing anything
that can allocate, sleep or emit an audit event. A pin is acquired
with a non-zero refcount check and dropped afterwards.

**Writers** allocate a new object, swap the pointer atomically, and
free the old one after a grace period and after reader pins have
drained. <a id="cite-facs.storage.writers-rcu-swap"></a> No partial read is possible.

**Population** is lazy, on first access. The xattr is read through an
internal kernel path that bypasses the read-denial hook, and the
parsed result is installed by compare-and-swap; a thread that loses
the race frees its own copy. <a id="cite-facs.storage.population-lazy-cas"></a>

Both native and legacy open finish descriptor-cache resolution before
acquiring the central access policy (CAAP) cache mutex. Resolution can take
an inode security mutex, while set-security takes that inode mutex before
CAAP; acquiring them in the opposite order could deadlock an open against a
descriptor update. <a id="cite-facs.storage.open-resolves-before-caap"></a> Open retains a pin on the immutable descriptor
selected by that resolution, before releasing the protection used to select
it. The pin survives the subsequent CAAP wait and access check. Clearing or
replacing the inode's cache after selection cannot by itself cause a spurious
denial or change which descriptor this open evaluates; a later open resolves
again and can select the replacement. A missing or corrupt selected entry
still fails closed. <a id="cite-facs.storage.open-pins-selected-descriptor"></a>

Live file access checks, executable integrity-label reads, descriptor queries,
and copy-up descriptor reads also retain the immutable entry selected during
resolution until they finish evaluating or copying it. This includes the
inode-only descriptor read used by stacking filesystems. Invalidation after
selection cannot alone cause a refusal or substitute a different descriptor;
the next operation resolves again. A selected missing or corrupt descriptor
still fails closed even if another thread repairs the cache before the reader
finishes. <a id="cite-facs.storage.readers-pin-selected-descriptor"></a>

CAAP is evaluated under its own, later cache lock; the descriptor selection
and CAAP evaluation are not an atomic snapshot of both policies. The inode
mutex is not held for the access check, and CAAP is not held across lazy
descriptor population.

**Eviction** frees the cached descriptor when the inode is evicted,
through an RCU-safe callback with the same pin draining, so in-flight
permission checks complete before the object goes away. <a id="cite-facs.storage.eviction-rcu-safe"></a>

**Invalidation** happens on write, but not atomically with it. The
set-security path deliberately releases the inode security lock across
the xattr write and re-acquires it afterwards to publish the new
parsed object, because holding it across the write would invert the
`i_rwsem` ordering the access path requires. <a id="cite-facs.storage.setsd-releases-lock-across-write"></a> Two concurrent
set-security calls on one inode are therefore last-writer-wins rather
than serialised end to end, and there is a window in which the xattr
and the cache disagree. <a id="cite-facs.storage.concurrent-setsd-last-writer-wins"></a> Readers are never blocked, and no reader sees
a partially written object — the exposure is which of two racing
writes lands, not a torn state.

Invalidation is also driven from the **other end**, by the write
itself: any canonical descriptor xattr landing on an inode drops that
inode's cached entry, whoever wrote it and by whatever path. <a id="cite-facs.storage.xattr-write-drops-cache"></a> The
set-security path above then publishes the new parsed object as usual;
for anything else, the next reader re-reads the authoritative bytes.

This is keyed on the xattr rather than on the writer, because the
writer is not always the one holding the cache. A descriptor set
through a stacking filesystem reaches **two** inodes — the one the
caller named, and the real one beneath, which the write is re-entered
on. <a id="cite-facs.storage.stacking-two-inodes"></a> Only the first is refreshed by the set-security path. The second
is not merely cold: a stacking filesystem resolves and caches
descriptors during its own metadata work on an inode it has just
created, so it can hold an entry from the moment the object existed
and keep serving it after the xattr underneath has changed. Keying on
the xattr closes that without either side needing to know the other is
there.

<a id="trm-3-9-5-7"></a>

## Missing descriptors <a id="cite-facs.storage.deny-missing-denies"></a>

Under **`facs_deny_missing`**, no descriptor means deny. Two
exceptions keep the repair path open. `SeChangeNotifyPrivilege`
bypasses intermediate traverse checks including on directories with no
descriptor, though not explicit `chdir()`, `chroot()` or `fchdir()`
use-time checks. And `O_PATH` opens bypass the open hook entirely, so
a file with a missing descriptor can still be acquired as an `O_PATH`
reference — which is exactly the repair route: `open(path, O_PATH)`
then `kacs_set_sd` with `AT_EMPTY_PATH` under `SeRestorePrivilege`. <a id="cite-facs.storage.missing-repair-route"></a>

Under the **synthesise classes**, a missing descriptor is generated
from two sources in order. <a id="cite-facs.storage.synthesis-order"></a> First, **inheritance from the parent**: if
the parent has one, the inheritance algorithm runs as though a new
file were being created. Otherwise the **mount-level template**,
applied where there is no parent descriptor — typically only at the
mount root. With no template configured, the fallback grants
`GENERIC_ALL` to SYSTEM and `BUILTIN\Administrators` and
`GENERIC_READ | GENERIC_EXECUTE` to Everyone, owned by SYSTEM with
SYSTEM as group. <a id="cite-facs.storage.synthesis-fallback-descriptor"></a>

Because these files already exist, the accessor is not their creator.
Where inheritance needs creator inputs — owner, primary group, default
DACL — a synthetic system-policy creator supplies them: the template's
owner, group and DACL if one exists, the fallback's otherwise. **The
accessor's token never affects the synthesised descriptor**, and the
synthesis path takes no subject token at all. <a id="cite-facs.storage.synthesis-ignores-accessor"></a>

Inheritance is recursive — a parent whose own descriptor is missing is
synthesised first, walking toward the mount root where the template
terminates it. <a id="cite-facs.storage.synthesis-recursive"></a> The walk is bounded at 32 ancestor levels; a target
nested deeper than that below the nearest resolvable ancestor fails
closed with `EACCES` rather than synthesising. <a id="cite-facs.storage.synthesis-depth-limit"></a>

Resolution does not nest FACS inode locks. It releases the current inode's
lock before resolving an ancestor or calling the filesystem's descriptor
xattr handler, which may itself resolve a lower inode in a stacked
filesystem. Referenced dentries and immutable descriptor-cache entries keep
the inputs alive across that work. <a id="cite-facs.storage.resolution-no-nested-inode-locks"></a>

Before publishing the result, resolution reacquires the inode lock and
checks both the mount-policy generation and the inode's cache mutation
sequence. An explicit replacement or invalidation makes it discard the
obsolete result and retry, including when an empty cache was populated and
cleared or invalidated while still empty. Ordinary cached files also retry
a competing reader publication, then use the current entry. A failed reread
never makes an entry from an old policy generation current again.
<a id="cite-facs.storage.resolution-revalidates-unlocked-work"></a>

StrataFS re-reads the current provider descriptor on every check, including
when an earlier result was missing or corrupt. Concurrent reader publication
does not restart these reads: without an explicit invalidation or policy
change, N checks perform N descriptor reads (each may query size and then
bytes). A reader may reuse a result published by another reader whose read
began later than its own; an older read cannot overwrite that later result,
including a missing or corrupt result. Its own read error is still returned.
Explicit writes and policy changes continue to trigger revalidation and may
require another read. This does not alter the fixed deny-missing policy or a
handle's frozen grant. <a id="cite-facs.storage.stratafs-read-contention"></a>

An **ephemeral** synthesis is cached in the inode blob only and never
written back, leaving the original filesystem unmodified. <a id="cite-facs.storage.ephemeral-not-written-back"></a> A
**persistent** one is additionally written to the xattr so the medium
acquires durable descriptors — but never inline. <a id="cite-facs.storage.persistent-written-back"></a>

<a id="trm-3-9-5-8"></a>

## Deferred write-back <a id="cite-facs.storage.write-back-deferred"></a>

Writing the xattr takes the inode's `i_rwsem`. Synthesis may be reached
from a metadata operation whose VFS caller already holds that lock, so
inline write-back would self-deadlock even though resolution releases its
FACS inode lock around parent resolution and xattr reads. Write-back
therefore runs with no FACS or VFS lock held.

Synthesis caches the descriptor immediately and marks the entry
pending. <a id="cite-facs.storage.synthesis-marks-pending"></a> The access decision is correct from that cached value the
instant synthesis completes — correctness never depends on the xattr
reaching disk. The write-back runs later from a task-work callback
firing as the triggering syscall returns to userspace, so a persistent
descriptor is normally on disk by the time the operation that first
observed it missing returns. <a id="cite-facs.storage.write-back-task-work"></a>

A pending entry is generation-tagged exactly like an ephemeral one, so
a policy or template change before the write-back discards it and
re-synthesises; a stale pre-change descriptor is never pinned to disk.

Write-back is best-effort, and can be because the synthesised
descriptor is a deterministic function of the parent or the template —
the on-disk xattr is a cache of a recomputable value, not unique
state. If it does not happen, because the entry was evicted or the
task exited first, the identical descriptor is re-synthesised on next
access and retried. A failed or skipped write-back never fails the
operation that triggered synthesis. <a id="cite-facs.storage.write-back-best-effort"></a> Kernel threads, and a failure to
queue the callback, fall back to re-synthesis the same way.

Once written, the cached entry becomes an ordinary xattr-backed
descriptor: durable, no longer generation-tagged, never synthesised
again, and owed no further write-back. <a id="cite-facs.storage.written-back-becomes-ordinary"></a>

An ancestor synthesised only to supply inheritance inputs for a
descendant is itself pending, and persists under the same rules when
it is next accessed in its own right. <a id="cite-facs.storage.ancestor-also-persists"></a>

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

## Corrupt descriptors <a id="cite-facs.storage.corrupt-fails-closed"></a>

A descriptor xattr that exists but fails structural validation is
corrupt, and the policy is fail-closed: deny all access, do not call
AccessCheck, and never treat a truncated DACL as an empty one.

Every encounter emits an audit event, fired exactly once per inode per
cache population rather than per access, so a hot corrupt inode does
not flood the log. <a id="cite-facs.storage.corrupt-audit-once-per-population"></a>

Recovery is a process holding `SeRestorePrivilege` calling
set-security to overwrite it. Offline repair tools can also rewrite
xattrs directly on an unmounted filesystem.

<a id="trm-3-9-5-10"></a>

## NFS client mounts <a id="cite-facs.storage.nfs-dual-authority"></a>

NFS is the one managed class where the sole-authority guarantee does
not hold. The server enforces its own access control independently:
FACS evaluates locally against a synthesised descriptor, and the
server may deny I/O that FACS allowed. A locally authorized `open()`
can therefore produce a descriptor whose `read()` calls fail. This is
inherent to network filesystems with server-side enforcement, and
nothing suppresses the server's denial.

## Related explanations

- [Mount classes and bootstrap descriptors](</kernel/internals/kacs/file-security/mount-classes-and-bootstrap-descriptors.md>)

---

# Mount classes and bootstrap descriptors

_Peios Kernel / Internals / KACS / File security_

> Mount classes and bootstrap descriptors: behaviour and implementation of the Peios kernel.

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

## Mount policy classes

The superblock policy object carries the class ([The Handle Model](</kernel/internals/kacs/file-security/the-handle-model.md#trm-3-9-1>)) and, for
synthesise-class mounts, an optional mount-level default template.

The default classifier maps from the superblock's filesystem magic.
`PROC_SUPER_MAGIC` and `SYSFS_MAGIC` are **unmanaged**: these expose
kernel state through inode-shaped handles with no on-disk identity and
no descriptor to consult. <a id="cite-facs.storage.proc-sysfs-unmanaged"></a> `NULL_FS_MAGIC` is unmanaged too — nullfs is
the immutable, permanently empty filesystem the kernel mounts as the
mount-namespace root, with the mutable rootfs mounted on top of it. It
declares no xattr support at all, so it can never carry a descriptor,
and its single root inode is immutable and childless: nothing to stamp
and nothing to protect. <a id="cite-facs.storage.nullfs-unmanaged"></a>

`STRATAFS_SUPER_MAGIC` is fixed at **`facs_deny_missing`** for the
superblock's lifetime, because StrataFS delegates every check to
current provider objects and must never synthesise a descriptor for
its merged namespace. <a id="cite-facs.storage.stratafs-fixed-deny-missing"></a> An attempt to change it fails with
`EOPNOTSUPP`.

`RAMFS_MAGIC`, `NFS_SUPER_MAGIC`, `MSDOS_SUPER_MAGIC`,
`EXFAT_SUPER_MAGIC`, `ISOFS_SUPER_MAGIC` and `CGROUP2_SUPER_MAGIC` are
**`facs_synthesize_ephemeral`** — either no persistent backing at all,
or storage with no native descriptor slot. <a id="cite-facs.storage.ephemeral-magics"></a>

Everything else, including `TMPFS_MAGIC`, `SQUASHFS_MAGIC`,
`EXT4_SUPER_MAGIC` and `BTRFS_SUPER_MAGIC`, defaults to
**`facs_deny_missing`**. <a id="cite-facs.storage.default-deny-missing"></a> These can all carry the descriptor xattr
natively and are expected to on every inode that participates in
access checks.

`TMPFS_MAGIC` covers both userspace tmpfs mounts and the kernel-mounted
instances established before any userspace runs. The latter are not
exempt from the default; they are handled by seeding.

<a id="trm-3-9-5-4"></a>

## Kernel-internal mounts <a id="cite-facs.storage.kernel-internal-mounts"></a>

Two filesystems are mounted by the kernel before any userspace process
exists and before anything can call `kacs_set_mount_policy` or
`kacs_set_sd`: the mutable root filesystem mounted by
`init_mount_tree`, a tmpfs mounted on top of the immutable nullfs
namespace root and made `/` by `set_fs_root`; and the devtmpfs
instance mounted by `devtmpfs_init` and populated by the `kdevtmpfs`
thread.

Both are `TMPFS_MAGIC` and therefore `facs_deny_missing`, and their
root inodes are kernel-created, never passing through a
userspace-supplied artifact, so they carry no descriptor at the moment
they become reachable. To make the class viable the kernel seeds one.

The mutable root filesystem is a tmpfs whatever the command line says.
<a id="cite-facs.storage.rootfs-always-tmpfs"></a> Upstream Linux makes it a ramfs
when the command line carries `root=`, or a `rootfstype=` that does not
name tmpfs, and ramfs stores no extended attributes: the seed below
would have nowhere to go, nothing the boot archive unpacks would
inherit a descriptor, and StrataFS, which reads a provider's stored
descriptor and never a synthesised one, would refuse every view an
initramfs mounts over it. An installed system always boots with
`root=`, so the upstream rule is not followed.

The rootfs root is seeded inside `init_mount_tree`, immediately after
`vfs_kern_mount` returns and before the mount is published into
`init_mnt_ns`, with the inode's `i_rwsem` held. <a id="cite-facs.storage.rootfs-seed-timing"></a> The devtmpfs root is
seeded inside `devtmpfs_init`, after `vfs_kern_mount` and before
`kdevtmpfs` starts, likewise under `i_rwsem`. <a id="cite-facs.storage.devtmpfs-seed-timing"></a> The nullfs root is not
seeded — it is unmanaged, empty, and incapable of xattr storage. <a id="cite-facs.storage.nullfs-not-seeded"></a>

A rootfs seed that fails panics the kernel. <a id="cite-facs.storage.rootfs-seed-failure-is-fatal"></a>
A boot that went on without it would fail later, in whatever first
reached the initramfs through a StrataFS view, with nothing to connect
the refusal to its cause.

The seeded descriptor is byte-for-byte identical in both places: owner
and group SYSTEM (`S-1-5-18`), a DACL of one `ACCESS_ALLOWED` ACE
granting `GENERIC_ALL` to SYSTEM flagged
`OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE` so that inheritance
derives a child descriptor for every inode created on the mount
afterwards, and no SACL. <a id="cite-facs.storage.seeded-descriptor-contents"></a>

The writes go through the kernel-internal xattr path, bypassing both
the FACS denial hooks and the LSM setxattr permission hook. <a id="cite-facs.storage.seed-writes-bypass-hooks"></a> They
consult no token — at the point either runs there may be no meaningful
subject — and the seeded descriptor is the sole authority for the
mount until trusted userspace replaces it. They depend on nothing
beyond the LSM scaffold that allocates inode and superblock blobs.

These are not exempt from later management: trusted userspace can
overwrite the per-inode descriptor or change the superblock's class
once it holds the privileges. <a id="cite-facs.storage.seeded-mounts-still-manageable"></a>

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

## Boot artifacts <a id="cite-facs.storage.boot-artifacts-not-seeded"></a>

A filesystem shipped as a boot artifact — a squashfs concatenated into
the initrd, a vendor squashfs delivered as a package, a flashed
partition image — defaults to `facs_deny_missing` and the kernel does
**not** seed it. These are already-populated trees the kernel cannot
extend at mount time, and in the read-only case cannot extend at all.

The obligation falls on the build pipeline, which emits
`security.peios.sd` on every inode ordinary access checks will reach.
`mksquashfs`, the ext utilities and the standard userland xattr
surfaces all preserve `security.*` natively.

An artifact without descriptors is a packaging defect. FACS treats
every missing descriptor on a `facs_deny_missing` mount as a
corruption indicator and denies. The operator path is to rebuild the
artifact, or to adopt the superblock under a synthesise class.

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

## Administration <a id="cite-facs.storage.set-mount-policy"></a>

The privilege gate below is verified in kernel source
[`8e0e22de3a59cad506bbbf8873de456e16ad272d`](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/capability.c#L613-L637),
including its use by both [set](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/mount_policy.c#L369-L380)
and [get](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/mount_policy.c#L479-L496). This is source-level
verification, not a deployed-kernel test or a historical release boundary.

Trusted userspace adopts a mounted filesystem by calling
`kacs_set_mount_policy` on a descriptor naming any object on the
target superblock; `O_PATH` descriptors are valid targets. The change
applies to the superblock, not the pathname used to reach it.

Setting a policy is volume management: the call requires
`SeManageVolumePrivilege` or `SeTcbPrivilege`, enabled, and must
successfully mark the enabled privilege as used; `kacs_get_mount_policy`
is gated the same way. <a id="cite-facs.storage.set-mount-policy-privilege"></a> Every change writes a
`kacs.mount.policy.changed` record ([Audit Event Schemas](</kernel/internals/kacs/auditing/event-families-and-delivery.md#trm-3-c>)), whose subject is the caller
and which names the filesystem's type, the policy set
(`object.mount.policy`), the one it replaced
(`object.mount.policy-previous`) and the new generation
(`object.mount.policy-generation`). Every refusal is decided before the
change, so a record is always of a change made; the template is not
carried. <a id="cite-facs.storage.set-mount-policy-recorded"></a> The
public ABI accepts only the three managed classes; `unmanaged`,
unknown values, nonzero reserved flags and malformed arguments all
fail closed. <a id="cite-facs.storage.set-mount-policy-input-validation"></a> The one
policy the kernel sets on its own initiative is for a tmpfs that a token
without the privilege brought into being inside its own mount namespace,
which is stamped `synth-ephemeral` with a creator-owned template at
`sb_kern_mount` ([A Private Mount Table](</kernel/internals/kacs/mount-namespaces/a-private-mount-table.md#trm-3-13-1>)).

The optional template is accepted only with a synthesise class. <a id="cite-facs.storage.template-requires-synthesise"></a> It is
a complete self-relative descriptor rather than a subset, passes
structural validation, and is at most 65535 bytes. <a id="cite-facs.storage.template-validation"></a> A null pointer with
zero length clears it. <a id="cite-facs.storage.template-null-clears"></a> Setting `facs_deny_missing` clears it and
rejects non-empty template input. <a id="cite-facs.storage.deny-missing-clears-template"></a> Pointer and length mismatches and
invalid bytes fail before any state changes.

Policy changes are **lazy**. They do not walk the filesystem and do
not stamp anything. <a id="cite-facs.storage.policy-change-lazy"></a> The superblock carries a monotonic generation
counter, incremented on every successful policy or template
replacement. <a id="cite-facs.storage.generation-counter"></a> Missing-descriptor, ephemeral-synthetic and
not-yet-written-back persistent-synthetic cache entries record the
generation they came from and are discarded and repopulated when it
changes. <a id="cite-facs.storage.generation-discards-synthetic"></a> Xattr-backed and corrupt-descriptor caches are not made valid
by a policy change, and open file descriptions keep their immutable
masks. <a id="cite-facs.storage.policy-change-keeps-xattr-caches"></a>

---

# The Set-Security Interface

_Peios Kernel / Internals / KACS / File security_

> The single syscall all descriptor modification flows through — ownership, integrity labels, the SeRestorePrivilege bypass and mandatory attributes.

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

All descriptor modification flows through one syscall. The caller
provides a file descriptor or path, a bitmask naming which components
to modify, and a self-relative descriptor blob carrying the new
values.

| Flag | Component | Required right |
|---|---|---|
| `OWNER_SECURITY_INFORMATION` | Owner SID | `WRITE_OWNER` <a id="cite-facs.set-sd.owner-requires-write-owner"></a> |
| `GROUP_SECURITY_INFORMATION` | Group SID | `WRITE_OWNER` |
| `DACL_SECURITY_INFORMATION` | Discretionary ACL | `WRITE_DAC` <a id="cite-facs.set-sd.dacl-requires-write-dac"></a> |
| `SACL_SECURITY_INFORMATION` | System ACL | `ACCESS_SYSTEM_SECURITY` <a id="cite-facs.set-sd.sacl-requires-access-system-security"></a> |
| `LABEL_SECURITY_INFORMATION` | Mandatory integrity label | `WRITE_OWNER`, plus the integrity constraints below <a id="cite-facs.set-sd.label-requires-write-owner"></a> |

The blob is validated structurally — parseable, well-formed ACEs,
valid SIDs, at most 65535 bytes. With an existing valid file security descriptor,
only the indicated components are merged into it. Unindicated components
are preserved unchanged. <a id="cite-facs.set-sd.merge-preserves-unindicated"></a>

The input is always one self-relative descriptor subset, never a raw
SID or ACL fragment. `SACL_SECURITY_INFORMATION` and
`LABEL_SECURITY_INFORMATION` cannot be combined in one call, because
both target the SACL field with incompatible meanings; the pair fails
with `EINVAL`. <a id="cite-facs.set-sd.sacl-label-exclusive"></a>

A `SACL_SECURITY_INFORMATION` write replaces the object's **entire**
SACL. <a id="cite-facs.set-sd.sacl-write-replaces-all"></a> A `LABEL_SECURITY_INFORMATION` write interprets the input SACL
as the label subset only: no SACL component removes the explicit
mandatory label and returns the object to the default unlabelled
state; a present SACL contains exactly one non-inherit-only
`SYSTEM_MANDATORY_LABEL_ACE` and nothing else; and the object's
non-label SACL ACEs are preserved. <a id="cite-facs.set-sd.label-write-subset"></a>

After merging, the result still has a non-null owner — the group SID
may be null — and a merge that would leave no owner fails. <a id="cite-facs.set-sd.owner-must-remain"></a>

MIC and PIP apply to these checks. A low-integrity caller cannot
modify a high-integrity file's descriptor even where the DACL grants
`WRITE_OWNER`. <a id="cite-facs.set-sd.mic-pip-apply"></a>

A read-only mount withholds the write along that path whatever the
descriptor grants: the call fails with `EROFS`, as every modifying
operation through a read-only bind does, and the descriptor stays
writable through any writable path to the same object. The mount is
consulted after the access check, so a caller the descriptor refuses
sees the denial rather than a read-only error that would confirm the
object exists. <a id="cite-facs.set-sd.read-only-mount-erofs"></a>

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

## Component merging and replacement

For a file whose cached descriptor is valid, [the C dispatcher](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/sd_access.c#L197-L255) selects the merge path. The [control-bit merge](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/token_runtime.rs#L4232-L4264) starts from the destination control value and replaces these bits from the input when their component is selected:

| Selected component | Replaced control bits |
|---|---|
| Owner | `OWNER_DEFAULTED` |
| Group | `GROUP_DEFAULTED` |
| DACL | `DACL_DEFAULTED`, `DACL_TRUSTED`, `DACL_AUTO_INHERIT_REQ`, `DACL_AUTO_INHERITED`, `DACL_PROTECTED` |
| Full SACL | `SACL_DEFAULTED`, `SACL_AUTO_INHERIT_REQ`, `SACL_AUTO_INHERITED`, `SACL_PROTECTED` |

This copies more than ACE lists, but is not byte-identical descriptor replacement. If group is not selected, [the destination group remains](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/token_runtime.rs#L4347-L4351). The [resource-manager control byte remains the destination's](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/token_runtime.rs#L4410-L4416), as does its `RM_CONTROL_VALID` state. A label-only merge does not replace the full-SACL control-bit set in the table.

A missing or invalid cached file security descriptor does **not** take that merge path. The dispatcher requires enabled `SeRestorePrivilege` and calls the [replacement builder](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/token_runtime.rs#L4420-L4468), which requires owner, group and DACL selections and validates the supplied owner and label. Do not apply valid-descriptor field-retention guarantees to that repair case.

These details are source-checked against kernel commit [`8e0e22de`](https://github.com/peios/pkm/tree/8e0e22de3a59cad506bbbf8873de456e16ad272d), not a runtime-validated restore procedure.

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

## Generic rights <a id="cite-facs.set-sd.generic-rights-mapped"></a>

Generic rights in a written DACL or SACL are mapped to file rights
before the descriptor is stored, as they are when a file is created.
An ACE that applies to the file has `GENERIC_READ`, `GENERIC_WRITE`,
`GENERIC_EXECUTE` and `GENERIC_ALL` replaced by the file rights they
stand for. An ACE that applies to the file and is also inherited is
split into a mapped ACE for the file and an inherit-only copy that
keeps the generic rights for the children it will reach. Inherit-only
ACEs are stored as given. A descriptor therefore reads back the same
whether it was supplied at creation, inherited, or set afterwards
([The DACL Walk](</kernel/internals/kacs/access-check/the-dacl-walk.md#trm-3-8-2-2>)).

The same rule applies to every object type with a set path —
registry keys, processes, tokens, System V IPC objects and the rest —
each through its own GenericMapping.

A descriptor change breaks other holders' handle caching on the file
([Leases](</kernel/internals/kacs/file-security/leases.md#trm-3-9-12-3>)).

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

## Ownership <a id="cite-facs.set-sd.ownership"></a>

A new owner may be set only to the caller's own SID, or to a group SID
on the token carrying `SE_GROUP_OWNER`. `SeTakeOwnershipPrivilege`
allows setting ownership to the caller's own SID regardless of what
the current descriptor says, and `SeRestorePrivilege` allows any
arbitrary SID. <a id="cite-facs.set-sd.take-ownership-and-restore"></a>

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

## Integrity labels <a id="cite-facs.set-sd.label-level-constraint"></a>

Without enabled `SeRelabelPrivilege` a caller may set a label only at or below
its own integrity level; with it, the label-level check permits any level.
Other access and validation checks still apply.

The constraint applies through **both** paths — the dedicated label
subset, and a label ACE embedded in a full SACL write. A SACL write
whose ACL contains a mandatory label ACE raising integrity above the
caller's level requires `SeRelabelPrivilege` exactly as the label path
does, even though the SACL component itself is gated only by
`ACCESS_SYSTEM_SECURITY`. <a id="cite-facs.set-sd.label-constraint-via-sacl"></a>
`SeSecurityPrivilege` or `SeRestorePrivilege` alone is not sufficient for
a label above the caller's integrity: the [label-assignment check](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/token_runtime.rs#L4180-L4197) independently requires enabled
`SeRelabelPrivilege`.

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

## The SeRestorePrivilege bypass

`SeRestorePrivilege` fires inside the AccessCheck pipeline, so it
bypasses the check only where `kacs_set_sd` runs a **live** one: an
`O_PATH` descriptor with `AT_EMPTY_PATH`, a pidfd, a token descriptor
with `AT_EMPTY_PATH`, or a path. <a id="cite-facs.set-sd.restore-bypass-live-only"></a> On those paths it grants every
requested right, `WRITE_OWNER`, `WRITE_DAC` and
`ACCESS_SYSTEM_SECURITY` included.

Called on an ordinary file descriptor the required rights are checked
against the cached mask instead, no AccessCheck runs, and the
privilege has no effect at all. <a id="cite-facs.set-sd.restore-no-effect-on-fd"></a> A caller needing the bypass has to use
the `O_PATH` route — which is the mechanism behind backup restoration,
administrative repair, and the missing-descriptor repair path
([File Descriptor Storage](</kernel/internals/kacs/file-security/descriptor-storage-and-caching.md#trm-3-9-5>)).

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

## Mandatory resource attributes <a id="cite-facs.set-sd.mandatory-attribute-requires-tcb"></a>

When a caller modifies the SACL, the existing and new SACLs are
compared for changes to `SYSTEM_RESOURCE_ATTRIBUTE_ACE` entries. An
existing attribute carrying `CLAIM_SECURITY_ATTRIBUTE_MANDATORY`
(0x0020) cannot be removed, nor its values modified, without
`SeTcbPrivilege` — and an attempt without it fails the entire call
rather than silently dropping the change.

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

## Write mechanics

The updated descriptor is serialised to self-relative binary form and
written to the xattr through an internal kernel path bypassing the
denial hook, and the in-memory cache is updated. <a id="cite-facs.set-sd.write-bypasses-denial-hook"></a> An audit event is
emitted if the file's SACL carries a matching audit ACE. <a id="cite-facs.set-sd.audit-on-matching-ace"></a>

The cache update is not atomic with the xattr write; [File Descriptor Storage](</kernel/internals/kacs/file-security/descriptor-storage-and-caching.md#trm-3-9-5>) describes
the lock ordering that forces this and the last-writer-wins window it
produces.

---

# Sharing and Deletion

_Peios Kernel / Internals / KACS / File security_

> NT share modes enforced for every process, delete-pending files, deletion and renaming through an open handle, and pinning a file's ancestors.

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

KACS keeps NT's sharing and deletion rules in the kernel, for every
process. An open says which kinds of access it lets other opens have at
the same time. A file can be marked for deletion through any open that
holds `DELETE`, and is removed when the last open of it closes. Deletion
and renaming can be done through an open handle rather than by name.

These rules apply to regular files and directories on FACS-managed
mounts. <a id="cite-facs.share.scope"></a> They do not apply to device nodes, FIFOs, sockets or symbolic
links, to unmanaged mounts such as `/proc`, `/sys` and nullfs, or to
`O_PATH` descriptors, which take no part in share checks.

<a id="trm-3-9-10-1"></a>

## Share modes <a id="cite-facs.share.check"></a>

The rules are those of MS-FSA 2.1.5.1.2.1 and 2.1.5.1.2.2. Access falls
into three classes:

| Class | Rights | Share bit that admits it |
|---|---|---|
| Read | `FILE_READ_DATA`, `FILE_EXECUTE` | `FILE_SHARE_READ` |
| Write | `FILE_WRITE_DATA`, `FILE_APPEND_DATA` | `FILE_SHARE_WRITE` |
| Delete | `DELETE` | `FILE_SHARE_DELETE` |

An open whose granted access contains none of these rights takes no part
in share checking: it neither conflicts with other opens nor constrains
them. <a id="cite-facs.share.attribute-only-opens"></a> Opening for attributes or for the security descriptor is
always possible, whatever other opens deny.

An open that does take part conflicts with an existing open, and fails
with `EBUSY`, when either of them holds access of a class the other
does not share. <a id="cite-facs.share.conflict-both-ways"></a> A native open is judged by the access it was
**granted**, not what it asked for, so a `MAXIMUM_ALLOWED` open is
judged by what it received. A native open reports the conflict as
`KACS_STATUS_SHARING_VIOLATION`. A successful open registers its access
and share mode until it closes.

**Legacy opens take part.** A plain `open(2)` shares all three classes,
so legacy opens never conflict with each other. A legacy open is judged
by its mode instead of its granted mask, because its mask carries
optional compat rights it may never use: a readable open, file or
directory, holds the read class, and a writable one the write class.
<a id="cite-facs.share.legacy-opens"></a> A legacy open of a file another
open has denied to its class fails with `EBUSY`, as a native open does.

**A running program takes part.** Executing a file holds it as an open
with read access that shares read and delete but not write. This is the
NT form of Linux's refusal to write a running executable, which still
applies first, with `ETXTBSY`. A program can be replaced by renaming a
new file over its name while it runs. <a id="cite-facs.share.exec"></a>

An open's share registration lasts as long as its open file
description. A memory mapping holds the description, so a mapped file
keeps its registration after its descriptor is closed, until it is
unmapped.

<a id="trm-3-9-10-2"></a>

## Denying only what you could do yourself <a id="cite-facs.share.deny-limits"></a>

Share modes would let any reader lock others out of a file, such as a
system configuration file it can only read. KACS limits each denial to
what the opener could do itself. Where an open omits a share bit it is
not entitled to deny, that bit is silently set, and the open proceeds as
if it had shared it.

- **Denying read** follows MS-FSA. It takes effect only if the opener
  has `FILE_WRITE_DATA` on the parent directory (2.1.5.1.2.2). On the
  first open of a directory it also needs the generic write rights on
  the directory itself (2.1.5.1.2). <a id="cite-facs.share.deny-read"></a>
- **Denying write** takes effect only if the opener's descriptor grants
  it `FILE_WRITE_DATA` or `FILE_APPEND_DATA` on the object. <a id="cite-facs.share.deny-write"></a>
- **Denying delete** takes effect only if the opener could delete the
  object: `DELETE` on it, or `FILE_DELETE_CHILD` on its parent. <a id="cite-facs.share.deny-delete"></a>

These decide whether the opener *could* exercise the right, not
whether it asked to. Each is an AccessCheck against the current
descriptor, made only for an open that omits the corresponding share
bit. An open that shares everything, which includes every legacy open,
costs nothing extra.

<a id="trm-3-9-10-7"></a>

## Overriding share modes <a id="cite-facs.share.override"></a>

Backup and restore tools have to read and replace files that others
hold open. A native open's backup and restore intents
([Privilege-Based Grants](</kernel/internals/kacs/privileges/the-privilege-model.md>)) also let it set aside other opens'
denials:

- backup intent with `SeBackupPrivilege` enabled ignores other opens'
  denial of read;
- restore intent with `SeRestorePrivilege` enabled ignores other opens'
  denial of write and delete.

The override skips only the share check. Lease breaks still happen, so
a client caching the file flushes first. The overriding open's own
share mode still binds later opens, and every override is audited. <a id="cite-facs.share.override-audited"></a>

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

## Delete-pending files <a id="cite-facs.delete.pending"></a>

A file is **delete-pending** when it has been marked to be deleted at
its last close. Any open of the file that holds `DELETE` can set or
clear the mark with `kacs_set_disposition`. An open created with
`KACS_CREATE_OPT_DELETE_ON_CLOSE` sets it when it closes. <a id="cite-facs.delete.set-clear"></a>

While a file is delete-pending:

- its name stays in place: `stat` and directory listings still show it;
- every new open of it fails with `EBUSY`, whatever the access asked,
  including attribute-only and `O_PATH` opens; a native open reports
  `KACS_STATUS_DELETE_PENDING`; <a id="cite-facs.delete.pending-opens-fail"></a>
- unlinking or renaming it by name fails with `EBUSY`;
- a delete-pending directory accepts no new entries: creating, linking
  or renaming into it fails with `EBUSY`; and
- creating a file of the same name fails, because the name still
  exists.

When the last open of the file closes, from whichever process, the
name is removed. <a id="cite-facs.delete.last-close"></a> The removal is authorized by the token of the open
that set the mark, captured when it was set, not by whoever happens to
close last; the closing task needs no right. A removal that fails at
close, for example because a directory gained an entry, is audited,
and the file is left in place and no longer delete-pending. <a id="cite-facs.delete.close-failure-audited"></a>

The name removed is the link the marking open was opened through,
followed across any renames since. Other hard links to the file remain.
If that name is already gone by the last close, nothing more is done.

A directory is removed at its last close only if it is empty then; one
that is not stays, and the failed removal is audited. A delete-pending
directory accepts no new entries meanwhile, so it can only empty. A
read-only regular file cannot be marked unless the caller sets it aside ([Special
Attributes](</kernel/internals/kacs/file-security/special-attributes.md#trm-3-9-13>)).

<a id="trm-3-9-10-4"></a>

## The disposition call <a id="cite-facs.delete.disposition-call"></a>

`kacs_set_disposition(fd, flags)` sets a file's delete disposition
through an open handle. Its flags are those of NT's
`FILE_DISPOSITION_INFORMATION_EX`:

| Flag | Value | Meaning |
|---|---|---|
| `KACS_DISPOSITION_DELETE` | 0x01 | Mark the file for deletion. Without it, clear the mark. |
| `KACS_DISPOSITION_POSIX_SEMANTICS` | 0x02 | With `DELETE`: remove the name now. |
| `KACS_DISPOSITION_ON_CLOSE` | 0x08 | Set or clear this open's delete-on-close obligation instead of the file's mark. |
| `KACS_DISPOSITION_IGNORE_READONLY` | 0x10 | Delete a read-only file. Requires `FILE_WRITE_ATTRIBUTES` as well. |

The open has to hold `DELETE`, or the call fails with `EACCES`. <a id="cite-facs.delete.disposition-needs-delete"></a> The
right was checked when the handle was opened, including through the
parent; the call checks the handle's mask, not the descriptor.

**POSIX semantics** remove the name at once, as `unlink(2)` does, and
open handles carry on with the unnamed file. <a id="cite-facs.delete.posix-now"></a> This is how a
Windows client's POSIX-semantics delete, and a Peios program's "delete
this file I hold open", are carried out. A directory has to be empty,
or the call fails with `ENOTEMPTY`.

Other opens of the file were checked against this open's `DELETE` when
each was opened, so the call does not repeat the share check. A read-only
regular file without `IGNORE_READONLY` fails with `EPERM`. Calling it on
an unmanaged descriptor fails with `EOPNOTSUPP`.

<a id="trm-3-9-10-5"></a>

## Renaming through a handle <a id="cite-facs.rename.handle"></a>

`kacs_rename(fd, newdirfd, newpath, flags)` moves the link an open
handle names to `newpath`, resolved relative to `newdirfd` as by
`renameat2()`. Its flags are those of NT's `FILE_RENAME_INFORMATION_EX`:

| Flag | Value | Meaning |
|---|---|---|
| `KACS_RENAME_REPLACE_IF_EXISTS` | 0x01 | Replace an existing file at the destination. |
| `KACS_RENAME_POSIX_SEMANTICS` | 0x02 | Replace a destination file that is open, if its opens share delete. |
| `KACS_RENAME_IGNORE_READONLY` | 0x40 | Replace a read-only destination file. |

An open file's name follows renames, so the handle always names its
current link; renaming by handle cannot hit a different file that has
since taken the old name. On StrataFS the link is found from the file's
provider instead ([Stacked filesystems](#trm-3-9-10-9)). Authorization is:

- `DELETE` in the handle's granted mask, for removing the source link; <a id="cite-facs.rename.needs-delete"></a>
- a live check for `FILE_ADD_FILE`, or `FILE_ADD_SUBDIRECTORY` for a
  directory, on the destination directory; and
- where a file is replaced, a live check for `DELETE` on it or
  `FILE_DELETE_CHILD` on its parent. <a id="cite-facs.rename.replace-checks"></a>

A replaced file that is open fails the rename with `EBUSY`, unless
`POSIX_SEMANTICS` is given and all its opens share delete. A replaced
file that is delete-pending, or read-only without `IGNORE_READONLY`,
also fails. A directory is never replaced. A destination that exists
without `REPLACE_IF_EXISTS` fails with `EEXIST`. If the handle's link
has already been removed, the call fails with `ENOENT`.

<a id="trm-3-9-10-8"></a>

## Deleting and renaming by name <a id="cite-facs.share.unlink-rename-by-name"></a>

NT treats deleting a file by name as an open with `DELETE`, so the
Linux calls obey the same rules. `unlink(2)`, `rmdir(2)` and `rename(2)`
fail with `EBUSY` when the source, or a file the rename would replace:

- is held by an open that does not share delete; or
- is delete-pending.

This covers `rm`, `mv`, and editors that save by renaming a new file
over the old one. The limit on denials means that only someone who
could delete a file can stop others deleting it. Their access checks
are unchanged ([Use-Time Semantics](</kernel/internals/kacs/file-security/use-time-semantics.md#trm-3-9-4>)). Plain deletion by name is still
immediate: the name goes at once, and open handles carry on.

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

## Ancestor pinning <a id="cite-facs.pin.ancestors"></a>

Windows will not rename or remove a folder while a file beneath it is
open. Linux has no such rule, and Peios keeps Linux's for its own
programs. An open made with `KACS_OPEN_PIN_ANCESTORS` asks for the
Windows rule for that one file: while it is open, each directory above
it, up to the root of the mount it was opened through, is **pinned**.
A pinned directory cannot be renamed, removed, or replaced by a rename,
by any process; those calls fail with `EBUSY`. <a id="cite-facs.pin.refuses-rename-rmdir"></a>

The pin follows the link the file was opened through, and the
directories it pins are those above that link when the open was made.
It is held as a count on each directory, so many pinned files beneath
one directory pin it once each. The counts are taken in a single walk
that is repeated if a rename moves one of the directories while the
walk is in progress, and dropped when the open's description closes.
<a id="cite-facs.pin.counts"></a> The pinned file itself is not pinned: renaming or deleting it is
governed by share modes.

Pinning blocks other people's work, so it requires
`SeLockParentagePrivilege`. File servers hold it, to give the Windows
clients they serve the folder protection those clients expect from each
other. <a id="cite-facs.pin.privilege"></a>

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

## Stacked filesystems <a id="cite-facs.share.stacked"></a>

A stacking filesystem shows files that live on another filesystem
beneath it, the **provider**. StrataFS gives every lookup of a name a
new inode of its own, so KACS keeps a file's share registrations,
delete-pending mark and pin counts on the provider's inode instead. All
routes to a file therefore see the same state: the merged view, another
StrataFS mount over the same stratum, and the stratum itself. A regular
file's open registers through the backing file that StrataFS opens on
the provider. A directory's open has no backing file, so it registers on
its provider itself. <a id="cite-facs.share.stratafs-provider"></a>

**Copy-up.** When StrataFS copies a regular file up to its writable
stratum, the file's opens move their registrations to the copy. A
directory copied up while it is open keeps its registrations and pins
on the former provider, so opens and removals made after the copy-up do
not see them. A directory present in more than one stratum cannot be
renamed in any case. <a id="cite-facs.share.stratafs-copy-up"></a>

**Renaming through a handle.** A StrataFS open's own name is the one it
was looked up by, which goes out of date when the file is renamed. The
provider is renamed in its own filesystem, which keeps its name current,
so `kacs_rename` finds the handle's link there:

1. it takes the provider's path within its stratum;
2. it looks that path up again through the mount the handle was opened
   through, and locks it as `rename(2)` would;
3. it checks that the name still reaches the same provider, retrying if
   a rename moved it meanwhile.

After a copy-up the handle names the copy. A name that a higher stratum
masks is not the handle's file, and the call fails with `ENOENT`, as it
does when the link has been removed. A file whose provider is a
read-only stratum fails with `EROFS`, as `rename(2)` does. <a id="cite-facs.rename.stratafs"></a>

**Overlayfs.** A file's opens register on its real inode through their
backing files. A directory opened through overlayfs opens its real
directory as a plain open, so the real directory sees a legacy open that
shares everything, and the native open's share mode is not enforced. <a id="cite-facs.share.overlayfs"></a>

---

# Byte-Range Locks

_Peios Kernel / Internals / KACS / File security_

> NT byte-range locks, kept by the kernel and enforced on every read and write — when they are checked, what they block, and the limit on who can block whom.

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

An NT byte-range lock reserves part of a file for one open. An
exclusive lock keeps every other open from reading or writing the range;
a shared lock keeps everyone, its holder included, from writing it.
Unlike Linux's advisory `fcntl` and `flock` locks, these are
**enforced**: a read or write that conflicts with another open's lock
fails, whichever program issued it. <a id="cite-facs.lock.enforced"></a> KACS keeps them for regular files
on FACS-managed mounts; `kacs_lock` on anything else fails with
`EOPNOTSUPP`.

Linux's own locks are unchanged and independent. A program that takes
`fcntl` locks neither sees nor conflicts with byte-range locks, except
that its reads and writes are checked against them like everyone
else's.

<a id="trm-3-9-11-1"></a>

## Taking and releasing locks <a id="cite-facs.lock.call"></a>

`kacs_lock(fd, args, size)` takes or releases a lock through an open
handle. `struct kacs_lock_args` gives the range as `offset` and
`length`, the operation, and flags:

| Operation | Value | Meaning |
|---|---|---|
| `KACS_LOCK_SHARED` | 1 | Take a shared lock. |
| `KACS_LOCK_EXCLUSIVE` | 2 | Take an exclusive lock. |
| `KACS_LOCK_UNLOCK` | 3 | Release a lock this open holds over exactly this range. |
| `KACS_LOCK_CANCEL` | 4 | Cancel this open's waiting request named by `cookie`. |

The open has to hold a data right — `FILE_READ_DATA`, `FILE_WRITE_DATA`
or `FILE_APPEND_DATA` — or the call fails with `EACCES`. <a id="cite-facs.lock.needs-data-right"></a> A lock
belongs to the open file description that took it, so descriptors
duplicated from it share its locks. When the description closes, its
locks are released and its waiting requests cancelled. <a id="cite-facs.lock.owner-and-release"></a>

Lock conflicts follow MS-FSA 2.1.4.10. Two locks of different opens
conflict where their ranges overlap and either is exclusive. An open's
exclusive lock also conflicts with its own overlapping exclusive lock.
A zero-length lock is a point at its offset, and the range from offset
zero with length zero conflicts with nothing. <a id="cite-facs.lock.conflicts"></a>

A request that conflicts waits until it can be granted, unless it
carries `KACS_LOCK_FAIL_IMMEDIATELY`, in which case it fails with
`EAGAIN`. A waiting request can be interrupted by a signal (`EINTR`),
or cancelled by another thread with `KACS_LOCK_CANCEL` and the same
`cookie`, in which case it fails with `ECANCELED`. Waiting requests are
granted in the order they arrived as the conflicting locks go.
<a id="cite-facs.lock.waiting"></a> Unlocking a range this open does not hold exactly fails with `ENOLCK`.

<a id="trm-3-9-11-2"></a>

## What locks block <a id="cite-facs.lock.io-checks"></a>

Each operation that reads or changes a file's contents is checked
against the locks of **other** opens:

| Operation | Checked as |
|---|---|
| Read | A read of its range |
| Write, including append | A write of its range |
| `truncate`, `ftruncate` | A write of the range between the old and new size |
| An open that truncates | Not checked, as on Windows: `O_TRUNC`, and a native open with `OVERWRITE`, `OVERWRITE_IF` or `SUPERSEDE` |
| `fallocate` that changes contents | A write of the range it changes, to end of file for collapse and insert |

An open that truncates is let through as Windows lets an overwriting
`CreateFile` through: the locks it drops go with the data, and the
holders' later I/O is checked against what is left. <a id="cite-facs.lock.open-truncate-unchecked"></a>

An exclusive lock blocks reads and writes; a shared lock blocks writes.
A shared lock also blocks its own holder's writes. A conflicting
operation fails with `EAGAIN`; it does not wait. <a id="cite-facs.lock.io-eagain"></a>

The check covers every way of issuing these operations: `read`,
`write` and their vectored and positioned forms, `sendfile`, `splice`
and `copy_file_range`, direct I/O, AIO and io_uring.

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

## When a lock takes effect <a id="cite-facs.lock.at-issue"></a>

An I/O is checked against the lock list when it is **issued**. Granting
a lock does not wait for I/O already admitted: an I/O that passed its
check before a conflicting lock was granted may finish after it, and
counts as having happened before the lock. This is the guarantee
Windows gives. No lock is held across the I/O itself, so asynchronous
I/O completing elsewhere needs no special treatment, and an I/O cannot
deadlock against a lock request.

A file with no byte-range locks costs one check that its lock list is
empty.

<a id="trm-3-9-11-4"></a>

## Memory mappings are not covered <a id="cite-facs.lock.mmap-excluded"></a>

Loads and stores through a memory mapping are not checked against
locks, as on Windows, where mapped views bypass byte-range locks.
Mapping a file, and changing a mapping's protection, are checked only
by the handle's rights ([Use-Time Semantics](</kernel/internals/kacs/file-security/use-time-semantics.md#trm-3-9-4-1>)).

<a id="trm-3-9-11-5"></a>

## Who can block whom <a id="cite-facs.lock.dos-limit"></a>

Enforced locks would let any reader stop others using a file. KACS
limits their reach as it limits share modes: a lock blocks other opens'
reads and writes only if the open that took it could write the file
itself, that is, if the file's descriptor grants its opener
`FILE_WRITE_DATA` or `FILE_APPEND_DATA`. A lock taken by an opener who
could not write the file still conflicts with other locks, so
cooperating readers can coordinate with it, but it blocks no I/O.

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

## Stacked filesystems <a id="cite-facs.lock.stacked"></a>

Through StrataFS, a lock belongs to the backing file its open reaches
and is held on the provider, so it covers every route to that file. A
copy-up gives the file a new provider: locks taken before it stay with
the former provider, and I/O through the copy is not checked against
them. Locks through overlayfs are not supported, and `kacs_lock` fails
with `EOPNOTSUPP`.

---

# Leases

_Peios Kernel / Internals / KACS / File security_

> NT caching leases kept by the kernel for a lease manager such as a file server — the read, handle and write states, what breaks them, and how breaks are delivered.

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

A lease lets a holder cache a file safely. Its state is any combination
of three NT caching bits:

| State | Value | The holder may cache |
|---|---|---|
| `KACS_LEASE_READ` | 0x1 | The file's contents and attributes, for reading. |
| `KACS_LEASE_HANDLE` | 0x2 | Its open handles, keeping them open after its own client has closed them. |
| `KACS_LEASE_WRITE` | 0x4 | Changes to the contents, not yet written back. |

When another open or operation would make the cached state wrong,
KACS **breaks** the lease: it tells the holder, waits for the holder to
flush and give up the state, then lets the operation proceed. A file
server holds leases on behalf of its clients and relays the breaks to
them, so a local program and a network client see a consistent file.
<a id="cite-facs.lease.purpose"></a>

Leases cover regular files and directories on FACS-managed mounts.
A directory lease can hold only read and handle caching. Below a
stacking filesystem a lease is held on the provider an open reaches
([Stacked filesystems](#trm-3-9-12-6)).

<a id="trm-3-9-12-1"></a>

## Lease managers <a id="cite-facs.lease.manager"></a>

A lease is held through a **lease manager**, created by
`kacs_create_lease_manager(flags, break_timeout_ms)`. The call returns a
descriptor; `KACS_LEASE_MANAGER_CLOEXEC` and
`KACS_LEASE_MANAGER_NONBLOCK` set close-on-exec and non-blocking
reads. Break notices for every lease the manager holds arrive on that
descriptor.

Each lease is identified by its manager and a 16-byte **key** the
manager chooses. Opens with the same key belong to one holder: an open
made with a key does not break the leases its manager holds under that
key ([KACS-Native Open](</kernel/internals/kacs/file-security/kacs-native-open.md#trm-3-9-2-12>)). <a id="cite-facs.lease.key"></a> A file server gives each client lease
its own key, and each oplock its own unique key.

Closing the manager's last descriptor releases all its leases.

<a id="trm-3-9-12-2"></a>

## Requesting a lease <a id="cite-facs.lease.request"></a>

`kacs_lease(fd, manager_fd, args, size)` requests, changes or releases
the lease on the file `fd` refers to. The open has to have been made
with `KACS_OPEN_LEASE_KEY`, naming the same manager and the key given
in `args`; otherwise the call fails with `EINVAL`.

KACS grants as much of the requested state as current opens allow,
writes the granted state back into `args.state`, and may grant none.
<a id="cite-facs.lease.grant"></a>

- **Read** needs the open to hold a read right, and no open under
  another key to hold write access.
- **Write** needs the open to hold a write right, and no open of the
  file under another key.
- **Handle** is granted with read.

A state of zero releases the lease. A lease is also released when the
last open under its key closes, unless it holds handle caching.

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

## What breaks a lease <a id="cite-facs.lease.break-points"></a>

Only operations from outside the holder break its lease: an operation
through an open under the lease's own key never does.

| Operation by another holder | Breaks | Reason |
|---|---|---|
| Opening the file | Write | `KACS_LEASE_BREAK_OPEN` |
| An open refused by a sharing conflict | Handle, then the open is checked again | `KACS_LEASE_BREAK_SHARING` |
| Writing the file | Read | `KACS_LEASE_BREAK_WRITE` |
| Changing its size | Read | `KACS_LEASE_BREAK_SIZE` |
| Taking a byte-range lock | Read | `KACS_LEASE_BREAK_LOCK` |
| Renaming or linking it, or renaming a directory above it | Handle | `KACS_LEASE_BREAK_NAMESPACE` |
| Deleting it, or setting its delete disposition | Handle | `KACS_LEASE_BREAK_DELETE` |
| Changing its security descriptor | Handle | `KACS_LEASE_BREAK_SECURITY` |
| Changing its attributes or extended attributes | Read | `KACS_LEASE_BREAK_ATTRIBUTES` |
| Adding, removing or renaming an entry of a leased directory | Read and handle | `KACS_LEASE_BREAK_CHILD` |

Breaking write also breaks whatever the new open could not share: a
writer breaks read as well. A broken lease falls to the state the
operation can live with, not necessarily to none.

The holder of a lease that loses only read caching can lose nothing it
has not already written, so such a break is a **notice**: the operation
does not wait for it. Every other break waits. <a id="cite-facs.lease.read-break-no-wait"></a>

Most of these are the points at which Linux breaks its own leases and
NFS delegations, and KACS's leases are entries in the same table, so
the existing break points reach them. KACS adds the others: writes and
size changes through descriptors that were already open, byte-range
locks, security changes, and sharing conflicts.

<a id="trm-3-9-12-4"></a>

## Break notices <a id="cite-facs.lease.notices"></a>

Reading a lease-manager descriptor returns break notices, each a
`struct kacs_lease_break`: the lease's key, the file's device and inode
number, the current and new state, the reason, and an epoch that counts
the lease's breaks. The descriptor is readable with `poll()` when a
notice is waiting.

Notices are never dropped. A lease has at most one break outstanding,
so a manager's queue is bounded by the number of leases it holds.
<a id="cite-facs.lease.lossless"></a>

The holder acknowledges a break with `kacs_lease`, setting
`KACS_LEASE_ACKNOWLEDGE` and a state no greater than the notice's new
state. The waiting operation then proceeds.

<a id="trm-3-9-12-5"></a>

## Timeouts <a id="cite-facs.lease.timeout"></a>

A break not acknowledged within the manager's break timeout is
completed by KACS: the lease is reduced to the new state, the waiting
operation proceeds, and the manager receives a notice with reason
`KACS_LEASE_BREAK_TIMEOUT`. The timeout is set when the manager is
created, in milliseconds, from 1 to 35 000; zero gives the default of
35 seconds, the time SMB allows a client to acknowledge a break.

An operation waiting on a break can be interrupted by a signal. Only
the waiting operation fails; the break goes on.

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

## Stacked filesystems <a id="cite-facs.lease.stacked"></a>

Through StrataFS, a regular file's lease is held on the provider its
open reaches, so it covers every route to that file. A copy-up gives the
file a new provider: a lease taken before it stays with the former
provider, and changes made through the copy do not break it. Leases on
StrataFS directories, and on anything reached through overlayfs, are not
supported; `kacs_lease` fails with `EOPNOTSUPP`.

---

# Special Attributes

_Peios Kernel / Internals / KACS / File security_

> The read-only flag KACS enforces for every process, and the settable Created At date, kept in the special-attributes extended attribute.

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

KACS keeps a file's **special attributes** in the extended attribute
`security.peios.sattr`, beside its security descriptor in
`security.peios.sd`. There are two today:

- **Read-only**, which KACS enforces for every process.
- **Created At**, a settable creation date.

<a id="trm-3-9-13-1"></a>

## Reading and writing them <a id="cite-facs.sattr.access"></a>

The attribute is read and written with the ordinary extended-attribute
calls — `getxattr`, `setxattr` and their descriptor and `*at` forms —
using `struct kacs_sattr` as the value. KACS answers these calls
itself. Reading needs `FILE_READ_ATTRIBUTES`, and writing or removing
needs `FILE_WRITE_ATTRIBUTES`, rather than the extended-attribute
rights. <a id="cite-facs.sattr.rights"></a> Through a descriptor, the right comes from the handle's
granted mask; by path, from a live check, which may grant
`FILE_READ_ATTRIBUTES` through the parent ([KACS-Native Open](</kernel/internals/kacs/file-security/kacs-native-open.md#trm-3-9-2-8>)).

| Field | Meaning |
|---|---|
| `version` | `KACS_SATTR_VERSION`, currently 1. |
| `valid` | The fields a write changes. A read sets every bit. |
| `attributes` | `KACS_SATTR_READONLY` (0x1). |
| `flags` | On a read, `KACS_SATTR_CREATED_AT_SET` if Created At is set. On a write, `KACS_SATTR_CREATED_AT_CLEAR` unsets it. |
| `created_at_sec`, `created_at_nsec` | Created At, as seconds and nanoseconds since the Unix epoch. |

A write changes only the fields its `valid` mask names and leaves the
others as they are. Two programs changing different attributes at once
therefore cannot undo each other's change. <a id="cite-facs.sattr.merge"></a> A write with an unknown
version, `valid` bit, attribute or flag, a nonzero `__pad`, a value of
the wrong size, or `XATTR_CREATE` or `XATTR_REPLACE` fails with
`EINVAL`. Removing the attribute clears read-only and unsets Created
At.

The attribute is stored only while something is set, and reading a
file that has none fails with `ENODATA`: it is not read-only, and has no
Created At.
Tools that copy extended attributes copy a stored attribute with the
rest; a copy that should keep an unset Created At has to read it and
set it on the copy.

<a id="trm-3-9-13-2"></a>

## Read-only <a id="cite-facs.sattr.readonly"></a>

Read-only protects a file against accidental change, and binds its
owner too, without anyone rewriting its permissions. It is the
attribute Windows programs set and check, and source-control tools
mark checked-in files with it.

On a regular file marked read-only, for every process: <a id="cite-facs.sattr.readonly-enforced"></a>

- An open asking `FILE_WRITE_DATA` or `FILE_APPEND_DATA` fails with
  `EACCES`. A legacy open for writing fails the same way. A
  `MAXIMUM_ALLOWED` open is granted neither right, nor
  `FILE_ADD_SUBDIRECTORY` or `FILE_DELETE_CHILD`, following MS-FSA
  2.1.5.1.2.1. `FILE_OVERWRITE` and `FILE_SUPERSEDE` fail with `EACCES`.
- `truncate` by path fails with `EACCES`.
- Deleting it fails with `EPERM`: `unlink(2)`, a rename that would
  replace it, a delete disposition, and an open with delete-on-close,
  which a native open reports as `KACS_STATUS_CANNOT_DELETE`. The
  disposition and rename calls can set this aside with their
  `IGNORE_READONLY` flags ([Sharing and Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md#trm-3-9-10-4>)).

The check is made at open and at deletion, not on every write: a handle
opened for writing before the file was marked read-only keeps working,
as on Windows. Renaming a read-only file, and changing its other
attributes or its descriptor, are not affected. Anyone with
`FILE_WRITE_ATTRIBUTES` can clear the flag.

On a directory, read-only is kept and reported but not enforced.
Windows uses the flag on folders to mark them as customized, not to
protect them. <a id="cite-facs.sattr.readonly-directories"></a>

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

## Created At <a id="cite-facs.sattr.created-at"></a>

Created At records when a file was created, in the sense a person or a
copy tool means: a copy can carry its original's creation date, and a
Windows client can set it. It is distinct from the filesystem's
**birth time**, which `statx` reports, which nobody can set, and which
records when this inode came into being. Birth time is the forensic
fact; Created At is the user-facing date.

While Created At has not been set, a file's creation date is its birth
time: a reader that finds no Created At, or finds
`KACS_SATTR_CREATED_AT_SET` clear, takes the date from `statx`. KACS
never changes Created At itself, and `statx` continues to report the
birth time.

---

# Linux credentials

_Peios Kernel / Internals / KACS / Linux credentials_

> Find the Peios kernel articles about linux credentials.

Use these articles to understand linux credentials in the Peios kernel.

- [DAC Neutralisation](</kernel/internals/kacs/linux-credentials/dac-neutralisation.md>)
- [setuid Behaviour](</kernel/internals/kacs/linux-credentials/setuid-behaviour.md>)
- [Netlink](</kernel/internals/kacs/linux-credentials/netlink.md>)

---

# DAC Neutralisation

_Peios Kernel / Internals / KACS / Linux credentials_

> Linux evaluates DAC before any LSM hook fires, so KACS has to neutralise it — the capability switchboard, the compatibility state and the LSM stack.

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

Linux evaluates DAC — UID, GID and mode-bit checks — *before*
consulting LSM hooks. If DAC denies an operation the hook never fires,
and KACS cannot override a DAC denial: LSM hooks are restrictive, able
to further deny what DAC would allow but never to grant what DAC has
refused.

KACS therefore neutralises DAC so the hooks always fire. Every process
receives a set of Linux capabilities that bypass the DAC gates, and
those capabilities are mandatory substrate rather than grants. <a id="cite-cred.dac.every-process-gets-allow"></a>

<a id="trm-3-10-2-1"></a>

## The capability switchboard

Linux's capabilities fall into three categories, and
`security_capable()` is authoritative for all of them — the raw
capability sets on `struct cred` are compatibility-visible state that
answers nothing. <a id="cite-cred.dac.security-capable-authoritative"></a>

**ALLOW** capabilities exist to override UID-based permission checks
on operations KACS enforces through its own hooks, so DAC never blocks
something KACS will evaluate independently: <a id="cite-cred.dac.allow-set"></a>

| CAP | Name | Rationale |
|---:|---|---|
| 0 | `CAP_CHOWN` | KACS file hooks enforce. |
| 1 | `CAP_DAC_OVERRIDE` | KACS file hooks enforce. |
| 2 | `CAP_DAC_READ_SEARCH` | KACS file hooks enforce. |
| 3 | `CAP_FOWNER` | KACS file hooks enforce. |
| 4 | `CAP_FSETID` | KACS file hooks enforce. |
| 5 | `CAP_KILL` | The `task_kill` hook enforces. |
| 6 | `CAP_SETGID` | Cosmetic under KACS. |
| 7 | `CAP_SETUID` | Cosmetic under KACS. |
| 11 | `CAP_NET_BROADCAST` | Unused in modern kernels. |
| 15 | `CAP_IPC_OWNER` | KACS IPC hooks enforce. |
| 28 | `CAP_LEASE` | KACS file hooks enforce. |
| 10 | `CAP_NET_BIND_SERVICE` | The port's reservation SD decides at `socket_bind`; the Linux privileged-port floor never refuses. |

**PRIVILEGE** capabilities gate operations no other KACS hook covers,
and map to a KACS privilege: <a id="cite-cred.dac.privilege-mapped"></a>

| CAP | Name | Privilege |
|---:|---|---|
| 9 | `CAP_LINUX_IMMUTABLE` | `SeTcbPrivilege` |
| 12 | `CAP_NET_ADMIN` | `SeTcbPrivilege` |
| 13 | `CAP_NET_RAW` | `SeTcbPrivilege` |
| 14 | `CAP_IPC_LOCK` | `SeLockMemoryPrivilege` |
| 16 | `CAP_SYS_MODULE` | `SeLoadDriverPrivilege` |
| 17 | `CAP_SYS_RAWIO` | `SeTcbPrivilege` |
| 18 | `CAP_SYS_CHROOT` | `SeTcbPrivilege` |
| 19 | `CAP_SYS_PTRACE` | `SeDebugPrivilege` |
| 20 | `CAP_SYS_PACCT` | `SeTcbPrivilege` |
| 21 | `CAP_SYS_ADMIN` | `SeTcbPrivilege` (but see the mount note below) |
| 22 | `CAP_SYS_BOOT` | `SeShutdownPrivilege` |
| 23 | `CAP_SYS_NICE` | `SeIncreaseBasePriorityPrivilege` |
| 24 | `CAP_SYS_RESOURCE` | `SeIncreaseQuotaPrivilege` |
| 25 | `CAP_SYS_TIME` | `SeSystemtimePrivilege` |
| 26 | `CAP_SYS_TTY_CONFIG` | `SeTcbPrivilege` |
| 27 | `CAP_MKNOD` | `SeTcbPrivilege` |
| 29 | `CAP_AUDIT_WRITE` | `SeAuditPrivilege` |
| 30 | `CAP_AUDIT_CONTROL` | `SeSecurityPrivilege` |
| 33 | `CAP_MAC_ADMIN` | `SeSecurityPrivilege` |
| 34 | `CAP_SYSLOG` | `SeTcbPrivilege` |
| 35 | `CAP_WAKE_ALARM` | `SeTcbPrivilege` |
| 36 | `CAP_BLOCK_SUSPEND` | `SeTcbPrivilege` |
| 37 | `CAP_AUDIT_READ` | `SeSecurityPrivilege` |
| 38 | `CAP_PERFMON` | `SeSystemProfilePrivilege` **or** `SeProfileSingleProcessPrivilege` **or** `SeLoadDriverPrivilege` |
| 39 | `CAP_BPF` | `SeTcbPrivilege` |
| 40 | `CAP_CHECKPOINT_RESTORE` | `SeTcbPrivilege` |

`CAP_PERFMON` is the one **OR-mapped** entry: the Linux capability
genuinely spans several Peios privilege tiers, and no single privilege
covers everything it gates. The check succeeds if the caller holds any
of the three, and every one it holds is marked used. <a id="cite-cred.dac.perfmon-or-mapped"></a> Per-operation
enforcement then happens at the relevant syscall hook, which checks
the *specific* privilege the *specific* operation needs ([Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)).
OR-mapping stops the capability ceiling manufacturing false denials;
it grants nothing the holder does not already have.

`CAP_SYS_ADMIN` maps to `SeTcbPrivilege` and is **not** OR-mapped, which
would be the obvious way to let administrators mount and is the wrong
one: `CAP_SYS_ADMIN` gates dozens of unrelated operations, so widening
it would hand out far more than mounting.

Mounting is handled outside the capability table instead. `may_mount()`
(`fs/namespace.c`, patched) calls `pkm_kacs_may_mount_op()`, whose first
rung accepts `SeManageVolumePrivilege` **or** `SeTcbPrivilege`, before
falling back to the ordinary `CAP_SYS_ADMIN` check. <a id="cite-cred.dac.may-mount-manage-volume"></a> In a mount
namespace the caller created for itself, a second rung admits a bind
mount, an unmount, a `pivot_root`, or a new tmpfs, proc or read-only
stratafs on the namespace's own security descriptor instead ([A Private Mount Table](</kernel/internals/kacs/mount-namespaces/a-private-mount-table.md#trm-3-13-1>)); in
the initial namespace the privilege is the only route. Every other `CAP_SYS_ADMIN` caller still needs the TCB.

It has to be asked there rather than through the `sb_mount` LSM hook:
`may_mount()`'s capability check runs *before* `security_sb_mount()`, so
an LSM is never consulted about a mount the capability check already
refused. A hook can narrow that decision; it cannot widen it.

The `CAP_SYS_ADMIN` gate on creating a namespace (`kernel/nsproxy.c`,
patched) has one carve-out of the same kind: a request for a mount
namespace alone passes without it, because the table it yields is an
object its creator owns. Any other namespace type, alone or in
combination, still needs the TCB. <a id="cite-cred.dac.mount-namespace-ungated"></a>

`CAP_SYS_BOOT` carries an extra condition the table cannot express: a
token whose logon session is of a remote origin — Network,
NetworkCleartext, NewCredentials or RemoteInteractive — additionally
requires `SeRemoteShutdownPrivilege`. <a id="cite-cred.dac.sys-boot-remote-shutdown"></a>

**DENY** capabilities are refused unconditionally, whatever privilege
the caller holds: `CAP_SETPCAP` (8) and `CAP_SETFCAP` (31), because
capabilities are dead under KACS, and `CAP_MAC_OVERRIDE` (32), because
KACS is the active LSM and must not be bypassable. <a id="cite-cred.dac.deny-set"></a>

An unmapped or unknown capability is denied by default. The
switchboard fails closed. <a id="cite-cred.dac.unmapped-denied"></a>

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

## Compatibility state

Programs may inspect the credential capability sets with `capget()` or
`/proc/<pid>/status`, and may attempt to mutate the non-ALLOW subset
with `capset()` or `prctl()`. None of that is authoritative.

`capget()` and `/proc/<pid>/status` report the ALLOW substrate as
present in the effective, permitted and inheritable sets — reported as
`CapEff`, `CapPrm` and `CapInh`, and additionally `CapBnd`, by the proc
interface. <a id="cite-cred.dac.capget-reports-allow"></a> Non-ALLOW bits present in the
credential state may also be reported, but grant no authority.
`CapAmb` reports raw Linux ambient state; the ALLOW substrate does not
depend on ambient capabilities.

The strict invariant is that the ALLOW set is mandatory substrate and
has to survive wherever Linux capability mechanics would otherwise
drop it out from under KACS. `capset()` rejects any request clearing
an ALLOW capability from the effective, permitted or inheritable sets,
and bounding-set drops and ambient manipulation reject anything that
would clear or exclude one. <a id="cite-cred.dac.allow-set-undroppable"></a> The implementation is slightly stricter
than that: an ambient *raise* of an ALLOW capability is refused too,
not only a clear. <a id="cite-cred.dac.ambient-raise-refused"></a>

After that validation, `capset()` follows ordinary Linux ambient
behaviour — ambient bits no longer present in both the requested
permitted and inheritable sets may be cleared. Because requests
clearing ALLOW bits from permitted or inheritable are denied outright,
that intersection can never indirectly clear an existing ALLOW ambient
bit.

Direct mutation of non-ALLOW state is therefore compatibility-only. It
may change what `capget()` reports and cannot change the authority
answer for any capability-gated operation.

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

## Neutralised native paths

Native commoncap helpers that make raw capability-subset decisions
*before* a KACS hook are neutralised where KACS has an authoritative
hook of its own. That covers the subset gates in ptrace access,
`PTRACE_TRACEME`, and `task_setnice`, `task_setscheduler` and
`task_setioprio` — each replaced by an unconditional allow, leaving
the KACS process-descriptor and PIP hooks to decide. <a id="cite-cred.dac.commoncap-neutralised"></a> Capability checks
that reach `security_capable()` directly stay under the switchboard.

For raw xattr operations the FACS metadata hooks are authoritative, so
the native security-xattr capability prechecks that would run first
are skipped. <a id="cite-cred.dac.xattr-precheck-skipped"></a> This does not revive Linux file capabilities: installing
or replacing non-empty `security.capability` data stays denied by the
dead `CAP_SETFCAP` policy, with the single exception of the
KACS-owned StrataFS clone ([The StrataFS Copy-Up Context](</kernel/internals/stratafs/security/kacs-admission-and-object-phases.md#trm-3-9-7>)), and exec-time file-capability
grants remain suppressed. <a id="cite-cred.dac.file-caps-dead"></a> Removing stale metadata goes through the
ordinary `FILE_WRITE_EA` path.

One structural wrinkle: `security_capable()` reaches the KACS
switchboard twice — once through the patched commoncap entry point and
once through the KACS `capable` hook — so a privilege consulted this
way is marked used twice. <a id="cite-cred.dac.privilege-use-double-counted"></a> The authorization answer is unaffected; the
privilege-use accounting double-counts.

<a id="trm-3-10-2-4"></a>

## The LSM stack

MAC LSMs — SELinux, AppArmor, SMACK, TOMOYO — and the BPF LSM have to
be disabled. <a id="cite-cred.dac.mac-lsms-disabled"></a> They would independently deny operations from their own
label and policy systems, undermining KACS's claim to be the sole
identity-based authorization mechanism and FACS's to be the sole file
access authority. Non-MAC LSMs are permitted where they make no
identity-based access decision: landlock, lockdown and integrity stack
safely. <a id="cite-cred.dac.non-mac-lsms-allowed"></a> Yama is not among them and is not built: its
relational `ptrace_scope` answers every attach to a non-descendant with
"does the caller hold `CAP_SYS_PTRACE`", which the switchboard maps to
SeDebugPrivilege, so it would decide ahead of the process descriptor
and PIP dominance that [Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>) makes the ptrace authority. The same-uid
attach it exists to close cannot arise under KACS, which never grants
on uid. <a id="cite-cred.dac.yama-not-built"></a>

The check is made at initialisation and KACS refuses to activate if it
fails — but it is a **build-configuration** test rather than an
inspection of the live LSM stack. It tests whether each conflicting
LSM is enabled in the kernel config, and never parses `CONFIG_LSM` or
enumerates what is actually registered.

---

# setuid Behaviour

_Peios Kernel / Internals / KACS / Linux credentials_

> Under KACS a UID has no security properties — what the setuid syscalls do, what the setuid bit does at exec, and the compatibility gaps that remain.

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

Under KACS a UID has no security properties whatever. It is not
consulted in any access decision, appears in no descriptor, and is
referenced by no ACE. It is a compatibility value stored in
`struct cred` for the sole purpose of answering `getuid()`.

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

## The setuid syscalls

The `setuid` family — `setuid`, `setgid`, `setresuid`, `setresgid`,
`setgroups` — changes Linux credentials.

**Without `SeAssignPrimaryTokenPrivilege`**, which is the common case,
the call is a silent no-op. It returns success, and every credential
field is restored from the old credential: UIDs, GIDs, supplementary
groups, capabilities. <a id="cite-cred.setuid.unprivileged-noop"></a> Neither the credential nor the token changes,
and the process's authority before and after is identical.

The silent success preserves consistency between the visible UID and
the KACS identity. Changing the UID without changing the token would
produce subtle failures — the wrong home directory from `getpwuid()`,
for instance — for no security benefit.

**With `SeAssignPrimaryTokenPrivilege`** the design calls for the
credential change to trigger a full identity swap, redirected to authd
to obtain a token for the target UID's principal, so that both token
and credential change together.

That is not what happens. A caller holding the privilege receives
`EOPNOTSUPP` and the call **fails**. <a id="cite-cred.setuid.privileged-eopnotsupp"></a> There is no authd redirect
anywhere in the LSM. The practical effect is that the privileged path
is unavailable rather than dangerous: a TCB component cannot change
identity this way, and has to install a token directly instead
([Token Lifecycle](</kernel/internals/kacs/tokens/token-lifecycle.md#trm-3-2-3>)).

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

## The setuid bit on exec

The filesystem setuid bit tells the kernel to change the effective UID
to the file owner's on exec.

**Without the privilege**, the Linux-visible UID and GID slots change
to the file owner's identity while the token is untouched — a cosmetic
escalation in which the process sees `geteuid() == 0` while KACS
continues to enforce the original token. <a id="cite-cred.setuid.exec-bit-cosmetic"></a> Concretely `uid` and `suid`
are set from `euid`, the GID counterparts mirror that, `fsuid` and
`fsgid` are carried over unchanged from the old credential, and the
token is cloned as-is. <a id="cite-cred.setuid.exec-bit-slot-values"></a>

**With the privilege**, the design calls for the slots *and* the token
to change — genuine escalation. As with the syscall, this is not
implemented: an exec that would change UID or GID under a token
holding `SeAssignPrimaryTokenPrivilege` returns `EOPNOTSUPP` and the
exec fails. <a id="cite-cred.setuid.exec-privileged-eopnotsupp"></a>

The asymmetry between the two mechanisms is intentional in the design.
`setuid()` is de-escalation, so leaving everything unchanged is the
safe failure mode. The setuid bit is escalation, and the target binary
expects the euid and will check it — `sudo` verifies
`geteuid() == 0` — so the euid has to change for the binary to
function at all.

| Mechanism | With privilege | Without privilege |
|---|---|---|
| `setuid()` syscall | Designed: all UIDs and token change. Actual: fails with `EOPNOTSUPP`. |  Silent no-op |
| Setuid bit on exec | Designed: euid/suid and token change. Actual: exec fails with `EOPNOTSUPP`. | euid/suid change, token unchanged |

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

## The current_fsuid patch

The kernel calls `current_fsuid()` whenever it needs a UID for a
filesystem operation — file creation ownership, quota tracking,
keyring lookup, NFS credentials. KACS redefines it, along with
`current_fsgid()` and `current_fsuid_fsgid()`, to return the projected
value from the effective token rather than `cred->fsuid`. <a id="cite-cred.setuid.fsuid-patch"></a>

So files are created owned by the projected UID, quotas track against
it, per-user keyrings are keyed by it, and an NFS server sees the real
identity rather than UID 0. <a id="cite-cred.setuid.fsuid-consequences"></a>

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

## Compatibility gaps

**The privilege-drop pattern.** A daemon that calls `setuid(target)`
and then checks `getuid() != target` to confirm the drop sees success
returned with the UID unchanged. This is intentional — UIDs carry no
security meaning here — and software ported to Peios should use
KACS-native token operations for privilege management instead.

**Direct capability manipulation.** Software that manipulates
capabilities with `capset()` and `capget()`, writes seccomp filters,
or inspects its own capability set may behave unexpectedly ([DAC Neutralisation](</kernel/internals/kacs/linux-credentials/dac-neutralisation.md#trm-3-10-2>)).
Seccomp filters themselves install as on Linux — `no_new_privs`, or
`CAP_SYS_ADMIN` resolved to `SeTcbPrivilege` — and `no_new_privs`
keeps its Linux meaning for the one Peios gain an exec can confer:
under it, an exec cannot raise the process's PIP label ([Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)).

**`setfsuid()`** is a no-op for filesystem purposes, since
`current_fsuid()` ignores `cred->fsuid`; and cosmetic setuid-bit exec
transitions do not flow into the projected values either. <a id="cite-cred.setuid.setfsuid-noop"></a>

**`access()` and `faccessat()`** use the effective token rather than
the real credential — the entire native credential-override machinery
those calls normally use is compiled out. <a id="cite-cred.setuid.access-uses-effective-token"></a> The concept of a "real
identity" separate from the acting one does not exist in KACS.

**`SO_PEERCRED`** returns projected UIDs rather than token
information, and because the switchboard allows `CAP_SETUID`, cosmetic
UID forgery in `SCM_CREDENTIALS` is possible. <a id="cite-cred.setuid.so-peercred-projected"></a> Both are Linux
compatibility metadata, not peer-token authorities: a service needing
authoritative identity uses stream or seqpacket peer-token capture, or
explicit token descriptor passing ([Impersonation Lifecycle](</kernel/internals/kacs/impersonation/state-transitions.md#trm-3-5-3>)).

**Legacy `auditd`** records projected UIDs, so KACS audit through KMES
replaces Linux audit for security-relevant logging.

A `uid0` utility — running a program with `cred->uid` forced to 0 for
legacy programs that refuse to start otherwise — is described in the
design and does not exist in the tree. <a id="cite-cred.setuid.uid0-utility-absent"></a> The kernel-side guarantee it
would rely on does hold: `current_fsuid()` ignores `cred->uid`
entirely, so even with such a utility active, filesystem operations
would use the projected UID and files would be owned by the real user.

---

# Netlink

_Peios Kernel / Internals / KACS / Linux credentials_

> Netlink requests are authorised through the capability switchboard — both the socket opener's token and the sender's — synchronously, in the sender's own context.

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

Netlink is the kernel's message interface: a process sends a request
to a kernel subsystem (routing, firewalling, audit, generic netlink
families) and the subsystem answers, or pushes notifications to
multicast groups. The kernel authorises those requests with capability
checks, and on Peios every one of them is a KACS privilege check.

<a id="trm-3-10-4-1"></a>

## Where the checks run

A request to the kernel is handled synchronously: `netlink_unicast`
delivers the message to the family's receive function inside the
sending task's own `sendmsg`, under the family's mutex. <a id="cite-cred.netlink.synchronous-delivery"></a> There is no
later context in which a message is processed, so the sender at every
check is the current thread, and audit attribution needs no capture.
Only messages between two user sockets are queued.

The netlink permission helpers — `netlink_capable`,
`netlink_ns_capable` and `netlink_net_capable`, and through them the
generic-netlink `GENL_ADMIN_PERM` and `GENL_UNS_ADMIN_PERM` operation
flags — test two subjects and require both to pass: the credential
that **opened** the netlink socket, held on the socket's file, and the
**sender**, the current thread. <a id="cite-cred.netlink.two-subject-check"></a> `netlink_allowed`, which gates binding
to a family's multicast groups and sending to another port, tests the
current thread. <a id="cite-cred.netlink.allowed-tests-sender"></a> This is Linux's own two-point rule, introduced after
CVE-2014-0181 so that a privileged program could not be turned into a
deputy by inheriting an unprivileged process's netlink socket as its
standard output.

<a id="trm-3-10-4-2"></a>

## What decides

Every one of those tests reaches `security_capable()` with a specific
credential, and the capability switchboard ([DAC Neutralisation](</kernel/internals/kacs/linux-credentials/dac-neutralisation.md#trm-3-10-2>)) evaluates **that
credential's token**: `pkm_kacs_capable_in_cred_ns` looks up the token
on the credential and asks whether it holds a privilege the capability
maps to. <a id="cite-cred.netlink.evaluated-against-cred-token"></a> The opener's file credential carries the opener's token; the
current thread's credential carries the sender's effective token,
impersonation included. So a netlink request is authorised against two
KACS tokens, with the same privilege catalogue and the same fail-closed
behaviour as any other capability check — not against uid bits, and
not against a projection of the token.

The catalogue maps `CAP_NET_ADMIN`, `CAP_NET_RAW` and `CAP_SYS_ADMIN`
to `SeTcbPrivilege`. Configuring the network — adding a route, setting
an interface up, editing a firewall — is therefore a TCB operation on
Peios; an administrator's session cannot do it, and a `RTM_NEWLINK`
from an administrator is answered with `EPERM`. <a id="cite-cred.netlink.rtm-newlink-needs-tcb"></a> Audit control
(`CAP_AUDIT_CONTROL`, `CAP_AUDIT_READ`) maps to `SeSecurityPrivilege`
and audit writes (`CAP_AUDIT_WRITE`) to `SeAuditPrivilege`. Requests
that need no capability — dumps of the routing table or the link list
— are answered for any caller. <a id="cite-cred.netlink.uncapped-requests-open"></a>

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

## What netlink carries about the sender

A netlink message's metadata (`NETLINK_CB`) records the sender's
projected UID and GID, in the same form `SO_PEERCRED` uses, and
delivers them to a receiving user socket that asked for
`SCM_CREDENTIALS` with `SO_PASSCRED`. <a id="cite-cred.netlink.cb-carries-projected-ids"></a> As everywhere on Peios, those
values are a projection for compatibility and display, not an
authorisation input ([Credential Projection](</kernel/internals/security/credentials.md#trm-3-10-1>)). Netlink between two user sockets is not
a supported identity-carrying transport: it carries the projection and
nothing more, and a program that needs the peer's token uses an
`AF_UNIX` socket ([Impersonation Levels](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-1>)).

---

# System V IPC

_Peios Kernel / Internals / KACS / System V IPC_

> Find the Peios kernel articles about system v ipc.

Use these articles to understand system v ipc in the Peios kernel.

- [Objects and Their Descriptors](</kernel/internals/kacs/system-v-ipc/objects-and-their-descriptors.md>)

---

# Objects and Their Descriptors

_Peios Kernel / Internals / KACS / System V IPC_

> Every System V message queue, shared memory segment and semaphore array carries a security descriptor, stamped at creation and enforced through the LSM IPC hooks.

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

System V IPC — message queues (`msgget`), shared memory segments
(`shmget`) and semaphore arrays (`semget`) — predates file descriptors
and paths: an object is named by an integer key, identified by an
integer id, and persists in the kernel until removed or reboot. Linux
protects each with a nine-bit mode in `struct ipc_perm`, checked by
`ipcperms()` against the caller's UID and GID.

On Peios that mode is inert. `CAP_IPC_OWNER` is in KACS's always-allow
set ([DAC Neutralisation](</kernel/internals/kacs/linux-credentials/dac-neutralisation.md#trm-3-10-2>)), so `ipcperms()` never denies on the mode and always
reaches `security_ipc_permission()`; there KACS decides, against a
security descriptor the object carries. <a id="cite-sysvipc.mode-inert"></a>

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

## The descriptor

Each object gets a descriptor when it is created, built from the
creator's effective token: owner and group from the token; the
creator's user SID, `BUILTIN\Administrators` and `SYSTEM` at
`GENERIC_ALL`. <a id="cite-sysvipc.default-descriptor"></a> It is held on the object's LSM blob for the object's
life — persisting with the object across the creator's exit, as SysV
objects do — and released when the object is removed. <a id="cite-sysvipc.descriptor-lifetime"></a>

The rights are those of `<pkm/ipc.h>`:

| Right | Grants |
|---|---|
| `KACS_IPC_READ` | `msgrcv`; `shmat` read-only; `semop` without alter; `GETVAL`, `GETPID`, `GETNCNT`, `GETZCNT`, `GETALL` |
| `KACS_IPC_WRITE` | `msgsnd`; `shmat` read-write; `semop` with alter; `SETVAL`, `SETALL` |
| `KACS_IPC_QUERY_INFORMATION` | `IPC_STAT` and the `SHM_STAT`, `MSG_STAT`, `SEM_STAT` families — together with `KACS_IPC_READ`, since Linux's own `ipcperms()` read check runs before the hook |
| `KACS_IPC_SET_INFORMATION` | `SHM_LOCK`, `SHM_UNLOCK` — `SHM_LOCK` additionally needs `SeLockMemoryPrivilege`, Linux's `CAP_IPC_LOCK` gate |
| `DELETE` | `IPC_RMID` |
| `WRITE_DAC` and `WRITE_OWNER` | `IPC_SET` — one command carries mode, uid and gid, so it needs both |
| `READ_CONTROL` | reading the descriptor with `kacs_get_sd` |

The generic mapping: `GENERIC_READ` is read plus query and
`READ_CONTROL`; `GENERIC_WRITE` is write plus set-information and
`READ_CONTROL`; `GENERIC_EXECUTE` is query and `READ_CONTROL`;
`GENERIC_ALL` is everything above. <a id="cite-sysvipc.generic-mapping"></a>

<a id="trm-3-11-1-2"></a>

## Where the checks run

`ipcperms()` runs for every data operation with the mode bits the
operation would have needed — read, write or both — and
`security_ipc_permission()` maps them to `KACS_IPC_READ` and
`KACS_IPC_WRITE` and runs AccessCheck for the caller's effective token,
under the caller's PIP context, against the object's descriptor. <a id="cite-sysvipc.data-ops-access-check"></a> The
`*get` path with an existing key goes through the same check with the
requested mode. <a id="cite-sysvipc.get-existing-key-checked"></a> The control operations go through the per-object
`shmctl`, `msgctl` and `semctl` hooks, which map the command to the
right in the table above; commands that address no object
(`IPC_INFO`, `SHM_INFO`, `MSG_INFO`, `SEM_INFO`) need nothing. <a id="cite-sysvipc.info-commands-unchecked"></a>

Linux's own ownership check on `IPC_SET` and `IPC_RMID` — that the
caller's effective UID matches the object's creator or owner, or holds
`CAP_SYS_ADMIN` — still runs first, on the projected UID, and cannot be
relaxed by the descriptor: the hooks only ever further restrict. <a id="cite-sysvipc.linux-owner-check-first"></a> So an
administrator who is not the object's creator needs both the
descriptor's `DELETE` (which the default grants Administrators) and
`SeTcbPrivilege` (what `CAP_SYS_ADMIN` maps to) to remove it. The
`uid`, `gid` and `mode` that `IPC_SET` writes remain as Linux stores
them and are what `ipcs` and `IPC_STAT` report; they are informational,
as file mode bits are under FACS.

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

## Reading and changing a descriptor

A SysV object has no fd and no path, so `kacs_get_sd` and `kacs_set_sd`
address it by kind and id: one of `KACS_SD_AT_SYSV_SHM`,
`KACS_SD_AT_SYSV_MSG` or `KACS_SD_AT_SYSV_SEM` in `flags`, the object
id in `dirfd`, and a NULL path. <a id="cite-sysvipc.sd-addressing"></a> The object is looked up in the caller's
IPC namespace; an unknown id is `EINVAL`, and so is a removed one,
because `IPC_RMID` drops the id from the namespace in the same step
that marks the object deleted — `EIDRM` is reserved for a lookup that
races that removal and finds the object already dead. <a id="cite-sysvipc.sd-lookup-errors"></a>
Reading needs the rights the requested `SECURITY_INFORMATION` implies
(`READ_CONTROL` for owner, group and DACL; `ACCESS_SYSTEM_SECURITY`
for the SACL), changing needs `WRITE_DAC` or `WRITE_OWNER` as for any
object, and the new descriptor is merged into the existing one
component by component, as for a process descriptor ([Process Security Descriptors](</kernel/internals/kacs/process-security/process-security-descriptors.md#trm-3-3-3>)).

<a id="trm-3-11-1-4"></a>

## Names

The key namespace is claim-on-create: whoever calls `*get` with
`IPC_CREAT` on a free key owns the object, and nothing prevents a
process from claiming a key another program expected to create — the
same shape as the abstract socket namespace and `/dev/shm`. <a id="cite-sysvipc.key-claim-on-create"></a> The
descriptor protects the object once it exists; it cannot protect the
name. A program that needs a specific key uses `IPC_EXCL` and treats a
failure as a signal, and a program that needs identity-carrying
messaging uses an `AF_UNIX` socket ([Impersonation Levels](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-1>)): a message queue conveys no
sender identity, and `msgrcv` returns bytes and a type, nothing more.

---

# Network objects

_Peios Kernel / Internals / KACS / Network objects_

> Find the Peios kernel articles about network objects.

Use these articles to understand network objects in the Peios kernel.

- [Port Reservations](</kernel/internals/kacs/network-objects/port-reservations.md>)
- [Socket Identity](</kernel/internals/kacs/network-objects/socket-identity.md>)

---

# Port Reservations

_Peios Kernel / Internals / KACS / Network objects_

> Binding a TCP or UDP port is an access check against a reservation — a security descriptor keyed by protocol and port range, read from the registry — not a privilege test against a port number.

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

Ports are a shared, unowned namespace. Linux protects it with one rule:
`bind(2)` below port 1024 needs `CAP_NET_BIND_SERVICE`, and everything
above is anyone's. That is too coarse in one direction — any privileged
process gets every low port — and absent in the other: nothing protects
8080, 3306 or 5432 from whichever process asks first.

On Peios the only thing worth authorising about a port is the **claim**
— binding a non-zero port — and it is authorised the way everything
else is: by a security descriptor. `CAP_NET_BIND_SERVICE` is in the
always-allow set ([DAC Neutralisation](</kernel/internals/kacs/linux-credentials/dac-neutralisation.md#trm-3-10-2>)), so the Linux floor never refuses first, and
every claim reaches `security_socket_bind()`, where KACS decides. <a id="cite-net.port.floor-never-refuses"></a>

The precedent is not Linux but HTTP.sys's URL reservations on Windows:
a sparse table of namespace prefixes, each carrying a descriptor,
consulted when a name is claimed, default-permissive where nothing is
reserved. This chapter moves that model down to the port layer.

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

## The object

A **reservation** is a selector mapped to a descriptor. The selector
names a set of protocols and an inclusive port range:

```
<proto>[,<proto>]:<lo>[-<hi>]      proto ∈ tcp | udp | *
```

`tcp:80`, `udp:53`, `tcp,udp:1-1023`, `*:8080`. Ports are decimal,
1–65535, no leading zeros, `lo <= hi`; a protocol may not repeat, so
every selector has one spelling. <a id="cite-net.port.selector-grammar"></a> The address family is deliberately not
part of the selector: a reservation covers IPv4 and IPv6 alike, or
dual-stack squatting — claiming the v6 side of a port reserved on v4 —
would bypass it. <a id="cite-net.port.family-agnostic"></a>

The rights are those of `<pkm/net.h>`:

| Right | Grants |
|---|---|
| `KACS_PORT_BIND` (`0x00000001`) | `bind(2)` to any port the selector contains |
| `READ_CONTROL` | reading the descriptor |

That is the whole mask. Editing a reservation is a registry write,
governed by the registry key's own descriptor — one edit policy for the
table — so `WRITE_DAC` and `WRITE_OWNER` inside a port descriptor mean
nothing and are never honoured. The generic mapping is `GENERIC_EXECUTE`
→ `PORT_BIND`, `GENERIC_READ` → `READ_CONTROL`, `GENERIC_WRITE` → nothing,
`GENERIC_ALL` → both. <a id="cite-net.port.generic-mapping"></a>

<a id="trm-3-12-1-2"></a>

## The table

Reservations live as **values** under one registry key:

```
Machine\System\Network\TcpIp\PortReservations\
    @                 REG_BINARY   SD     the default reservation
    tcp,udp:1-1023    REG_BINARY   SD
    tcp:80            REG_BINARY   SD
```

Each value's name is its selector and its data a self-relative
descriptor. The key's unnamed default value, `@`, is the **default
reservation**: the descriptor for every port no selector contains. <a id="cite-net.port.default-reservation"></a> The
shipped seed grants `PORT_BIND` to Everyone on `@` — an unreserved port
is anyone's, as on Windows — and to SYSTEM and the `bind-low-ports`
capability SID on `tcp,udp:1-1023`, which is the Linux convention
restated as policy. <a id="cite-net.port.shipped-seed"></a> Services then carry their own entries:
`tcp:80,443 → NT SERVICE\httpd: PORT_BIND`, which composes with
per-service SIDs so that a compromised `sshd` cannot take 443 even
though both are "privileged".

The kernel reads the key whole and **rejects it whole**. Every name must
parse, every descriptor must parse, exactly one `@` must exist, and no
two selectors of equal width may overlap — the most specific match
would be ambiguous, and the kernel refuses to guess. <a id="cite-net.port.table-all-or-nothing"></a> On any failure the
load is audited and the previous table stays in force. <a id="cite-net.port.rejected-load-keeps-previous"></a>
The rejection is recorded as `kacs.config.value.rejected` ([Audit Event Schemas](</kernel/internals/kacs/auditing/event-families-and-delivery.md#trm-3-c>)):
`config.key.path` names the key, `config.name` the value at fault where
one is, and `outcome.reason` why — `empty`, `too-large`, `bad-selector`,
`bad-descriptor`, `duplicate-default`, `missing-default` or `overlap` —
with `policy.previous-retained` true and `policy.fallback` saying whether
what stayed in force is the compiled-in table. <a id="cite-net.port.rejected-load-recorded"></a> Nested overlap,
and overlap between selectors of different widths, is how specificity
works and is accepted. <a id="cite-net.port.nested-overlap-accepted"></a>

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

## The decision

At `bind(2)` on an `AF_INET` or `AF_INET6` socket whose protocol is TCP,
UDP or UDP-Lite:

1. If the requested port is 0 — ephemeral allocation — nothing is
   checked. Protocols no reservation covers (SCTP, raw) pass untouched. <a id="cite-net.port.ephemeral-unchecked"></a>
2. The **most specific** reservation containing `(protocol, port)` is
   selected: the one covering the fewest ports, regardless of how many
   protocols it names. None → the default reservation. <a id="cite-net.port.most-specific-match"></a>
3. The caller's effective token is evaluated against that descriptor
   for `PORT_BIND`, through the ordinary AccessCheck pipeline ([AccessCheck Overview](</kernel/internals/kacs/access-check/accesscheck-overview.md#trm-3-8-1>))
   with PIP context, privilege-use marking and audit events — a port
   descriptor may carry a SACL, and its decisions surface through the
   same KMES stream as any other object's, with `object.kind`
   `socket`. <a id="cite-net.port.access-check"></a>
4. Deny → `-EACCES`. Grant → the bind proceeds, and the caller's token is
   recorded on the socket as its **binder**. <a id="cite-net.port.deny-eacces"></a>

An explicit `bind(2)` before an outbound `connect(2)` meets the same
rule; it is not special-cased.

**Rebinding.** Binding onto a port that is already bound — with
`SO_REUSEADDR` or `SO_REUSEPORT` — is still a `bind(2)` and still meets
the reservation. <a id="cite-net.port.rebind-meets-reservation"></a> The rule beyond that is that the new binder's user SID
must equal the existing binder's, or the caller must hold
`SeTcbPrivilege`: rebind is a property of the current binding, not of
policy, and a right on the reservation that let one principal rebind
onto another's port is a thing nothing legitimately needs. <a id="cite-net.port.rebind-same-sid-or-tcb"></a> The binder
recorded on each socket is what makes that comparison local; the
comparison itself is applied where the stack resolves bind conflicts,
and Linux already applies the same-owner half of it for `SO_REUSEPORT`
by comparing the sockets' projected UIDs.

<a id="trm-3-12-1-4"></a>

## Before the registry

The table comes from the registry through the same self-configuration
path LCS uses for its own limits ([The Bootstrap Problem](</kernel/internals/lcs/bootstrap/dependencies-and-boot-sequence.md#trm-5-10-1>)): read at the first source's
registration, then watched, so a change to the key is live without a
restart. <a id="cite-net.port.table-watched-live"></a> Until the first successful load — early boot, or a registry
that never becomes available — a **compiled-in fallback** answers:
owner and group SYSTEM, one entry granting SYSTEM `PORT_BIND`, nobody
else. <a id="cite-net.port.compiled-in-fallback"></a> It is stricter than the shipped seed on purpose: nothing but
system components should be claiming ports before the registry exists.

The fallback is **replaced, never merged**. The moment the key loads it
is the sole authority; if a later load is rejected the last good table
stays, not the fallback. <a id="cite-net.port.fallback-replaced-not-merged"></a> Effective policy therefore never depends on
boot timing.

<a id="trm-3-12-1-5"></a>

## What this retired

`SeBindPrivilegedPortPrivilege` (bit 63) was the KACS privilege
`CAP_NET_BIND_SERVICE` mapped to before this object existed. A
reservation's grant is an ACE, and an ACE names a SID, not a privilege;
keeping the privilege would have been a second authorisation path
around the descriptor. It is retired and its bit is not reused. <a id="cite-net.port.privilege-retired"></a> Low
ports are granted through the capability SID on the `1-1023`
reservation, which reaches a token by confinement — peinit for a
service, or positive confinement from the authority at logon for a
user.

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

## Tracing <a id="cite-net.port.tracing"></a>

Every decision emits `kacs:kacs_socket_bind` with reason `port-bind`:
`desired` carries `PORT_BIND`, `max_imp` carries the port, and `ret` the
verdict. Table loads emit reason `port-table`. See Appendix 3.C for the audit
events an evaluated descriptor's SACL can produce.

---

# Socket Identity

_Peios Kernel / Internals / KACS / Network objects_

> The governing identity KACS stamps on every inet socket for network policy — which token, taken when, and how the engine reads it.

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

Network policy speaks of programs, and a packet carries no program. What
carries one is the socket: KACS records on every `AF_INET` and
`AF_INET6` socket the **identity that governs its traffic**, and the
network policy engine (Chapter 6, [The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)) reads it at the first judgment
of each flow. <a id="cite-net.socket.stamp-on-inet-sockets"></a> AF_UNIX sockets carry the peer-identity machinery of
[Impersonation Levels](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-1>) instead and are not stamped.

<a id="trm-3-12-2-1"></a>

## The stamp

The stamp is the caller's **effective token** — the impersonation token
during impersonation, the primary otherwise — held by a counted
reference, together with the process facts of that moment: the process
GUID ([PSB Fields](</kernel/internals/kacs/process-security/psb-fields.md#trm-3-3-2>)), the thread-group id, and the task's `comm`. <a id="cite-net.socket.stamp-contents"></a> Choosing the
effective token means a service thread acting for a client attributes
the socket to the client, exactly as file creation and audit do under
impersonation; the service's own identity is then not on the socket for
that flow.

It is taken at every act that commits the socket to a role, and the
last one governs: <a id="cite-net.socket.last-act-governs"></a>

| Act | Where |
|---|---|
| creation | `socket_post_create`; a kernel socket (`sock_create_kern`) is stamped as the **kernel's**, with no token <a id="cite-net.socket.kernel-socket-stamp"></a> |
| `bind(2)` | after the port reservation permits it ([Port Reservations](</kernel/internals/kacs/network-objects/port-reservations.md#trm-3-12-1>)) |
| `listen(2)` | `socket_listen` |
| `connect(2)` | `socket_connect` |
| `accept(2)` | `sk_clone_security`: the child inherits the listener's stamp, its own reference <a id="cite-net.socket.accept-inherits"></a> |
| `KACS_SO_RESTAMP` | any state: the caller's effective identity replaces the stamp |

Restamping is what makes a hand-off well defined. A listener opened by
one program and passed to another — socket activation, a descriptor
store, a broker — is governed by whichever program last committed it,
and a program that receives a socket it did not create can say so
explicitly with `KACS_SO_RESTAMP`, self-gated like every attestation of
one's own identity. <a id="cite-net.socket.restamp-self-gated"></a> Sockets that never pass through these hooks (a task
with no token in early boot) read as *unstamped*, which the engine
treats as the kernel's and confesses. <a id="cite-net.socket.unstamped-reads-kernel"></a>

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

## Reading it

The engine reads the stamp with `pkm_kacs_socket_owner()`
(`<linux/peios_ntfe.h>`): a counted token reference the caller releases
with `pkm_kacs_socket_owner_put()`, and a copy of the kind, GUID, pid and
comm. <a id="cite-net.socket.owner-accessor"></a> The copy is what makes the facts outlive the process; the
reference is what makes them outlive the socket — a flow keeps its
identity for its life ([The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)) even after the socket that started it is
gone. The fields live under their own lock, taken with bottom halves
disabled, because both the accept path and the engine's read run in
softirq context.

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

## Final release

Once the socket's last user is gone, KACS releases the token references
and security descriptor owned by the socket. This also releases any
peer, listener, binder and send-cache references; each field owns its
own reference even when several refer to the same token. Final cleanup
can run from an RCU callback and must not sleep or acquire the locks
used to coordinate live socket users. It has exclusive ownership at
this point. References already taken by a flow or another reader remain
valid until that reader releases them. <a id="cite-net.socket.final-release-rcu-safe"></a>

<a id="trm-3-12-2-4"></a>

## Tracing <a id="cite-net.socket.tracing"></a>

Every stamp emits `kacs:kacs_socket_token` with reason `owner`; the
`max_imp` field carries the kind (1 program, 2 kernel). See Appendix
3.C.

---

# Mount namespaces

_Peios Kernel / Internals / KACS / Mount namespaces_

> Find the Peios kernel articles about mount namespaces.

Use these articles to understand mount namespaces in the Peios kernel.

- [A Private Mount Table](</kernel/internals/kacs/mount-namespaces/a-private-mount-table.md>)

---

# A Private Mount Table

_Peios Kernel / Internals / KACS / Mount namespaces_

> A mount namespace is a KACS object — any process may create one without privilege, and what it may then do to its own mount table is decided by the namespace's security descriptor, not by a capability manufactured in a user namespace.

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

A mount namespace is a private copy of the kernel's mount table: the
map from directory paths to the filesystems mounted there. Linux
answers "who may change this table" with `CAP_SYS_ADMIN` in the user
namespace that owns it, and lets an unprivileged process manufacture
that capability by creating a user namespace first — which is how
bubblewrap, and every unprivileged container tool built the same way,
gets a private root.

On Peios that route leads nowhere. The capability switchboard discards
the target user namespace and answers from the token's privileges
alone ([DAC Neutralisation](</kernel/internals/kacs/linux-credentials/dac-neutralisation.md#trm-3-10-2>)), so being root in a user namespace confers nothing, and
`CAP_SYS_ADMIN` maps to `SeTcbPrivilege`. KACS answers the question the
way it answers every other: the mount namespace is an object with a
security descriptor, and changing it is an access check. <a id="cite-mntns.object-model"></a>

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

## The object

Every mount namespace other than the initial one carries a security
descriptor, minted in `copy_mnt_ns()` from the creating task's effective
token and released when the namespace is. <a id="cite-mntns.descriptor-lifetime"></a> The initial namespace, and the
anonymous namespaces `open_tree(OPEN_TREE_CLONE)` and `fsmount` create
for detached trees, carry none. <a id="cite-mntns.initial-has-no-descriptor"></a>

The minted descriptor names its creator and nobody else: owner and
group come from the token, and the DACL is a single allow ACE granting
the creator's user SID `GENERIC_ALL`. <a id="cite-mntns.default-descriptor"></a> `SYSTEM` and
`BUILTIN\Administrators`, which the SysV IPC and socket defaults name,
are absent on purpose — the privilege rung of the mount gate admits them
before the descriptor is read, so an ACE would only pretend the
descriptor was what let them in.

The rights are those of `<pkm/mntns.h>`:

| Right | Grants |
|---|---|
| `KACS_MNTNS_MOUNT` | changing the table: a bind mount, an unmount, `pivot_root` |
| `KACS_MNTNS_ENTER` | joining the namespace with `setns` — defined so the descriptor's meaning is fixed; no code consults it yet, and `setns` into a mount namespace still needs `SeTcbPrivilege` |
| `READ_CONTROL`, `WRITE_DAC`, `WRITE_OWNER` | the standard rights, which `KACS_MNTNS_ALL_ACCESS` includes; nothing exposes a namespace's descriptor to `kacs_get_sd` or `kacs_set_sd` yet |

The generic mapping: `GENERIC_WRITE` is `KACS_MNTNS_MOUNT` and
`WRITE_DAC`; `GENERIC_EXECUTE` is `KACS_MNTNS_ENTER` and `READ_CONTROL`;
`GENERIC_READ` is `READ_CONTROL` alone, there being nothing to read from
a namespace beyond its descriptor; `GENERIC_ALL` is
`KACS_MNTNS_ALL_ACCESS`. <a id="cite-mntns.generic-mapping"></a>

<a id="trm-3-13-1-2"></a>

## Creating one

`unshare(CLONE_NEWNS)`, and `clone` with `CLONE_NEWNS`, need no
privilege when the mount namespace is the only namespace requested. <a id="cite-mntns.create-unprivileged"></a>
Every other namespace type — and any combination that includes one —
keeps the `CAP_SYS_ADMIN` gate in `kernel/nsproxy.c`, which the
switchboard answers with `SeTcbPrivilege`. <a id="cite-mntns.other-types-stay-gated"></a> A user namespace may still be
created alongside, as upstream allows; it changes nothing about what
follows.

A table created by a task that does not hold the mount privilege
receives its mounts as *slaves* of the parent table's, exactly as
upstream does for a copy owned by a different user namespace:
propagation runs parent to child only, so whatever the creator mounts
in its own table never appears in the one it copied. <a id="cite-mntns.unprivileged-copy-is-slave"></a> A table created
with the privilege is copied as upstream copies it, peers and all.

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

## The mount gate

`may_mount()` in `fs/namespace.c` is the gate for `mount`, `umount2`,
`pivot_root`, `open_tree(OPEN_TREE_CLONE)`, `fsmount`, `move_mount` and
`mount_setattr`, and for `fsopen` and `fspick` in `fs/fsopen.c`.
`mount_capable()` in `fs/super.c` is the second
gate a new filesystem passes, when its superblock is brought into being.
Under KACS both take the operation as an argument, with the filesystem
type where one is being created, and ask `pkm_kacs_may_mount_op()` in
three rungs, against the caller's effective token and the descriptor of
the caller's current namespace: <a id="cite-mntns.gate-rungs"></a>

1. **Privilege.** A token holding `SeManageVolumePrivilege` or
   `SeTcbPrivilege`, enabled, is admitted to every operation in every
   namespace, and the privilege is marked used. This rung is decided
   first and alone: a token that holds the privilege never reaches the
   descriptor, and a token that does not is never asked the privilege
   question, so an unprivileged caller's routine bind mount records no
   privilege refusal. <a id="cite-mntns.gate-privilege-first"></a>
2. **No descriptor.** In a namespace with no descriptor — the initial
   one — nothing else admits anything. This is the whole of the rule that
   the root table keeps: without the privilege, no process changes it. <a id="cite-mntns.root-table-privilege-only"></a>
3. **Descriptor.** Otherwise, and only for an operation the descriptor
   can admit, AccessCheck for `KACS_MNTNS_MOUNT` runs against the
   namespace's descriptor under the caller's PIP context, exactly as it
   does for a socket or a SysV object. <a id="cite-mntns.gate-descriptor-check"></a>

The operations the descriptor can admit are the ones that put no
kernel filesystem parser of an untrusted image in reach of the caller: <a id="cite-mntns.admissible-operations"></a>

| `mount(2)` shape | Gate operation | Admissible by descriptor |
|---|---|---|
| `MS_BIND`, with or without `MS_REC` | bind | yes |
| `umount2` without `MNT_FORCE` | unmount | yes |
| `pivot_root` | pivot_root | yes |
| a new `tmpfs`, `proc` or `stratafs` (`do_new_mount`) | new filesystem | yes |
| any other filesystem type | new filesystem | no |
| `MS_REMOUNT`, including `MS_REMOUNT\|MS_BIND` | other | no |
| `MS_MOVE`; `MS_SHARED`, `MS_PRIVATE`, `MS_SLAVE`, `MS_UNBINDABLE` | other | no |
| `open_tree(OPEN_TREE_CLONE)`, `fsopen`, `fspick`, `fsmount`, `move_mount`, `mount_setattr` | other | no |

The filesystem types a descriptor can admit are an allowlist KACS keeps,
and it holds exactly `tmpfs`, `proc` and `stratafs`: all three read
nothing but the caller's own mount options. tmpfs has no backing image,
proc is a view of the kernel's own state, and stratafs is a view of
directories the caller can already traverse, every access through it
decided on the providing object ([Access Check Delegation](</kernel/internals/stratafs/security/access-check-delegation.md#trm-4-6-1>)). A type that parses an image —
ext4, squashfs, iso9660, ntfs3 — is refused before the type is even
looked up. The list is an attack-surface list and not a policy knob:
who may change a table is decided by the table's descriptor alone, and
the same descriptor that admits tmpfs refuses ext4. <a id="cite-mntns.fs-type-allowlist"></a>

A stratafs stack admitted this way is read-only or absent-tolerant.
stratafs's own admission ([Mount Admission](</kernel/internals/stratafs/strata-and-mounting/mount-admission.md#trm-4-2-3>)) refuses a `create` stratum to any
caller outside the initial user namespace or without `CAP_SYS_ADMIN`,
which is `SeTcbPrivilege`, and that test runs after the gate, so an
unprivileged caller that asks for one gets `EPERM` from stratafs
whatever its table's descriptor grants. Copy-up carries no add-entry
right of its own, which is why a writable stack is authority in itself
and stays with the TCB; a private table's writable paths are tmpfs, or
bind mounts of directories the caller owns. <a id="cite-mntns.stratafs-read-only-only"></a> Admitting the type does put
stratafs's option parser and stack validation in reach of unprivileged
input for the first time; both fail closed with `EINVAL` on a relative
stratum, a duplicate, `create` combined with `ro`, an empty stack or
more than sixteen strata, and with `ENOENT` on a missing stratum not
marked `am`.

Everything in the *no* rows needs the privilege whatever the descriptor
grants, and `MNT_FORCE` additionally keeps its own `CAP_SYS_ADMIN` test
on the superblock's user namespace. A mount that the gate admits still
goes through every check upstream applies afterwards: the bind source is
looked up through the caller's own table, an unmount needs a mount
point that belongs to it, and `pivot_root` needs the propagation
conditions it always needed, which the slave copy of an unprivileged
table satisfies.

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

### An unprivileged tmpfs is stamped for its creator

A fresh tmpfs is deny-missing under FACS ([File Descriptor Storage](</kernel/internals/kacs/file-security/descriptor-storage-and-caching.md#trm-3-9-5>)): nothing on it carries
a descriptor, so nothing on it is reachable until someone sets the
superblock's mount policy, which `kacs_set_mount_policy` reserves to the
mount privilege. That is right for the system's own overlays, which are
seeded deliberately, and it would leave a tmpfs admitted by a namespace
descriptor permanently empty. So at `sb_kern_mount`, a tmpfs brought
into being by a token that holds no mount privilege is stamped
synthesize-ephemeral with a template descriptor the kernel mints itself:
owner and group from the mounter's token, one allow ACE granting the
mounter's user SID `GENERIC_ALL` — the same shape as the namespace
descriptor. <a id="cite-mntns.unprivileged-tmpfs-stamped"></a> The policy generation moves to 1, which retires the
deny-missing default the root inode's creation cached during
`fill_super`. The mounter cannot choose the template, and a superblock
whose policy `kacs_set_mount_policy` has already set is left alone. A
privileged mounter's tmpfs is untouched: it keeps the magic default and
the mounter seeds it, as before. <a id="cite-mntns.privileged-tmpfs-untouched"></a> proc is unmanaged and needs no
stamp; a second proc mount in the same pid namespace shows the same
processes under the same per-process checks.

So a process whose whole world is a directory of its choosing is:

```
unshare(CLONE_NEWNS);
mount(dir, dir, NULL, MS_BIND, NULL);
chdir(dir);
pivot_root(".", ".");
umount2(".", MNT_DETACH);
chdir("/");
```

with no user namespace and no privilege. <a id="cite-mntns.private-root-sequence"></a> The bind makes the directory a
mount point, which `pivot_root` requires; pivoting onto the same path
stacks the old root on the new one, and detaching `.` drops it.

<a id="trm-3-13-1-4"></a>

## What the object does not change

The token never changes at `exec` ([setuid Behaviour](</kernel/internals/kacs/linux-credentials/setuid-behaviour.md#trm-3-10-3>)), so a program run inside a
private table has exactly the authority of the process that built it,
and a fake `/etc` fools nobody but its author. Every access to a file
reached through a bind mount is decided on the real object's
descriptor, so a bind mount shows a name and denies at open. The
kernel's own helpers — `modprobe` and its kin — are executed in the
initial namespace and refused unless TCB-signed ([Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)). A signed
binary's PIP tier is derived from the binary and not from the table it
was found in, and library verification, where a process enables it,
compares signatures at `mmap` rather than paths. <a id="cite-mntns.no-new-authority"></a>

<a id="trm-3-13-1-5"></a>

## Tracing

The `kacs:kacs_mntns` event records a descriptor minted at namespace
creation, each rung of the gate, and a tmpfs stamped for its creator,
with the operation code, the right asked of the descriptor where a rung
reached it, a reason from `<pkm/trace.h>` — `sd-alloc`, `sd-alloc-fail`,
`gate-privilege`, `gate-no-sd`, `gate-op-not-admitted`,
`gate-sd-decision`, `gate-pip-context`, `gate-fs-not-admitted`,
`sb-stamp`, `sb-stamp-fail` — and the verdict. <a id="cite-mntns.trace-event"></a>

---

# Auditing

_Peios Kernel / Internals / KACS / Auditing_

> Find the Peios kernel articles about auditing.

Use these articles to understand auditing in the Peios kernel.

- [Event families and delivery](</kernel/internals/kacs/auditing/event-families-and-delivery.md>)

---

# Event families and delivery

_Peios Kernel / Internals / KACS / Auditing_

> The audit records KACS emits through KMES — the event families, their shared payload records, and how they are delivered.

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

KACS emits its audit records through KMES with origin class 2 ([Event Model](</kernel/internals/kmes/event-model.md#trm-2-2>)). <a id="cite-audit-events.origin-class-two"></a>
Each event's payload is a msgpack map whose field paths follow [PGSS field
conventions](https://learn.peios.org/specifications/pgss/events/fields/): `access.requested` is the key `requested` inside the map under
`access`, never a key containing a dot, and a value the emitter does
not have is absent rather than nil. The shared `subject` group — the
effective token's `subject.token.*`, the PIP state in `subject.pip.*`,
and the calling process as `emitter.process.{pid,name,executable}` — is
attached at emission time from the resolved call context rather than by
the evaluation pipeline ([Auditing in AccessCheck](</kernel/internals/kacs/access-check/auditing-in-accesscheck.md#trm-3-8-9>)). A process with no executable, such as a
kernel thread, has `executable` left out; the record is still written.

This appendix describes where KACS emits each event. The `.evman` fragments
in `peios/packages/data/evman/` define the payload schemas and field meanings.
Use `evman <event-type>` for an installed event definition, or `evman <field>`
for a field's type, meaning, and carrying events.

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

## Event families

| Event type | Emitted by |
|---|---|
| `kacs.audit.access.checked` | The SACL walk, and token audit-policy forcing. <a id="cite-audit-events.access-audit-record"></a> |
| `kacs.audit.handle.used` | Enforcement points, per operation, against a handle's continuous audit mask. <a id="cite-audit-events.continuous-audit-record"></a> |
| `kacs.audit.privilege.used` | Privilege-use auditing, for the five AccessCheck-influencing privileges in an access check, and at a Linux capability or volume gate ([The Privilege Model](</kernel/internals/kacs/privileges/the-privilege-model.md#trm-3-4-1>)). <a id="cite-audit-events.privilege-use-record"></a> |
| `kacs.audit.descriptor.changed` | A change to the descriptor of a file, token, process or System V IPC object (below). |
| `kacs.impersonation.started`, `kacs.impersonation.reverted` | An impersonation attempt, and the end of an impersonation ([Impersonation Lifecycle](</kernel/internals/kacs/impersonation/state-transitions.md#trm-3-5-3>)). |
| `kacs.caap.sacl.skipped`, `kacs.caap.staging.diverged` | A CAAP rule SACL that could not be parsed or evaluated; a staged result that differs from the effective one. <a id="cite-audit-events.caap-policy-diagnostic-record"></a> |
| `kacs.session.destroyed` | LogonSession teardown ([LogonSessions and Revocation](</kernel/internals/kacs/tokens/logonsessions-and-revocation.md#trm-3-2-7>)). <a id="cite-audit-events.logon-session-destroyed-record"></a> |
| `kacs.descriptor.rejected` | A descriptor xattr that exists but fails structural validation ([File Descriptor Storage](</kernel/internals/kacs/file-security/descriptor-storage-and-caching.md#trm-3-9-5>)). <a id="cite-audit-events.corrupt-sd-record"></a> |
| `kacs.caap.policy.changed` | `kacs_set_caap` installing, replacing or removing a central access policy ([Central Access and Auditing Policy](</kernel/internals/kacs/access-check/central-access-and-auditing-policy.md#trm-3-8-8>)). |
| `kacs.mount.policy.changed` | `kacs_set_mount_policy` ([File Descriptor Storage](</kernel/internals/kacs/file-security/descriptor-storage-and-caching.md#trm-3-9-5>)). |
| `kacs.config.value.rejected` | A port reservation table refused whole ([Port Reservations](</kernel/internals/kacs/network-objects/port-reservations.md#trm-3-12-1>)). |
| `stratafs.file.copied-up` | StrataFS copy-up lifecycle and failure ([The StrataFS Copy-Up Context](</kernel/internals/stratafs/security/kacs-admission-and-object-phases.md#trm-3-9-7>)). <a id="cite-audit-events.stratafs-copy-up-record"></a> |
| `stratafs.mutation.refused` | A StrataFS arrangement refusal. <a id="cite-audit-events.stratafs-mutation-refused-record"></a> |

`kacs.descriptor.rejected` carries `object.kind` `file` and
`outcome.reason` `corrupt`. It does not name the file by path: the
descriptor is read through internal path anchors whose mount cannot
always be resolved to an absolute path, so `object.file.path` is absent.
It names the file by `object.file.inode` and `object.file.device` (the
filesystem's `st_dev`) instead, carries the stored attribute's length as
`object.sd.length`, and carries the `subject` whose access made KACS read
the descriptor. <a id="cite-audit-events.corrupt-sd-identifies-file"></a>

KACS also writes `kacs.signature.crypto.failed` once at boot when the
signature transform is unavailable ([Binary Signature Verification](</kernel/internals/kacs/executable-trust/signature-verification.md#trm-3-6>)), carrying
`signature.crypto-stage` `boot-probe` and the negative `outcome.errno`.

The `privilege.name` field of a `kacs.audit.privilege.used` event carries a canonical
name. A record of an access check (`operation.name` `access-check`)
names one of five — `SeSecurityPrivilege`, `SeTakeOwnershipPrivilege`,
`SeBackupPrivilege`, `SeRestorePrivilege` and `SeRelabelPrivilege` —
the only privileges an access check consults. <a id="cite-audit-events.privilege-five-canonical-names"></a>
A record of a capability or volume gate (`linux-cap`, `volume-mount`)
names whichever privilege the gate spent ([The Privilege Model](</kernel/internals/kacs/privileges/the-privilege-model.md#trm-3-4-1>)). The encoder names
every defined privilege, and a bit with no name fails it closed rather
than emitting an unnamed privilege; a token holding only privileges an
access check does not consult produces no access-check record at all. <a id="cite-audit-events.privilege-encoder-fails-closed"></a>

`kacs.audit.handle.used` carries an `operation.name` naming the enforcement
point: `file.access`, `file.mmap`, `file.mprotect`, `file.permission`,
`file.write`, `file.ioctl`, `file.lock`, `file.fcntl`, `file.truncate`
and `file.fallocate`. <a id="cite-audit-events.continuous-operation-names"></a> It never carries a caller-supplied audit context: its
`object.kind` is always `file`, with the handle's absolute path in
`object.file.path` (absent only if the path cannot be resolved), and it
never sets `fields.attestation.userspace`. <a id="cite-audit-events.continuous-object-context-nil"></a>

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

## Descriptor changes

`kacs.audit.descriptor.changed` records a change to the descriptor of a
file, a token, a process or a System V IPC object by a caller authorised
to make it, whether or not the change then applied. A change that
includes the SACL is always recorded, whatever either descriptor says —
so removing a file's SACL, which leaves nothing to audit the removal
itself, is still recorded. <a id="cite-audit-events.descriptor-changed-sacl-always"></a>
Any other change is recorded when the rights it needed overlap the alarm
mask on the handle it was made through. Only a file handle opened
through FACS carries such a mask, so a change made through a path, or to
a token, a process or an IPC object, is recorded only when it includes
the SACL. <a id="cite-audit-events.descriptor-changed-dacl-by-handle-mask"></a>

The record names the object by `object.kind` and its identity —
`object.file.path` where it can be resolved, `object.token.id` and
`.guid`, `object.process.guid`, or `object.ipc.type` and `.id` — and
describes the change in `object.sd`: the parts set as `components`, and
the length, SHA-256 digest and owner of the descriptor written
(`length`, `digest`, `owner`) and of the one replaced (`length-previous`,
`digest-previous`, `owner-previous`; absent where there was no stored
descriptor). `access.requested` is the rights the change needed, with the
handle's `access.granted`, `access.audit-mask` and the overlap as
`access.matched` — zero when only the SACL made the record exist — for a
change made through one. <a id="cite-audit-events.descriptor-changed-object-kinds"></a>
Registry keys have the same record as `lcs.audit.key.descriptor.changed`.

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

## Delivery

Audit and privilege-use events are delivered **before** any result is
written back to the caller, and a delivery failure fails the syscall
with `EIO` or `EOPNOTSUPP`. <a id="cite-audit-events.delivered-before-result"></a> An audit event cannot be suppressed by
handing the call a bad output pointer.

Three emissions are best-effort by contrast, and drop silently rather
than failing the operation that caused them:

- `kacs.session.destroyed` where the authentication package name is
  not valid UTF-8. <a id="cite-audit-events.best-effort-logon-session-utf8"></a>
- The two StrataFS events on an over-long operation string or path. <a id="cite-audit-events.best-effort-stratafs"></a>
- Any self-emitted payload that would exceed its encoding buffer. <a id="cite-audit-events.best-effort-oversize-payload"></a>

A StrataFS record is not lost for want of memory. When the allocation
for the full record fails, a reduced record is written from a fixed
buffer instead: the same type with the stratum indices, the operation
and the outcome, and without the paths — `object.file.path-relative` and
each `stratum.path` — whose absence marks it as reduced. <a id="cite-audit-events.stratafs-reduced-record"></a>

The transport itself — ring buffer delivery, buffering and drop
accounting — is KMES's ([Ring Buffers](</kernel/internals/kmes/ring-buffers.md#trm-2-5>), [Failure Modes](</kernel/internals/kmes/failure-modes.md#trm-2-7>)).

---

# Integration

_Peios Kernel / Internals / KACS / Integration_

> Find the Peios kernel articles about integration.

Use these articles to understand integration in the Peios kernel.

- [LSM hooks and object state](</kernel/internals/kacs/integration/lsm-hooks-and-object-state.md>)

---

# LSM hooks and object state

_Peios Kernel / Internals / KACS / Integration_

> The KACS security blobs, registered Linux Security Module hooks, and direct entry points at patched file-metadata call sites.

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

KACS registers as the `pkm` Linux Security Module. This appendix is an
implementation inventory for kernel developers: it describes the storage
and call sites behind the contracts in this chapter. These C structures
and callbacks are kernel-private, not userspace layouts or extension APIs.
The exported ABI remains in [KACS ABI Reference](</kernel/userspace/native/kacs/generated-syscall-index.md#trm-3-a>).

The inventory comes from `security/pkm/kacs/lsm.c` (`pkm_blob_sizes` and
`pkm_hooks[]`), the structures in `security/pkm/kacs/lsm_internal.h`, and the callback
implementations listed below. When changing those declarations, update
this inventory with the same change. The hook matrix preserves registration
order; each row names an actual `LSM_HOOK_INIT` entry.

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

## Security-blob inventory

`pkm_blob_sizes` requests eight sized blob families. Each `lbs_*` entry
is initialized with `sizeof` the corresponding structure; Linux's LSM
infrastructure assigns its offset in the object's security storage. Byte
sizes and offsets depend on the build and are not fixed by this manual.

| LSM size entry | KACS structure | State carried |
|---|---|---|
| `lbs_cred` | `pkm_kacs_cred_security` | Token reference, shared `process_state`, projected UID/GID, and the pending descriptor used while overlayfs creates or copies up an inode. |
| `lbs_task` | `pkm_kacs_task_security` | Shared `process_state`, usermode-helper and impersonation state, the applied primary-installation epoch and thread-enrollment callback, deferred privilege-audit work, native-open/create requests, write/metadata decisions, narrowly scoped StrataFS creation, supersede and cleanup context, the deferred deletion in progress at a delete-pending file's last close, the failure status of the last native open, a handle rename in progress, and the lease keys and notes that lease breaks consult. |
| `lbs_sock` | `pkm_kacs_socket_security` | Socket descriptor, conveyed peer/listener identities, token-conveyance cache and impersonation limits, binder identity/reuse decision, and the committed socket-owner identity used by network policy. |
| `lbs_ipc` | `pkm_kacs_ipc_security` | Refcounted descriptor and lock for a System V message queue, shared-memory segment or semaphore array. |
| `lbs_file` | `pkm_kacs_file_security` | Cached `granted_access` and `continuous_audit_mask`, copy-up context and phase generation, the open's NT share registration (`nt_inode`, `nt_classes`, `nt_share`, `nt_intent`), its lease manager and key, its ancestor pin set, `managed`, `delete_on_close`, and the referenced token that will mark the file delete-pending. |
| `lbs_backing_file` | `pkm_kacs_backing_file_security` | Cached `granted_access` and `continuous_audit_mask`, the outer open's share participation and lease key, plus `managed` and `inherited`, for the explicit outer-to-backing-file snapshot transfer. |
| `lbs_inode` | `pkm_kacs_inode_security` | Lock and RCU descriptor-cache pointer, the lazily allocated NT state (`nt`: share counters, delete-pending mark, byte-range locks and leases), the cached read-only special attribute, the ancestor-pin and signed-exec pin counters, and the deferred descriptor-persistence state. Test-only members exist under `CONFIG_SECURITY_PKM_KUNIT`. |
| `lbs_superblock` | `pkm_kacs_superblock_security` | Mount-policy lock, template descriptor bytes/length, policy generation and mount policy. |

The additional `lbs_xattr_count = 1` reserves one xattr-initialization
slot. It is not a ninth object blob or a byte-size declaration.

The file blob uses separate `u8 managed` and `u8 delete_on_close`
fields. The NT state lives in `nt_file.c`, `nt_lock.c` and `nt_lease.c`,
the handle syscalls in `nt_handle.c`, pinning in `nt_pin.c`, and the
special attributes in `sattr.c`. There is no `flags` member or `KACS_FILE_FACS_MANAGED` constant.
The backing-file blob is distinct from the ordinary file blob: its
`inherited` marker records explicit adoption of the outer description's
cached grants and continuous-audit mask ([The StrataFS Copy-Up Context](</kernel/internals/stratafs/security/kacs-admission-and-object-phases.md#trm-3-9-7>)).

The task blob reaches process-wide state through its `process_state`
pointer. The refcounted `pkm_kacs_process_state` contains `process_guid`,
`pip_type`, `pip_trust`, one `u32 mitigation_bits`, the KMES rate bucket,
the `process_sd` reference and process-scoped privilege-audit bookkeeping.
It also holds `primary_lock`, `desired_primary_token` and `primary_epoch`,
which order primary-token installation across the process's threads
([Token Lifecycle](</kernel/internals/kacs/tokens/token-lifecycle.md#trm-3-2-3>)).
PIP identity and the process descriptor are not inline task-blob fields;
the process mitigations are not nine independent booleans. This shared
state is separate from the effective token used during impersonation.

The credential blob's `pending_create_sd` has the lifetime of an override
credential. Overlayfs uses it to stamp the descriptor computed for the
original object or caller/parent onto the actual created inode; credential
preparation does not inherit it into a derived credential. The task blob's
internal SD read/write depth and operation contexts similarly identify
specific kernel work; they are not caller-settable authorization flags.

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

## Registered hook matrix

The current `pkm_hooks[]` table contains 100 registrations. Paths in the
last column are relative to the `pkm` source repository. A callback's
presence here identifies where KACS is called; the operation's access,
privilege and lifetime rules remain specified in the relevant chapter.

| Linux LSM hook | KACS callback | Implementation |
|---|---|---|
| `cred_prepare` | `pkm_kacs_cred_prepare` | `security/pkm/kacs/cred_lifecycle.c` |
| `cred_transfer` | `pkm_kacs_cred_transfer` | `security/pkm/kacs/cred_lifecycle.c` |
| `cred_alloc_blank` | `pkm_kacs_cred_alloc_blank` | `security/pkm/kacs/cred_lifecycle.c` |
| `cred_free` | `pkm_kacs_cred_free` | `security/pkm/kacs/cred_lifecycle.c` |
| `sb_alloc_security` | `pkm_kacs_sb_alloc_security` | `security/pkm/kacs/object_lifecycle.c` |
| `sb_free_security` | `pkm_kacs_sb_free_security` | `security/pkm/kacs/object_lifecycle.c` |
| `sb_kern_mount` | `pkm_kacs_sb_kern_mount` | `security/pkm/kacs/mnt_namespace.c` |
| `inode_alloc_security` | `pkm_kacs_inode_alloc_security` | `security/pkm/kacs/object_lifecycle.c` |
| `inode_free_security_rcu` | `pkm_kacs_inode_free_security_rcu` | `security/pkm/kacs/object_lifecycle.c` |
| `inode_getattr` | `pkm_kacs_inode_getattr` | `security/pkm/kacs/file_metadata.c` |
| `path_notify` | `pkm_kacs_path_notify` | `security/pkm/kacs/namespace.c` |
| `inode_setattr` | `pkm_kacs_inode_setattr` | `security/pkm/kacs/file_metadata.c` |
| `inode_file_getattr` | `pkm_kacs_inode_file_getattr` | `security/pkm/kacs/file_metadata.c` |
| `inode_file_setattr` | `pkm_kacs_inode_file_setattr` | `security/pkm/kacs/file_metadata.c` |
| `inode_xattr_skipcap` | `pkm_kacs_inode_xattr_skipcap` | `security/pkm/kacs/file_metadata.c` |
| `inode_getxattr` | `pkm_kacs_inode_getxattr` | `security/pkm/kacs/file_metadata.c` |
| `inode_setxattr` | `pkm_kacs_inode_setxattr` | `security/pkm/kacs/file_metadata.c` |
| `inode_post_setxattr` | `pkm_kacs_inode_post_setxattr` | `security/pkm/kacs/file_metadata.c` |
| `inode_removexattr` | `pkm_kacs_inode_removexattr` | `security/pkm/kacs/file_metadata.c` |
| `inode_listxattr` | `pkm_kacs_inode_listxattr` | `security/pkm/kacs/file_metadata.c` |
| `inode_copy_up` | `pkm_kacs_inode_copy_up` | `security/pkm/kacs/file_metadata.c` |
| `inode_copy_up_xattr` | `pkm_kacs_inode_copy_up_xattr` | `security/pkm/kacs/file_metadata.c` |
| `inode_follow_link` | `pkm_kacs_inode_follow_link` | `security/pkm/kacs/file_metadata.c` |
| `inode_set_acl` | `pkm_kacs_inode_set_acl` | `security/pkm/kacs/file_metadata.c` |
| `inode_remove_acl` | `pkm_kacs_inode_remove_acl` | `security/pkm/kacs/file_metadata.c` |
| `inode_getsecurity` | `pkm_kacs_inode_getsecurity` | `security/pkm/kacs/file_metadata.c` |
| `inode_permission` | `pkm_kacs_inode_permission` | `security/pkm/kacs/namespace.c` |
| `inode_create` | `pkm_kacs_inode_create` | `security/pkm/kacs/namespace.c` |
| `inode_link` | `pkm_kacs_inode_link` | `security/pkm/kacs/namespace.c` |
| `inode_unlink` | `pkm_kacs_inode_unlink` | `security/pkm/kacs/namespace.c` |
| `inode_symlink` | `pkm_kacs_inode_symlink` | `security/pkm/kacs/namespace.c` |
| `inode_mkdir` | `pkm_kacs_inode_mkdir` | `security/pkm/kacs/namespace.c` |
| `inode_rmdir` | `pkm_kacs_inode_rmdir` | `security/pkm/kacs/namespace.c` |
| `inode_mknod` | `pkm_kacs_inode_mknod` | `security/pkm/kacs/namespace.c` |
| `inode_rename` | `pkm_kacs_inode_rename` | `security/pkm/kacs/namespace.c` |
| `inode_readlink` | `pkm_kacs_inode_readlink` | `security/pkm/kacs/namespace.c` |
| `inode_init_security` | `pkm_kacs_inode_init_security` | `security/pkm/kacs/namespace.c` |
| `inode_post_create_tmpfile` | `pkm_kacs_copy_up_post_create_tmpfile` | `security/pkm/kacs/copy_up.c` |
| `dentry_create_files_as` | `pkm_kacs_dentry_create_files_as` | `security/pkm/kacs/namespace.c` |
| `file_alloc_security` | `pkm_kacs_file_alloc_security` | `security/pkm/kacs/object_lifecycle.c` |
| `backing_file_alloc` | `pkm_kacs_backing_file_alloc` | `security/pkm/kacs/object_lifecycle.c` |
| `file_release` | `pkm_kacs_file_release` | `security/pkm/kacs/object_lifecycle.c` |
| `file_free_security` | `pkm_kacs_file_free_security` | `security/pkm/kacs/object_lifecycle.c` |
| `file_open` | `pkm_kacs_file_open` | `security/pkm/kacs/file_access.c` |
| `file_receive` | `pkm_kacs_file_receive` | `security/pkm/kacs/object_lifecycle.c` |
| `file_permission` | `pkm_kacs_file_permission` | `security/pkm/kacs/file_access.c` |
| `file_ioctl` | `pkm_kacs_file_ioctl` | `security/pkm/kacs/file_access.c` |
| `file_ioctl_compat` | `pkm_kacs_file_ioctl_compat` | `security/pkm/kacs/file_access.c` |
| `file_lock` | `pkm_kacs_file_lock` | `security/pkm/kacs/file_access.c` |
| `file_fcntl` | `pkm_kacs_file_fcntl` | `security/pkm/kacs/file_access.c` |
| `file_truncate` | `pkm_kacs_file_truncate` | `security/pkm/kacs/file_access.c` |
| `kernel_read_file` | `pkm_kacs_kernel_read_file` | `security/pkm/kacs/firmware.c` |
| `kernel_post_read_file` | `pkm_kacs_kernel_post_read_file` | `security/pkm/kacs/firmware.c` |
| `task_alloc` | `pkm_kacs_task_alloc` | `security/pkm/kacs/task_lifecycle.c` |
| `task_free` | `pkm_kacs_task_free` | `security/pkm/kacs/task_lifecycle.c` |
| `sk_alloc_security` | `pkm_kacs_sk_alloc_security` | `security/pkm/kacs/socket.c` |
| `sk_free_security` | `pkm_kacs_sk_free_security` | `security/pkm/kacs/socket.c` |
| `sk_clone_security` | `pkm_kacs_sk_clone_security` | `security/pkm/kacs/socket.c` |
| `socket_post_create` | `pkm_kacs_socket_post_create` | `security/pkm/kacs/socket.c` |
| `socket_bind` | `pkm_kacs_socket_bind` | `security/pkm/kacs/socket.c` |
| `socket_connect` | `pkm_kacs_socket_connect` | `security/pkm/kacs/socket.c` |
| `unix_stream_connect` | `pkm_kacs_unix_stream_connect` | `security/pkm/kacs/socket.c` |
| `unix_may_send` | `pkm_kacs_unix_may_send` | `security/pkm/kacs/socket.c` |
| `socket_listen` | `pkm_kacs_socket_listen` | `security/pkm/kacs/socket.c` |
| `ipc_permission` | `pkm_kacs_ipc_permission` | `security/pkm/kacs/ipc.c` |
| `msg_queue_alloc_security` | `pkm_kacs_ipc_alloc_security` | `security/pkm/kacs/ipc.c` |
| `msg_queue_free_security` | `pkm_kacs_ipc_free_security` | `security/pkm/kacs/ipc.c` |
| `msg_queue_msgctl` | `pkm_kacs_msg_queue_msgctl` | `security/pkm/kacs/ipc.c` |
| `shm_alloc_security` | `pkm_kacs_ipc_alloc_security` | `security/pkm/kacs/ipc.c` |
| `shm_free_security` | `pkm_kacs_ipc_free_security` | `security/pkm/kacs/ipc.c` |
| `shm_shmctl` | `pkm_kacs_shm_shmctl` | `security/pkm/kacs/ipc.c` |
| `sem_alloc_security` | `pkm_kacs_ipc_alloc_security` | `security/pkm/kacs/ipc.c` |
| `sem_free_security` | `pkm_kacs_ipc_free_security` | `security/pkm/kacs/ipc.c` |
| `sem_semctl` | `pkm_kacs_sem_semctl` | `security/pkm/kacs/ipc.c` |
| `task_kill` | `pkm_kacs_task_kill` | `security/pkm/kacs/process_access.c` |
| `ptrace_access_check` | `pkm_kacs_ptrace_access_check` | `security/pkm/kacs/process_access.c` |
| `ptrace_traceme` | `pkm_kacs_ptrace_traceme` | `security/pkm/kacs/process_access.c` |
| `task_setnice` | `pkm_kacs_task_setnice` | `security/pkm/kacs/process_access.c` |
| `task_setscheduler` | `pkm_kacs_task_setscheduler` | `security/pkm/kacs/process_access.c` |
| `task_setioprio` | `pkm_kacs_task_setioprio` | `security/pkm/kacs/process_access.c` |
| `task_setpgid` | `pkm_kacs_task_setpgid` | `security/pkm/kacs/process_access.c` |
| `task_getpgid` | `pkm_kacs_task_getpgid` | `security/pkm/kacs/process_access.c` |
| `task_getsid` | `pkm_kacs_task_getsid` | `security/pkm/kacs/process_access.c` |
| `task_getscheduler` | `pkm_kacs_task_getscheduler` | `security/pkm/kacs/process_access.c` |
| `task_getioprio` | `pkm_kacs_task_getioprio` | `security/pkm/kacs/process_access.c` |
| `task_movememory` | `pkm_kacs_task_movememory` | `security/pkm/kacs/process_access.c` |
| `task_fix_setuid` | `pkm_kacs_task_fix_setuid` | `security/pkm/kacs/cred_projection.c` |
| `task_fix_setgid` | `pkm_kacs_task_fix_setgid` | `security/pkm/kacs/cred_projection.c` |
| `task_fix_setgroups` | `pkm_kacs_task_fix_setgroups` | `security/pkm/kacs/cred_projection.c` |
| `task_prlimit` | `pkm_kacs_task_prlimit` | `security/pkm/kacs/process_access.c` |
| `capable` | `pkm_kacs_capable` | `security/pkm/kacs/capability.c` |
| `capset` | `pkm_kacs_capset` | `security/pkm/kacs/capability.c` |
| `task_prctl` | `pkm_kacs_task_prctl` | `security/pkm/kacs/psb.c` |
| `mmap_file` | `pkm_kacs_mmap_file` | `security/pkm/kacs/psb.c` |
| `mmap_backing_file` | `pkm_kacs_mmap_backing_file` | `security/pkm/kacs/object_lifecycle.c` |
| `file_mprotect` | `pkm_kacs_file_mprotect` | `security/pkm/kacs/psb.c` |
| `bprm_check_security` | `pkm_kacs_bprm_check_security` | `security/pkm/kacs/exec.c` |
| `bprm_creds_from_file` | `pkm_kacs_bprm_creds_from_file` | `security/pkm/kacs/exec.c` |
| `bprm_committing_creds` | `pkm_kacs_bprm_committing_creds` | `security/pkm/kacs/exec.c` |
| `bprm_committed_creds` | `pkm_kacs_bprm_committed_creds` | `security/pkm/kacs/exec.c` |

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

## Direct file-metadata entry points

An LSM hook receives the arguments supplied by the Linux hook API. Some
file-descriptor operations also need the particular open file's cached
FACS grant. PKM's patch series therefore calls KACS directly at the
file-descriptor call site, before the later inode-level work. These
functions are declared and called directly under `CONFIG_SECURITY_PKM`;
they are not additional entries in `pkm_hooks[]` and are not dispatched
through another LSM's hook table.

| File-descriptor operation | Direct KACS entry point | Kernel call site |
|---|---|---|
| Change mode | `pkm_kacs_file_chmod` | `fs/open.c` |
| Change owner/group | `pkm_kacs_file_chown` | `fs/open.c` |
| Change timestamps through a file descriptor | `pkm_kacs_file_utimens` | `fs/utimes.c` |
| Read file attributes through a file descriptor | `pkm_kacs_file_getattr` | `fs/stat.c` |
| Read an xattr through a file descriptor | `pkm_kacs_file_sd_xattr_get` | `fs/xattr.c` |
| Set an xattr through a file descriptor | `pkm_kacs_file_sd_xattr_set` | `fs/xattr.c` |
| Remove an xattr through a file descriptor | `pkm_kacs_file_sd_xattr_remove` | `fs/xattr.c` |

All seven implementations are in `security/pkm/kacs/file_metadata.c`.

The NT handle semantics add direct entry points at other call sites:

| Operation | Direct KACS entry point | Kernel call site |
|---|---|---|
| An open that fails after the open hook | `pkm_kacs_file_open_failed` | `fs/open.c` |
| An `O_PATH` open, refused while delete-pending | `pkm_kacs_file_open_path` | `fs/open.c` |
| A control handle, opened with no data mode | `dentry_open_control` (VFS helper) | `fs/open.c` |
| A read or write, checked against byte-range locks | `pkm_kacs_nt_lock_check_io` | `fs/read_write.c` |
| A content-changing `fallocate` | `pkm_kacs_nt_lock_check_fallocate` | `fs/open.c` |
| Writing or removing the special attributes | `pkm_kacs_sattr_vfs_set`, `pkm_kacs_sattr_vfs_remove` | `fs/xattr.c` |
| Looking up a rename destination | `pkm_filename_parentat` (VFS helper) | `fs/namei.c` | The xattr
functions enforce the file's metadata grant as well as the separate
rules for protected SD attributes; their names do not make raw SD-xattr
access a supported security-descriptor API.

The names `security_file_setattr`, `security_file_getattr`,
`security_file_getxattr` and `security_file_setxattr` do not name hooks
provided by this kernel. In particular, do not confuse them with the
real `inode_file_getattr` and `inode_file_setattr` registrations in the
matrix: those receive a dentry and `struct file_kattr`, not the open file
whose cached grant the direct entry points consult. The metadata decision
record connects the file-level check to the later inode-level operation.
This table covers those file-metadata entry points, not every direct
KACS call in the kernel.

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

## Reserved access-mask bits

`RESERVED_ACCESS_MASK_BITS` in
`security/pkm/kacs/kacs_core/access_mask.rs` is `0x0ce0_0000` (bits 21, 22, 23,
26 and 27, counting from zero). It remains a private evaluator constant,
not a new UAPI definition. [The Algorithm](</kernel/internals/kacs/access-check/the-algorithm.md#trm-3-8-10>) already specifies the public behavior:
reserved bits in a desired mask or any ACE mask reject the check, rather
than being ignored. This inventory records the implementation value
without adding another exported spelling.
