# Tokens

---

# Tokens

_Peios Kernel / Internals / KACS / Tokens_

> Find the Peios kernel articles about tokens.

Use these articles to understand tokens in the Peios kernel.

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

---

# The Token Model

_Peios Kernel / Internals / KACS / Tokens_

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

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

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

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

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

## Relationship to Linux credentials

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

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

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

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

## Primary and effective tokens

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

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

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

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

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

## Evaluation context

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

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

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

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

---

# Token Structure

_Peios Kernel / Internals / KACS / Tokens_

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

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

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

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

## Identity core (fixed)

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

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

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

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

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

## Token type (fixed)

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

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

## Integrity (fixed)

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

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

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

## Privileges (adjustable)

Each privilege on a token has four independent states.

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

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

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

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

## Elevation (one-way)

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

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

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

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

## Default object security (adjustable)

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

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

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

## Metadata (fixed)

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

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

## Mutation tracking (adjustable)

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

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

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

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

## Interactivity scope (adjustable)

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

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

## Claims and security attributes (fixed)

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

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

## LCS registry credentials (fixed)

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

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

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

## Device identity (fixed)

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

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

## Confinement (fixed)

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

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

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

## Audit (fixed)

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

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

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

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

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

## Credential projection (fixed)

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

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

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

## Token security (adjustable)

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

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

## Internal

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

---

# Token Lifecycle

_Peios Kernel / Internals / KACS / Tokens_

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

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

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

## Fork and clone

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

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

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

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

## Exec

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

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

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

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

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

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

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

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

## Self-installing a primary token

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

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

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

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

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

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

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

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

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

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

## Bootstrap tokens

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

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

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

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

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

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

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

## External token replacement

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

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

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

---

# Token Creation

_Peios Kernel / Internals / KACS / Tokens_

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

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

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

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

## CreateToken

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

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

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

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

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

Validation covers, in turn:

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

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

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

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

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

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

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

## DuplicateToken

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

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

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

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

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

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

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

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

## FilterToken

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

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

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

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

---

# Token Adjustment

_Peios Kernel / Internals / KACS / Tokens_

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

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

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

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

## AdjustPrivileges

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

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

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

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

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

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

## AdjustGroups

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

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

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

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

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

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

## AdjustInteractivityScope

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

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

## AdjustDefault

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

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

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

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

---

# Linked Tokens and Elevation

_Peios Kernel / Internals / KACS / Tokens_

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

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

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

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

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

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

## What KACS does

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

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

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

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

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

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

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

## What KACS does not do

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

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

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

## Lifecycle

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

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

---

# LogonSessions and Revocation

_Peios Kernel / Internals / KACS / Tokens_

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

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

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

## LogonSessions

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

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

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

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

### Logon types

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

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

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

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

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

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

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

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

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

## Expiration

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

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

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

## Revocation

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

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

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

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

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

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

---

# Token Access Rights

_Peios Kernel / Internals / KACS / Tokens_

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

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

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

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

## Obtaining a token file descriptor

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

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

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

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

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

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

## Token-specific rights

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

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

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

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

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

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

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

## Standard rights

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

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

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

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

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

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

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

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

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

## Check-at-open

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

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