# Impersonation

---

# Impersonation

_Peios Kernel / Internals / KACS / Impersonation_

> Find the Peios kernel articles about impersonation.

Use these articles to understand impersonation in the Peios kernel.

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

---

# Levels and admission

_Peios Kernel / Internals / KACS / Impersonation_

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

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

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

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

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

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

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

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

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

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

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

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

The level only ever goes down:

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

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

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

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

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

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

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

## The identity gate

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---

# State transitions

_Peios Kernel / Internals / KACS / Impersonation_

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

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

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

## The sequence

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

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

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

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

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

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

## Anonymous

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

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

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

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

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

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

## Interaction with MIC and PIP

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

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

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

## SeImpersonatePrivilege

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

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

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

## Audit records

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

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

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

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

## Related explanations

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

---

# Transport and per-message identity

_Peios Kernel / Internals / KACS / Impersonation_

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

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

## Delegation and the network boundary

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

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

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

## Per-message identity

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

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

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

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

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

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

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

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

## Supported transports

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

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

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