KACS
Peios kernel kacs documentation.
Single-page view · as markdown
Overview
Peios Kernel / Internals / KACS / Start here
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), the Process Security Block (The PSB Model), privileges (The Privilege Model), impersonation (Impersonation Levels), binary signature verification (Binary Signature Verification), Process Integrity Protection (Process Integrity Protection), the AccessCheck algorithm in full (AccessCheck Overview), file enforcement (The Handle Model), and how Peios identity is projected onto the Linux credential model (Credential Projection).
The kernel-private storage and call-site inventory is in LSM integration: 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.
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).
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.
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 records every departure and why.
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): 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).
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).CONFIG_STRATAFS_FS, without which the copy-up API of The StrataFS Copy-Up Context is inert.
Related explanations #
- ABI status and naming differences
- Descriptor and ACE semantics
- Token query semantics
- Socket ABI compatibility
Calling the subsystem #
The native KACS interface reference collects the caller contracts and generated ABI tables.
Topics #
Boot and trust invariants
Peios Kernel / Internals / KACS / Start here
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.
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
for the registered hooks and direct callers.
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.
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.
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, 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.
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) and executable verification (Binary Signature Verification).
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).
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.
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.
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.
The invariant verification #
Use the supported build entry points described in
Building Peios; 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.
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.
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.
Where to go next #
Read Peios kernel behaviour for the Linux compatibility boundaries, KACS process integrity (Process Integrity Protection) for runtime protection, and Building Peios for configuration and build validation.
Tokens
Peios Kernel / Internals / KACS / Tokens
Use these articles to understand tokens in the Peios kernel.
The Token Model
Peios Kernel / Internals / KACS / Tokens
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.
Every live userspace thread has one. 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.
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. At fork the child receives an
independent deep copy, so mutations after fork are invisible across
the process boundary.
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.
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.
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.
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.
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. User-originated asynchronous work that has neither captured credentials nor cached handle authority reaches KACS without a token-bearing credential and fails closed.
Kernel-originated infrastructure work running under the boot SYSTEM credential evaluates as SYSTEM. There is no separate worker-flag-based kernel authority identity.
Token Structure
Peios Kernel / Internals / KACS / Tokens
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). One-way fields can be set or tightened but never cleared or loosened.
Identity core (fixed) #
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.
The group SID set is fixed at creation — adjustment never adds or
removes a SID. 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 token holds at most 1024 group entries including the kernel-injected logon SID, so CreateToken accepts at most 1023 caller-supplied groups.
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). |
Integrity (fixed) #
mandatory_policy is immutable: a process cannot change its own MIC
constraints at runtime, neither loosening nor tightening them. 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) to be enforced unconditionally.
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. Enabled — the privilege is currently active; only present privileges can be enabled or disabled. 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.
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.
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.
Elevation (one-way) #
| Field | Type | Description |
|---|---|---|
elevation_type | enum | Default (non-elevated), Full (elevated), or Limited (filtered). |
A token is created as Default. 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. The role is sticky: relinking
can replace the partner but never converts Full to Limited or the
reverse. 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.
Linked pairs are associated at the LogonSession level rather than stored on individual tokens; Linked Tokens and Elevation describes the pairing mechanism.
Default object security (adjustable) #
Storing indices rather than SID copies keeps the owner and primary group consistent with the group array they name.
Metadata (fixed) #
Mutation tracking (adjustable) #
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.
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.
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. |
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. |
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.
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. |
Confinement (fixed) #
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.
Deciding which capabilities a package token receives is authd's job
and policy tooling's, not the kernel's.
Audit (fixed) #
| Field | Type | Description |
|---|---|---|
audit_policy | u32 | Per-token audit overrides as a bitmask, fixed at creation — no adjustment operation exists. |
The policy is additive. It forces audit events that system-wide policy would not generate, and cannot suppress events that system-wide policy requires. 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. The creation default is 0.
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).
Credential projection (fixed) #
| Field | Description |
|---|---|
projected_uid | Linux UID for the user SID, precomputed by authd when the token is minted (PSPU Overview); 65534 for the anonymous identity. |
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. Projection reflects all groups regardless of enabled state, so adjusting groups does not trigger recalculation. Credential Projection covers how the projection is used.
Token security (adjustable) #
| Field | Description |
|---|---|
security_descriptor | The token's own SD, controlling who may query, adjust, duplicate, or impersonate it. |
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
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. If the parent is impersonating, the impersonation token
is not inherited: the child's effective credential is set from
real_cred. After the fork, mutations to either token are invisible
to the other.
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. Each thread keeps independent impersonation state through its
own cred. 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.
Exec #
The primary token survives execve() unchanged, with the single
exception of NEW_PROCESS_MIN below. 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.
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.
NEW_PROCESS_MIN #
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.
- 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. This is deliberately not the access-check rule, under which an unlabelled object counts as Medium (Mandatory Integrity Control): 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.
- If the file's level is lower than the token's, a new token is
created following DuplicateToken semantics — new
token_id, newtoken_guid,modified_idinitialised to the newtoken_id,elevation_typereset to Default — withintegrity_levelset to the file's label. Every other field — the impersonation level included — is copied from the source, and the original token is dropped. - If the file's level is greater than or equal to the token's, nothing happens and the token survives exec unchanged.
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.
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.
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. 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 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.
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. 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.
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.
Such an exec also gives the new image the installed token's Linux credentials, projected as an installation projects them (Credential Projection): 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 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.
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.
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.
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), and tokens derived from it carry the
same policy. 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 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.
| 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.
The SYSTEM token carries SeBackupPrivilege and SeRestorePrivilege
present and enabled at boot. FACS passes backup and restore intent
flags into AccessCheck, which grants read and write regardless of file
DACLs — subject still to PIP. Once peinit has launched the TCB
services and early boot is complete, it disables these on child
service tokens through FilterToken.
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.
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
Three operations create tokens, each for a different purpose: CreateToken mints one from nothing, DuplicateToken copies one, and FilterToken produces a strictly weaker copy.
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.
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.
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.
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), and logon_sid, derived from the LogonSession ID
as S-1-5-5-{id >> 32}-{id & 0xFFFFFFFF}.
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. 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.
Validation covers, in turn:
- that the caller holds
SeCreateTokenPrivilege; - that every SID is structurally well-formed;
- that the owner SID is the user SID or a group carrying
SE_GROUP_OWNER, resolved toowner_sid_index; - that the primary group SID is the user SID or a group on the token,
resolved to
primary_group_index; - that
auth_idreferences an existing LogonSession; - that
user_deny_onlyis true wheneverwrite_restrictedis; - that
confinement_sidis present wheneverisolation_boundaryis; - that the wire format's
elevation_typefield is 0, since the kernel always sets Default itself; - and that the caller's group count plus the injected logon SID fits the 1024-entry limit.
The optional LCS registry credential extension, when present, has to use the version and layout of KACS ABI Reference, 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. Malformed LCS credentials fail the whole call closed.
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 minter chooses this ceiling deliberately (Impersonation Levels). 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.
DuplicateToken #
Creates an independent copy of an existing token, requiring
TOKEN_DUPLICATE access on the source.
Two things may change during duplication. The token type may go
from primary to impersonation or the reverse. 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 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.
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. 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): no
custom descriptor can be supplied at duplication time, and changing it
afterwards means using WRITE_DAC on the new handle.
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.
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. 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.
FilterToken #
Creates a restricted copy, requiring TOKEN_DUPLICATE access on the
source. 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. 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. 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. 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.
Input validation is all-or-nothing — a single malformed entry means no token is created. 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. The restricting SID blob has to parse exactly as the declared packed SID list, with no truncated or trailing bytes. 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.
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. The privilege states are the source's modified by the removal
list, except that used resets to 0 — unlike duplication, which
carries it across. groups keeps the source's SIDs with attributes
modified per the deny-only list, adding and removing nothing.
restricted_sids is the supplied list, or its intersection with the
source's when the source was already restricted. write_restricted is
sticky: set if requested or if the source had it. 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.
Token Adjustment
Peios Kernel / Internals / KACS / Tokens
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.
AdjustPrivileges #
Requires TOKEN_ADJUST_PRIVILEGES on the token, and has three modes.
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. 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. The reset touches only
privileges_enabled: it does not restore privileges that were removed
from privileges_present.
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. The deletion is irreversible; nothing re-adds a
privilege to a token.
Duplicate privilege indices in one request are invalid. The kernel validates every entry before applying any change, so an invalid entry fails the whole operation with no state change at all. The caller receives a report of each adjusted privilege's previous state.
AdjustGroups #
Requires TOKEN_ADJUST_GROUPS on the token, and has two modes.
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. And
the user SID, when it appears in the group list, cannot be disabled,
which is the one constraint that is direction-scoped.
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.
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. Reset is encoded as a single
kacs_group_entry of { index = 0xFFFFFFFF, enable = 0 }.
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.
AdjustInteractivityScope #
Requires TOKEN_ADJUST_INTERACTIVITY_SCOPE on the token and
SeTcbPrivilege on the caller's real token. 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.
AdjustDefault #
Requires TOKEN_ADJUST_DEFAULT on the token, and covers three fields.
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. 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
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. 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.
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. 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. The ioctl
ignores the handle it was issued on entirely; only the two named
handles matter.
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. 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.
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.
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. That correspondence is authd's to get right.
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. 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. 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
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. 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. 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.
When the last token referencing a session is freed, the kernel
destroys the session object and emits a kacs.session.destroyed
event through KMES. 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. 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.
On success it destroys the object and emits the same
kacs.session.destroyed event as normal cleanup. A nonexistent
session fails with -ENOENT; one with any live token, linked-token
state, or in-flight reference fails with -EBUSY.
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. 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); 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.
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. 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). And the
CAP_SYS_BOOT mapping selects between SeShutdownPrivilege and
SeRemoteShutdownPrivilege by inspecting the session's logon type
(Credential Projection). interactivity_scope is metadata in the same way: the kernel
stores it and returns it on query, and no kernel security mechanism
evaluates it.
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.
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. 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):
- 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.
- authd enumerates processes whose primary token carries the
target
auth_id, by walking/proc, opening each process withpidfd_open, opening its primary token withkacs_open_process_tokenon that pidfd, and readingTokenStatistics, which includesauth_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. - authd sends each
SIGTERMwithpidfd_send_signal, waits up to a grace period (5 seconds) for them to exit, and sendsSIGKILLto the survivors. - It walks again, since a process may have forked meanwhile, for at most three rounds.
- The processes terminate, dropping their token references.
- 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. 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: each has its own security descriptor, and reaching a token means passing an AccessCheck against it.
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 separate variant opens a thread's impersonation token. Opening
another process's token additionally requires
PROCESS_QUERY_INFORMATION on the target process's descriptor.
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.
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 token delivered
in a KACS_SCM_TOKEN control message carries the same three.
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); it is safe to hand out because the level ratchet means the
copy can never act above the level the client chose (Impersonation Levels).
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.
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.
Token-specific rights #
Bit 0x0010, TOKEN_QUERY_SOURCE, is subsumed by TOKEN_QUERY: a
holder of 0x0008 can query source information too. 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.
Generic mapping #
| 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) |
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.
The default token descriptor #
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.
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.
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. 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.
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.
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 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
Use these articles to understand process security in the Peios kernel.
State and lifetime
Peios Kernel / Internals / KACS / Process security
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). 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.
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 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.
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.
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. 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.
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. The DACL follows the default template.
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.
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. no_child_process persists in the same
way: a process restricted from creating children stays restricted no
matter what it execs.
process_guid is not reset either, because it identifies the process — the scheduling entity — rather than the binary.
The process descriptor is not reset. Exec preserves it unchanged. 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).
Clone with CLONE_THREAD #
Threads share the process's PSB. Thread creation is unaffected by
no_child_process, which blocks new processes only.
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.
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) 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
Process identity (fixed at fork) #
The process GUID is distinct from the PID. PIDs are recycled; process GUIDs are unique within a boot, and globally unique in practice. It is the stable correlation key that lets KMES attribute events to a process across its whole lifetime.
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.
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. Neither None nor Isolated is defined as a named
constant in the public ABI at all. The parent process cannot influence the
determination at all — even a compromised peinit running as SYSTEM
cannot forge PIP protection for an unsigned binary. 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.
Process mitigations (one-way) #
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.
Do not infer an additional service policy from peinit launch: the source-checked peinit 0.0.12 path 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. If any requested mitigation cannot be activated or verified, the whole operation fails closed without mutating any bit from that request. 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.
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.
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. 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. Anonymous executable
mappings are governed by wxp alone; tlp and lsv apply only to
file-backed ones.
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.
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.
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. cfib works, through shadow-stack enable-and-lock,
with one restriction: enabling it on a task other than the caller
fails.
Two mitigations are event-gated rather than retroactive: pie is
enforced at subsequent exec and no_child_process at subsequent
process creation. 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.
UI access (one-way) #
| 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. |
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. |
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.
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. Every prefix begins with / and
ends with / — so that /usr/lib/ does not match /usr/libevil — and contains no embedded NUL byte. 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.
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. 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.
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.
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. process_guid is the 16 bytes in order,
formatted 8-4-4-4-12.
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.
The PSB is otherwise written only: kacs_set_psb sets mitigations and
returns nothing about them.
Identity virtualization (reserved) #
| 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
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.
Process access rights #
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. And
cgroup sits in the PROCESS_QUERY_LIMITED set rather than the
detailed one.
psb is the process's PSB, read under PROCESS_QUERY_LIMITED with no
PIP dominance (PSB Fields). It is the one /proc entry whose check is
KACS's own rather than the metadata rule's.
Signal classification #
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.
PROCESS_TERMINATE — default action terminate, or terminate with
a core dump:
| 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:
| 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:
| 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.
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.
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. 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), captured at send time. 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.
Generic mapping #
| 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 |
The default process descriptor #
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. 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.
How PIP relates to it #
PIP and the process descriptor are complementary, and both checks have
to pass. 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. The privilege therefore
rescues a descriptor denial while remaining unable to cross a PIP
boundary, which is exactly the split Privilege Catalogue describes for it.
Privileges
Peios Kernel / Internals / KACS / Privileges
Use these articles to understand privileges in the Peios kernel.
The Privilege Model
Peios Kernel / Internals / KACS / Privileges
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.
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.
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. 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.
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. Where the shared privilege helper performs the check, it marks the bit immediately, and the impersonation gate does the same. 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;
- primary token installation marks after the same-user and same-LogonSession gate;
- and the
CAP_SYS_BOOTmapping marks after the remote-shutdown origin gate.
Used-state for the AccessCheck-influencing privileges follows the provenance rules of AccessCheck Overview 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.
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.
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. AccessCheck Overview gives the exact mechanics.
Intent gating #
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.
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.
Auditing #
Every exercise sets the token's monotonic used state for that privilege, and every standalone gate emits an ftrace event.
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.
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.
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 MAXIMUM_ALLOWED request short-circuits this accounting entirely,
recording no used bits and emitting no kacs.audit.privilege.used
events for any privilege.
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.
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.
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 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.
The boot SYSTEM token carries PRIVILEGE_USE_SUCCESS (Token Lifecycle), 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
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.
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.
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. 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).
SeAssignPrimaryTokenPrivilege gates installing a token as a
process's primary identity. 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). 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). The privilege is also consulted as a deny gate on
the exec and credential projection paths.
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.
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.
SeBackupPrivilege and SeRestorePrivilege read and write any object
regardless of the DACL. Inside AccessCheck they are intent-gated
(The Privilege Model), 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.
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.
SeChangeNotifyPrivilege bypasses traverse checking — without it,
reaching a file requires FILE_TRAVERSE on every intermediate
directory. 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. The privilege additionally gates
open_by_handle_at, which has nothing to do with traversal. 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.
SeCreateSymbolicLinkPrivilege creates symbolic links, and is
required in addition to FILE_ADD_FILE on the parent directory.
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). 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.
System operations #
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.
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. SeRemoteShutdownPrivilege is required in
addition when the request originates from a Network,
NetworkCleartext, NewCredentials, or RemoteInteractive logon.
SeLoadDriverPrivilege loads and unloads kernel modules through
CAP_SYS_MODULE. SeDebugPrivilege attaches to and inspects any
process regardless of its descriptor, and does not bypass PIP (Process Integrity Protection).
SeSystemtimePrivilegechanges the clock,SeIncreaseBasePriorityPrivilegeraises scheduling priority and sets CPU affinity for other processes,SeIncreaseQuotaPrivilegeoverrides resource limits,SeLockMemoryPrivilegelocks pages in physical memory,- and
SeAuditPrivilegewrites events to the audit log — it is what KMES requires for userspace event emission.
SeProfileSingleProcessPrivilege attaches perf_event_open() to a
specific other process. It respects PIP dominance, and own-task
profiling requires nothing. 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. 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. The two profiling privileges are otherwise disjoint
tiers.
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.
Bit 63 was SeBindPrivilegedPortPrivilege until that object existed; the
bit is retired and not reused.
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.
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.
| 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. |
Unallocated and unnamed bits #
SeCreateJobPrivilege is allocated bit 62 and is unused: no kernel
definition exists for it and nothing consults it. 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.
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.
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. 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. 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
Use these articles to understand impersonation in the Peios kernel.
Levels and admission
Peios Kernel / Internals / KACS / Impersonation
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.
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.
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. 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. 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.
The level is a ratchet #
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.
The level only ever goes down:
- Socket capture and
KACS_SCM_TOKENattach store the lower of the socket's level and the source token's own; - DuplicateToken refuses a result above its source, whatever the types involved;
- fork, exec,
NEW_PROCESS_MIN, FilterToken and primary installation copy it unchanged.
The one way to a higher level is a fresh token from CreateToken, which
takes SeCreateTokenPrivilege. 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) 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.
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 server already
impersonating another client has its gates judged against its own
service identity, so a previous impersonation cannot influence the
next one.
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.
SeImpersonatePrivilege — the server's primary token holds it,
enabled.
If neither holds, the level is silently capped to Identification. 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.
The reverse direction, unrestricted server to restricted client, is a
harmless downgrade and takes the ordinary cap-to-Identification path.
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.
The integrity ceiling #
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.
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. MS-DTYP allows the privilege to bypass every check including
this one; KACS does not, because mandatory_policy is immutable here
(Token Structure) and MIC is consequently a real boundary. Letting a privilege
punch through would give back exactly what that immutability buys.
Composition #
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
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(). 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), 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. 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. Clients that connect before the restamp
see the previous holder, which is honest: that is who was listening.
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. 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. 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).
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.
Anonymous #
Any thread may impersonate the Anonymous identity without passing
either gate. 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.
Double impersonation #
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.
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 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.
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.
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.
Audit records #
Every KACS_IOC_IMPERSONATE writes a kacs.impersonation.started
record through KMES (Audit Event Schemas). 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 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 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.
Ending an impersonation writes kacs.impersonation.reverted, a
verbose type, so only where the emission policy (Emission Policy) 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.
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
Peios Kernel / Internals / KACS / Impersonation
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.
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. 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.
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.
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_TOKENset 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. The derivation is cached against the effective token it was made from, so a run of sends under one identity costs one derivation. 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_TOKENcmsg. The kernel gates the attach exactly as it would gate impersonating that token: the fd must carryTOKEN_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. An attach the gates would cap below the token's own level fails withEPERM— an explicit act fails loudly where an install would silently downgrade. 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. At most one token per message.
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 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. 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 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 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. 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.
Supported transports #
Peer-token capture works on two AF_UNIX socket types. 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.
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 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 socket that is
not yet connected fails with ENOTCONN. Pipes and FIFOs are not
sockets at all, so getsockopt itself fails with ENOTSOCK before
KACS is reached.
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.
Executable trust
Peios Kernel / Internals / KACS / Executable trust
Use these articles to understand executable trust in the Peios kernel.
Signature verification
Peios Kernel / Internals / KACS / Executable trust
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.
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.
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). 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.
The consequence is that a verified binary is always Protected/8192. 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 build configured for KUnit compiles in a different, hard-coded key at the same tier, taken from the test vector header. 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. 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.
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.
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.
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.
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 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. 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 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.
The xattr path reads security.peios.sig and requires exactly 3310
bytes; any other size is treated as unsigned. The read bypasses the
LSM xattr hooks, so FACS does not mediate the verifier's own read of
the signature.
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. 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. 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. 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.
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.
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 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.
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.
The boot-time probe #
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_sigreturnsENOENTon 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.
Revocation #
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
Peios Kernel / Internals / KACS / Executable trust
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.
Exec proceeds in every case where the question could be answered.
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. 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.
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 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.
Once committed, the values are fixed for the lifetime of the process image, inherited at fork, and re-derived at the child's exec.
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. 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. Under LSV a pin failure denies the mapping instead.
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. 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.
Mutation or removal of the security.peios.sig xattr is rejected as
well.
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.
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.
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. 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. 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.
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. Anonymous mappings have neither a path nor a signature, so TLP
and LSV skip them and only WXP applies.
Enabling lsv on a running process also re-validates its existing
executable mappings before the bit is committed (PSB Fields), so the
mitigation cannot be turned on over already-mapped unsigned code.
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. 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).
Firmware verification
Peios Kernel / Internals / KACS / Executable trust
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). 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.
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 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. The hash covers the compressed bytes as they sit on disk, so verification precedes decompression.
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. 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. Under log the
verdict goes to a rate-limited warning and the kacs:kacs_firmware_load
tracepoint and the load proceeds. 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. 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 selected 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 from insufficiently trusted processes through trust label ACEs evaluated inside AccessCheck (PIP in AccessCheck). 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.
The process descriptor check is an ordinary AccessCheck of the caller's token against the target's process descriptor (Process Security Descriptors). 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.
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.
The dominance test #
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). The early return for an unprotected target is what keeps ordinary processes universally accessible whatever trust values a caller happens to carry.
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.
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.
SeDebugPrivilege #
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.
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. 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. 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. 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.
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.
Signal delivery, uniformly regardless of signal type. 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. 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.
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. 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.
Kernel-originated signals bypass the whole check, as described in Process Security Descriptors.
pidfd_open(), a boundary information query rather than a memory
or attach operation, needs PROCESS_QUERY_LIMITED plus dominance.
pidfd_getfd() maps to PROCESS_DUP_HANDLE plus dominance —
extracting a descriptor from another process is a boundary crossing in
its own right.
/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 gives the mapping. 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). Entries stricter than a metadata
query, such as /proc/<pid>/stack, keep their native hardening and
are not brought under the metadata rule.
Denying access prevents reading inside /proc/<pid>/ but does not
hide the PID: the directory name is still visible through getdents.
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.
Against another process it is a detailed information query needing
PROCESS_QUERY_INFORMATION plus dominance.
Resource limits, scheduler and placement. Read-only prlimit
needs PROCESS_QUERY_INFORMATION plus dominance; a limit change needs
PROCESS_SET_INFORMATION plus dominance.
setpgid()needsPROCESS_SET_INFORMATION;getpgid()andgetsid()needPROCESS_QUERY_LIMITED;- the scheduler, affinity and I/O priority queries need
PROCESS_QUERY_INFORMATION; - and the memory-placement mutations Linux routes through
task_movememoryneedPROCESS_SET_INFORMATION.
Setting nice, scheduler parameters and I/O priority all need
PROCESS_SET_INFORMATION too. Self-directed
versions of all of these are not boundary operations and skip both
checks.
CPU affinity is per-thread, so changing the caller's own thread or
a sibling in the same process is not a boundary operation. 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. KACS does
not relax the kernel's native affinity validity rules: an invalid or
disallowed mask still fails.
Token opens. kacs_open_process_token and
kacs_open_thread_token need PROCESS_QUERY_INFORMATION plus
dominance. 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. Own-task profiling is not a boundary
operation and needs no privilege. System-wide profiling, pid == -1,
samples every task on a CPU including protected ones, so it needs the
operator-class SeSystemProfilePrivilege. Cgroup perf mode stays
under Linux's native model. 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.
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.
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. 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 refusal emits kacs_exec with reason umh-not-tcb, so it is
visible rather than presenting as an unexplained module-load failure.
Trust raising under a tracer or supervisor #
Dominance is tested when a tracer attaches and when a seccomp filter is
installed, and not again. 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. 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 cap emits
kacs_exec with reason pip-capped-unsafe carrying the label that
was kept.
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. The
same initialisation gate refuses to coexist with SELinux, AppArmor,
Smack, TOMOYO or the BPF LSM.
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.
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.
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. 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), the PSB is the only safe source.
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. Requests that keep or make it non-dumpable are
allowed, and no alternative dumpable-setting path is left ungated. If
a later exec assigns None/0, normal Linux exec-time dumpability rules
apply to the new image.
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. The two are not mutually exclusive; disabling dumps is the minimum viable position.
Access check
Peios Kernel / Internals / KACS / Access check
Use these articles to understand access check in the Peios kernel.
AccessCheck Overview
Peios Kernel / Internals / KACS / Access check
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.
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. 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.
AccessCheckResultList is the per-property variant and requires an object type list. It returns a separate verdict for each node, so a denial on one property fails that property alone rather than the whole request. 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. 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.
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.
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
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.
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 deny ACE whose SID matches denies its not-yet-decided rights — marking them decided but not granted — and likewise leaves decided bits alone.
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. 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 group with neither SE_GROUP_ENABLED nor
SE_GROUP_USE_FOR_DENY_ONLY participates in no matching at all.
The user SID follows the same rule — when user_deny_only is set on
the token, it matches deny ACEs and not allow ACEs.
Skipping and mapping #
ACEs carrying INHERIT_ONLY exist purely to propagate to child
objects and are skipped by the walk.
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. 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).
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 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.
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. The
valid rights are bounded by MapGenericBits(GENERIC_ALL, mapping)
rather than by a raw 0xFFFFFFFF.
If the DACL is present but holds zero ACEs, the walk grants nothing. The only access an owner gets in that case comes from the implicit rights mechanism below.
Owner implicit rights #
By default the owner of an object receives READ_CONTROL and
WRITE_DAC whatever the DACL says. 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.
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). 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.
During the walk proper, S-1-3-4 is treated as an ordinary SID
matching the owner, at both allow and deny polarity. 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.
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.
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.
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.
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. 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 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.
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.
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 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.
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.
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. 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. 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.
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. The field is fixed at
creation (Token Structure), which is what makes MIC a boundary rather than a
suggestion.
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.
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. 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 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.
Policy bits #
Unknown bits in a label mask are ignored.
The algorithm #
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
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.
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. 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.
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. 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. The restricting list acts as a ceiling: the principal can never receive more access than the restricting SIDs would independently justify.
Write-restricted tokens #
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.
Privileges bypass the restricted pass #
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.
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.
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. 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.
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
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.
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.
With no list supplied, object ACEs with GUIDs apply globally, as if
they were basic ACEs. 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. An object ACE
whose GUID does not appear anywhere in the supplied tree is silently
skipped.
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.
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. 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. Ancestors still apply first-writer-wins to the propagated bits, so a denial cannot overturn something an ancestor had already decided.
Downward from denials. A denial on a property set flows to every attribute within it, again subject to first-writer-wins.
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. With a null self_sid, PRINCIPAL_SELF ACEs
match nothing.
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.
Scalar and per-node results #
AccessCheck requires every node to pass, so a denial on any one
property fails the whole request. AccessCheckResultList returns a
separate verdict per node.
The scalar result AccessCheck returns is the root node's granted
mask. 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.
Validation #
Object type lists are validated strictly, at parse time.
- A supplied list is non-empty.
- Its first node is at level 0.
- There is exactly one level-0 node.
- There are no level gaps, meaning no node at level N+2 following one at level N.
- No GUID appears twice.
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
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 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.
The confinement SID set is confinement_sid together with every SID
in confinement_capabilities. 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.
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. 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.
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. Owner
implicit rights are skipped entirely, because the pass runs with
skip_owner_implicit set.
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 null DACL means "no discretionary restrictions", and the confinement pass follows standard evaluation, granting all valid bits.
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.
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. Deciding
which capabilities a package token receives belongs to authd and
policy tooling.
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.
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. The two confinement-scoped virtual groups are the only exception, and they follow the confinement rules during conditional membership evaluation.
Ordering #
Confinement runs after the restricted token merge and after its privilege restoration. 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
An object opts in to PIP protection by carrying a
SYSTEM_PROCESS_TRUST_LABEL_ACE in its SACL. 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 caller that
does not dominate is limited to the ACE mask, and everything else is
denied.
Unlike MIC, PIP has no default. An object with no trust label is unrestricted, reachable by any process whatever its PIP identity.
The label SID #
A trust label SID has the form S-1-19-{type}-{trust} — the Process
Trust authority, exactly two sub-authorities. 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 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.
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.
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 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.
The algorithm #
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
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.
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, Process Integrity Protection).
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. 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.
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
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. 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.
It extends the Windows Central Access Policy model by adding an audit component: each rule carries both an access restriction and an audit requirement.
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 rule with
no condition applies to every object referencing the policy.
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.
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 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. Inherit-only scoped policy ACEs do not apply to the object carrying them and are ignored during lookup. 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 rule whose condition evaluates FALSE or UNKNOWN is skipped. 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.
The rule's DACL is evaluated with backup and restore intent not passed: intent is a caller concern, not a policy concern. 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. 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.
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.
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.
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 non-null spec for an existing
SID replaces the policy; a null spec or zero length removes it.
Every call that passes the privilege gate writes a
kacs.caap.policy.changed record (Audit Event Schemas) 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. 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.
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. The applies_to expression is conditional ACE bytecode,
carrying the same artx prefix as callback ACE application data.
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.
The version byte has to be 0x01. Trailing bytes after the declared
rules are rejected.
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 rule with a zero-length
effective DACL fails the same way, as do truncated fields, lengths
exceeding the buffer, and invalid ACL headers. SeTcbPrivilege is
checked before any parsing begins.
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.
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.
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.
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.
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. 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.
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 rule whose SACL evaluation errors has its audit contribution skipped, and a diagnostic event is emitted.
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 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.
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.
- Preserve the effective policy and its object references. Author proposed staged DACL/SACL fields without replacing the effective ones.
- Load and verify the policy on each intended machine through the privileged kernel interface. Distribution and object-side scoped-policy ACEs are separate responsibilities.
- 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.
- Review unexpected differences. A mismatch is neither a denial caused by the staged policy nor a complete list of which ACEs differ.
- 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. No audit rule affects the access decision, and audit ACEs are evaluated after the decision is final.
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 third family is
emitted for the CAAP conditions of Central Access and Auditing Policy: 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. The event type strings and
payload schemas are in Audit Event Schemas.
Event delivery happens before any result is written back to the caller, and a failure to deliver fails the call. An audit event cannot be suppressed by handing the syscall a bad output pointer.
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.
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. 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.
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. 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.
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.
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. 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.
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. For FACS handles that
is the same mask used by the use-time check (Use-Time Semantics). 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.
Events are emitted after the per-operation decision is known, for successful and denied attempts alike. The subject and process recorded are the operation-time effective token and current task, not necessarily the ones that opened the handle. 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. Transport buffering and drop accounting remain KMES's concern (Failure Modes).
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.
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). 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 privilege that contributed nothing
to the requested access produces no event either way.
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 MAXIMUM_ALLOWED request short-circuits this stage entirely,
recording no used bits and emitting no privilege-use events at all.
How counterfactual the accounting really is varies by privilege, as
The Privilege Model 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.
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.
Success here means every requested bit was granted, or that nothing was requested at all.
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. The policy is per-token, fixed at creation, and follows impersonation, since it is read from the effective token.
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.
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.
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.
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 check made through kacs_access_check names its object through the
audit context (audit_context_ptr, audit_context_len), the
PGSS The event stream map:
{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 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 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
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.
Pipeline overview #
Before the pipeline proper, two things are checked and can fail the call outright.
- The token's own invariants are validated — a
write_restrictedtoken withoutuser_deny_onlyis rejected as invalid. - In the orchestrator, a null descriptor is rejected and
AccessCheckResultListis required to have been given an object type list.
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.
The pipeline then runs in this order:
- Impersonation level gate. An impersonation token at Identification level is denied immediately. Anonymous tokens proceed through the full pipeline.
- Input validation. Reject a descriptor with no owner. A null group SID is valid and has no direct effect on the decision.
- Generic mapping. Map generic bits in the desired mask to
object-specific bits; strip
MAXIMUM_ALLOWED. - Effective privileges. Clear the backup and restore bits when the corresponding intent flag is absent. Callers of the userspace AccessCheck can give only these two intents.
- Privilege grants. Resolve
ACCESS_SYSTEM_SECURITY, backup and restore. Seeddecided,grantedandprivilege_granted. - 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.
- Virtual group resolution.
S-1-3-4andS-1-5-10become matchable where the caller is the owner or the object's principal. - Tree initialisation. Seed each node from the scalar state.
- 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). Every later step still applies.
- Post-DACL WRITE_OWNER override.
SeTakeOwnershipPrivilegegrantsWRITE_OWNERif the DACL did not and no mandatory mechanism blocked it. - Restricted token pass, with intersection and privilege restoration.
- Confinement pass, with absolute intersection.
- CAAP. Evaluate each applicable rule's DACL through the full per-descriptor pipeline and intersect; collect SACLs.
- Privilege-use auditing.
- Audit emission, over the object's SACL and any CAAP SACLs.
- 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. Step 1 re-checks only emptiness.
Reserved access-mask bits (0x0CE0_0000) are rejected wherever a mask
is mapped. 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.
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 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) has
fewer bits to preserve, and the audit provenance masks reflect the
narrowed set.
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.
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.
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. 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.
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.
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. 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) 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.
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.
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.
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. 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. 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.
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.
Provenance masks #
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
Use these articles to understand file security in the Peios kernel.
The Handle Model
Peios Kernel / Internals / KACS / File security
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 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 lists them.
A second immutable mask is stamped alongside it: the continuous audit mask (Auditing in AccessCheck), 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.
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.
unmanaged puts the mount outside the handle model entirely: no
granted mask is stamped on its file descriptions. 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.
Scope #
The sole-authority claim covers local FACS-managed filesystems. It does not cover:
O_PATHdescriptors, 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.
Descriptors for processes obtained through pidfd bypass FACS at open
as well.
Handle acquisition #
A descriptor carries its granted mask through every acquisition path, and transfer is an intentional capability-delegation mechanism.
dup/dup3andforkproduce the same open file description and therefore the same rights;- descriptors without
FD_CLOEXECsurvive exec unchanged; SCM_RIGHTStransfers the descriptor as a capability token, with possession as authorization and no re-check of the receiver's identity; andpidfd_getfd()is gated by an AccessCheck forPROCESS_DUP_HANDLEagainst the target process, after which the caller receives the descriptor with its full mask.
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 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.
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. No new AccessCheck runs against the task executing the stacking filesystem.
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. 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. 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. 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.
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.
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
and legacy-open compatibility,
not a general promise that every operation consults only one immutable mask.
KACS-Native Open
Peios Kernel / Internals / KACS / File security
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. This is the strict mode, in contrast to
the legacy path's subset behaviour (Legacy Open Compatibility).
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.
MAXIMUM_ALLOWED may also be named alone. The maximum includes
the rights granted through the parent directory, described below, and
excludes the rights a read-only file withholds (Special
Attributes).
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. 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.
Handle modes #
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).
An open granted none of these is a control handle: a managed descriptor with no data mode, carrying only metadata, security or delete rights. 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.
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.
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 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.
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.
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. Those are parent-directory authorization rights for
namespace operations, evaluated live at the operation, not rights a
handle carries.
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 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. FILE_EXECUTE is not a valid data substitute for them — a
kacs_open naming it on such a node fails closed. 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. This differs deliberately
from kacs_get_sd and kacs_set_sd, where the same flag resolves the
symlink object itself.
Rights granted through the parent #
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):
DELETEis granted if the parent grantsFILE_DELETE_CHILD.FILE_READ_ATTRIBUTESis granted if the parent grantsFILE_LIST_DIRECTORY. A caller who may list a directory may already see what its entries' attributes would show.
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 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).
Share access #
Every open of a regular file or directory on a managed mount takes part
in NT share-mode checking (Sharing and Deletion). 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. An open that conflicts with
another fails with EBUSY and the status KACS_STATUS_SHARING_VIOLATION.
Create dispositions #
| 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. 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.
FILE_OVERWRITE truncates in place — same inode, same descriptor,
hardlinks preserved — and requires FILE_WRITE_DATA.
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.
Create options #
All other bits are reserved and have to be zero; a nonzero reserved
bit fails with EINVAL.
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). 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. 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 read-only
regular file cannot be opened with delete-on-close: the open fails with
EPERM and the status KACS_STATUS_CANNOT_DELETE.
Caller-supplied descriptors #
The descriptor format and size bound are defined in SD Structure.
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.
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. FILE_OPEN with a descriptor supplied fails with
EOPNOTSUPP.
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 supplied SACL is treated as a full SACL
input rather than a label-only fragment, and therefore requires
SeSecurityPrivilege. 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.
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).
The creator's access #
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 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. 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);
- 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.
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.
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). It requires SeLockParentagePrivilege enabled;
without it the open fails with EPERM.
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). lease_fd has to be a lease-manager
descriptor, or the open fails with EBADF.
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. 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. 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.
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. 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.
When the open fails for a reason one errno cannot tell apart,
status_out also names the NT condition:
| 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'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.
Core rights #
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.
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.
FILE_READ_ATTRIBUTES is always core: a descriptor granting data
access but denying attribute reads is not openable through the legacy
APIs at all.
Compat rights #
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.
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.
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.
Sharing, deletion and read-only #
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). It also fails with EBUSY if the file is delete-pending,
as an O_PATH open of a delete-pending file does.
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).
FILE_READ_ATTRIBUTES, which every legacy open requires, may be
granted through the parent's FILE_LIST_DIRECTORY (KACS-Native
Open).
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. They serve as namespace
anchors for the *at() syscalls.
fstat() and fstatfs() on them are allowed unconditionally.
fchdir() runs a live FILE_TRAVERSE check at use time. fchmod(),
fchown(), fgetxattr(), fsetxattr(), ioctl() and mmap() are
denied with EBADF — though futimens() currently has no such guard.
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.
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, with one exception: execveat(AT_EMPTY_PATH) uses a
live AccessCheck.
Data operations #
A fallocate mode outside the supported set fails closed, and
PUNCH_HOLE additionally requires KEEP_SIZE.
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). Memory-mapped access is not.
Metadata operations #
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.
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. The signature xattr, security.peios.sig, is governed by
Binary Signature Verification.
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).
Directory traversal #
Path resolution checks FILE_TRAVERSE on managed directory
components. A token holding SeChangeNotifyPrivilege bypasses the
intermediate checks, including on directories whose descriptor is
missing.
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). An ordinary fchdir() checks the descriptor's cached mask;
an O_PATH fchdir() runs live.
Watch placement #
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.
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)
resolves that to SeTcbPrivilege, so these are TCB-only. 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.
Append-only enforcement #
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. Requesting both RWF_APPEND and RWF_NOAPPEND together
fails with EACCES.
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.
fcntl #
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. Adding O_NOATIME requires FILE_WRITE_ATTRIBUTES and
clearing it is always allowed. Changing only O_NONBLOCK, O_NDELAY
or O_DIRECT needs no KACS right, though ordinary Linux validation
still applies.
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.
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. 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. Unknown DN_* bits on a managed
descriptor fail closed.
Unmanaged descriptors sit outside the handle check entirely, and an unknown fcntl command on a managed one fails closed.
ioctl #
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.
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.
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.
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.
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 pinned inode (Binary Signature Verification) 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.
Execution #
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). 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).
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.
Descriptor storage and caching
Peios Kernel / Internals / KACS / File security
Xattr protection #
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. 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.
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.
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. 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. 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.
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. 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.
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.
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.
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. 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. 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. 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. 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.
Missing descriptors #
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.
Under the synthesise classes, a missing descriptor is generated
from two sources in order. 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.
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.
Inheritance is recursive — a parent whose own descriptor is missing is
synthesised first, walking toward the mount root where the template
terminates it. 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.
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.
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.
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.
An ephemeral synthesis is cached in the inode blob only and never written back, leaving the original filesystem unmodified. A persistent one is additionally written to the xattr so the medium acquires durable descriptors — but never inline.
Deferred write-back #
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. 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 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. 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.
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.
Corrupt descriptors #
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.
Recovery is a process holding SeRestorePrivilege calling
set-security to overwrite it. Offline repair tools can also rewrite
xattrs directly on an unmounted filesystem.
NFS client mounts #
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
Peios Kernel / Internals / KACS / File security
Mount policy classes #
The superblock policy object carries the class (The Handle Model) 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. 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.
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. 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.
Everything else, including TMPFS_MAGIC, SQUASHFS_MAGIC,
EXT4_SUPER_MAGIC and BTRFS_SUPER_MAGIC, defaults to
facs_deny_missing. 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.
Kernel-internal mounts #
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.
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. The devtmpfs root is
seeded inside devtmpfs_init, after vfs_kern_mount and before
kdevtmpfs starts, likewise under i_rwsem. The nullfs root is not
seeded — it is unmanaged, empty, and incapable of xattr storage.
A rootfs seed that fails panics the kernel. 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.
The writes go through the kernel-internal xattr path, bypassing both the FACS denial hooks and the LSM setxattr permission hook. 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.
Boot artifacts #
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.
Administration #
The privilege gate below is verified in kernel source
8e0e22de3a59cad506bbbf8873de456e16ad272d,
including its use by both set
and get. 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. Every change writes a
kacs.mount.policy.changed record (Audit Event Schemas), 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. The
public ABI accepts only the three managed classes; unmanaged,
unknown values, nonzero reserved flags and malformed arguments all
fail closed. 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).
The optional template is accepted only with a synthesise class. It is
a complete self-relative descriptor rather than a subset, passes
structural validation, and is at most 65535 bytes. A null pointer with
zero length clears it. Setting facs_deny_missing clears it and
rejects non-empty template input. 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. The superblock carries a monotonic generation counter, incremented on every successful policy or template replacement. 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. Xattr-backed and corrupt-descriptor caches are not made valid by a policy change, and open file descriptions keep their immutable masks.
The Set-Security Interface
Peios Kernel / Internals / KACS / File security
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.
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.
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 SACL_SECURITY_INFORMATION write replaces the object's entire
SACL. 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.
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.
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 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.
Component merging and replacement #
For a file whose cached descriptor is valid, the C dispatcher selects the merge path. The control-bit merge 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. The resource-manager control byte remains the destination's, 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, 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, not a runtime-validated restore procedure.
Generic rights #
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).
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).
Ownership #
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.
Integrity labels #
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.
SeSecurityPrivilege or SeRestorePrivilege alone is not sufficient for
a label above the caller's integrity: the label-assignment check independently requires enabled
SeRelabelPrivilege.
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. 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 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).
Mandatory resource attributes #
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.
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. An audit event is emitted if the file's SACL carries a matching audit ACE.
The cache update is not atomic with the xattr write; File Descriptor Storage describes the lock ordering that forces this and the last-writer-wins window it produces.
Sharing and Deletion
Peios Kernel / Internals / KACS / File security
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. 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.
Share modes #
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. 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 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 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.
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.
Denying only what you could do yourself #
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_DATAon 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). - Denying write takes effect only if the opener's descriptor grants
it
FILE_WRITE_DATAorFILE_APPEND_DATAon the object. - Denying delete takes effect only if the opener could delete the
object:
DELETEon it, orFILE_DELETE_CHILDon its parent.
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.
Overriding share modes #
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) also let it set aside other opens' denials:
- backup intent with
SeBackupPrivilegeenabled ignores other opens' denial of read; - restore intent with
SeRestorePrivilegeenabled 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.
Delete-pending files #
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.
While a file is delete-pending:
- its name stays in place:
statand directory listings still show it; - every new open of it fails with
EBUSY, whatever the access asked, including attribute-only andO_PATHopens; a native open reportsKACS_STATUS_DELETE_PENDING; - 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. 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.
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).
The disposition call #
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. 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. 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.
Renaming through a handle #
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). Authorization is:
DELETEin the handle's granted mask, for removing the source link;- a live check for
FILE_ADD_FILE, orFILE_ADD_SUBDIRECTORYfor a directory, on the destination directory; and - where a file is replaced, a live check for
DELETEon it orFILE_DELETE_CHILDon its parent.
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.
Deleting and renaming by name #
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). Plain deletion by name is still
immediate: the name goes at once, and open handles carry on.
Ancestor pinning #
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.
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. 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.
Stacked filesystems #
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.
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.
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:
- it takes the provider's path within its stratum;
- it looks that path up again through the mount the handle was opened
through, and locks it as
rename(2)would; - 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.
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.
Byte-Range Locks
Peios Kernel / Internals / KACS / File security
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. 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.
Taking and releasing locks #
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 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.
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 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.
Unlocking a range this open does not hold exactly fails with ENOLCK.
What locks block #
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.
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.
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.
When a lock takes effect #
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.
Memory mappings are not covered #
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).
Who can block whom #
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.
Stacked filesystems #
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
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.
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).
Lease managers #
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). 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.
Requesting a lease #
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.
- 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.
What breaks a lease #
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.
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.
Break notices #
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.
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.
Timeouts #
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.
Stacked filesystems #
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
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.
Reading and writing them #
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. 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).
| 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 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.
Read-only #
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:
- An open asking
FILE_WRITE_DATAorFILE_APPEND_DATAfails withEACCES. A legacy open for writing fails the same way. AMAXIMUM_ALLOWEDopen is granted neither right, norFILE_ADD_SUBDIRECTORYorFILE_DELETE_CHILD, following MS-FSA 2.1.5.1.2.1.FILE_OVERWRITEandFILE_SUPERSEDEfail withEACCES. truncateby path fails withEACCES.- 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 asKACS_STATUS_CANNOT_DELETE. The disposition and rename calls can set this aside with theirIGNORE_READONLYflags (Sharing and Deletion).
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.
Created At #
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
Use these articles to understand linux credentials in the Peios kernel.
DAC Neutralisation
Peios Kernel / Internals / KACS / Linux credentials
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.
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.
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:
| 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:
| 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. Per-operation
enforcement then happens at the relevant syscall hook, which checks
the specific privilege the specific operation needs (Process Integrity Protection).
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. 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); 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.
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.
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.
An unmapped or unknown capability is denied by default. The switchboard fails closed.
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. 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. The implementation is slightly stricter
than that: an ambient raise of an ALLOW capability is refused too,
not only a clear.
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.
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. 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. 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), and exec-time file-capability
grants remain suppressed. 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. The authorization answer is unaffected; the
privilege-use accounting double-counts.
The LSM stack #
MAC LSMs — SELinux, AppArmor, SMACK, TOMOYO — and the BPF LSM have to
be disabled. 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. 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 makes the ptrace authority. The same-uid
attach it exists to close cannot arise under KACS, which never grants
on uid.
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 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().
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. 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. 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).
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. 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.
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.
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 |
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.
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.
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).
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).
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.
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. 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. 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).
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. 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 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.
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. 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. netlink_allowed, which gates binding
to a family's multicast groups and sending to another port, tests the
current thread. 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.
What decides #
Every one of those tests reaches security_capable() with a specific
credential, and the capability switchboard (DAC Neutralisation) 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. 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. 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.
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. As everywhere on Peios, those
values are a projection for compatibility and display, not an
authorisation input (Credential Projection). 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).
System V IPC
Peios Kernel / Internals / KACS / System V IPC
Use these articles to understand system v ipc in the Peios kernel.
Objects and Their Descriptors
Peios Kernel / Internals / KACS / System V IPC
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), so ipcperms() never denies on the mode and always
reaches security_ipc_permission(); there KACS decides, against a
security descriptor the object carries.
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. 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.
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.
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. The
*get path with an existing key goes through the same check with the
requested mode. 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.
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. 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.
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. 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.
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).
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. 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): a message queue conveys no
sender identity, and msgrcv returns bytes and a type, nothing more.
Network objects
Peios Kernel / Internals / KACS / Network objects
Use these articles to understand network objects in the Peios kernel.
Port Reservations
Peios Kernel / Internals / KACS / Network objects
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), so the Linux floor never refuses first, and
every claim reaches security_socket_bind(), where KACS decides.
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.
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. 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.
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.
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. 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. 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. On any failure the
load is audited and the previous table stays in force.
The rejection is recorded as kacs.config.value.rejected (Audit Event Schemas):
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. Nested overlap,
and overlap between selectors of different widths, is how specificity
works and is accepted.
The decision #
At bind(2) on an AF_INET or AF_INET6 socket whose protocol is TCP,
UDP or UDP-Lite:
- If the requested port is 0 — ephemeral allocation — nothing is checked. Protocols no reservation covers (SCTP, raw) pass untouched.
- 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. - The caller's effective token is evaluated against that descriptor
for
PORT_BIND, through the ordinary AccessCheck pipeline (AccessCheck Overview) 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, withobject.kindsocket. - Deny →
-EACCES. Grant → the bind proceeds, and the caller's token is recorded on the socket as its binder.
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. 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. 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.
Before the registry #
The table comes from the registry through the same self-configuration
path LCS uses for its own limits (The Bootstrap Problem): read at the first source's
registration, then watched, so a change to the key is live without a
restart. 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. 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. Effective policy therefore never depends on boot timing.
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. 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.
Tracing #
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
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) reads it at the first judgment
of each flow. AF_UNIX sockets carry the peer-identity machinery of
Impersonation Levels instead and are not stamped.
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), the thread-group id, and the task's comm. 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:
| Act | Where |
|---|---|
| creation | socket_post_create; a kernel socket (sock_create_kern) is stamped as the kernel's, with no token |
bind(2) | after the port reservation permits it (Port Reservations) |
listen(2) | socket_listen |
connect(2) | socket_connect |
accept(2) | sk_clone_security: the child inherits the listener's stamp, its own reference |
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. 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.
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. 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) 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.
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.
Tracing #
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
Use these articles to understand mount namespaces in the Peios kernel.
A Private Mount Table
Peios Kernel / Internals / KACS / Mount namespaces
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), 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.
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. The initial namespace, and the
anonymous namespaces open_tree(OPEN_TREE_CLONE) and fsmount create
for detached trees, carry none.
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. 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.
Creating one #
unshare(CLONE_NEWNS), and clone with CLONE_NEWNS, need no
privilege when the mount namespace is the only namespace requested.
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 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 table created with the privilege is copied as upstream copies it, peers and all.
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:
- Privilege. A token holding
SeManageVolumePrivilegeorSeTcbPrivilege, 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. - 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.
- Descriptor. Otherwise, and only for an operation the descriptor
can admit, AccessCheck for
KACS_MNTNS_MOUNTruns against the namespace's descriptor under the caller's PIP context, exactly as it does for a socket or a SysV object.
The operations the descriptor can admit are the ones that put no kernel filesystem parser of an untrusted image in reach of the caller:
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). 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 stratafs stack admitted this way is read-only or absent-tolerant.
stratafs's own admission (Mount Admission) 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. 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.
An unprivileged tmpfs is stamped for its creator #
A fresh tmpfs is deny-missing under FACS (File Descriptor Storage): 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. 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. 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. 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.
What the object does not change #
The token never changes at exec (setuid Behaviour), 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). 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.
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.
Auditing
Peios Kernel / Internals / KACS / Auditing
Use these articles to understand auditing in the Peios kernel.
Event families and delivery
Peios Kernel / Internals / KACS / Auditing
KACS emits its audit records through KMES with origin class 2 (Event Model).
Each event's payload is a msgpack map whose field paths follow PGSS field
conventions: 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). 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.
Event families #
| Event type | Emitted by |
|---|---|
kacs.audit.access.checked | The SACL walk, and token audit-policy forcing. |
kacs.audit.handle.used | Enforcement points, per operation, against a handle's continuous audit mask. |
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). |
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). |
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. |
kacs.session.destroyed | LogonSession teardown (LogonSessions and Revocation). |
kacs.descriptor.rejected | A descriptor xattr that exists but fails structural validation (File Descriptor Storage). |
kacs.caap.policy.changed | kacs_set_caap installing, replacing or removing a central access policy (Central Access and Auditing Policy). |
kacs.mount.policy.changed | kacs_set_mount_policy (File Descriptor Storage). |
kacs.config.value.rejected | A port reservation table refused whole (Port Reservations). |
stratafs.file.copied-up | StrataFS copy-up lifecycle and failure (The StrataFS Copy-Up Context). |
stratafs.mutation.refused | A StrataFS arrangement refusal. |
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.
KACS also writes kacs.signature.crypto.failed once at boot when the
signature transform is unavailable (Binary Signature Verification), 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 record of a capability or volume gate (linux-cap, volume-mount)
names whichever privilege the gate spent (The Privilege Model). 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.
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. 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.
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.
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.
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.
Registry keys have the same record as lcs.audit.key.descriptor.changed.
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. 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.destroyedwhere the authentication package name is not valid UTF-8.- The two StrataFS events on an over-long operation string or path.
- Any self-emitted payload that would exceed its encoding buffer.
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.
The transport itself — ring buffer delivery, buffering and drop accounting — is KMES's (Ring Buffers, Failure Modes).
Integration
Peios Kernel / Internals / KACS / Integration
Use these articles to understand integration in the Peios kernel.
LSM hooks and object state
Peios Kernel / Internals / KACS / Integration
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.
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.
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).
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).
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.
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 |
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 |
| 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.
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 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.