SDK Reference
Header-by-header reference for the Peios SDK — the conventions every call follows, then security descriptors, tokens, access checks, files, processes, the registry, events, msgpack, and the registry-source interface.
Single-page view · as markdown
1.1 Library Conventions
Peios / Developing for Peios / SDK Reference / Library Conventions
libpeios and librsi share an error model and explicit ownership rules. Check each result before using output parameters, and follow the installed header for the function's particular buffer contract.
1.1.1 Results and errors #
Most int functions return zero or a new file descriptor on success and
-1 with errno on failure. Length-returning functions use ssize_t.
Predicate functions and void builder setters have different contracts;
read their declarations before choosing an error check.
Read errno only after a function reports failure. Save it before cleanup
calls if the caller needs to report the original error.
1.1.2 Buffers and builders #
Many libpeios encoders support a zero-capacity size probe. Allocate the reported space and repeat the call. String lengths exclude the terminating NUL, so string buffers need one additional byte.
Registry reads use lengths stored in parameter structures and report a
short buffer through ERANGE. They do not use the same return convention
as security encoders. Recheck sizes when retrying reads of mutable data.
Builders retain their first error until it is inspected or the result is
requested. Free each builder with its matching library destructor. Do not
pass a library-owned builder to free().
1.1.3 Borrowed data #
Parsed views borrow the caller's input bytes. Keep those bytes alive and unchanged until every view and derived pointer is unused. Copy borrowed data before retaining it beyond the input buffer's lifetime.
Registry source request decoders follow the same rule. Reading the next request into a frame buffer invalidates views into the previous frame.
1.1.4 File descriptors #
Close owned descriptors when their use ends. Passing a descriptor to an operation does not transfer ownership unless the header states otherwise. A successful operation does not grant ownership of a descriptor merely mentioned in an output structure; use that function's documented contract.
Start with result conventions and memory ownership for examples.
1.2 How Results Are Returned
Peios / Developing for Peios / SDK Reference / Library Conventions
Every entry point reports success or failure through its return type. There are three return shapes, and the shape tells you how to read the result.
1.2.1 int — a file descriptor, or zero #
A function returning int returns either:
- a file descriptor (a non-negative
int), when its job is to open something — a token, a registry key, an event stream; or 0on success, when it performs an action with no handle to hand back; and-1on failure, with the reason inerrno.
int fd = ;
if
1.2.2 ssize_t — a byte length #
A function returning ssize_t produces a variable-length result — a SID,
a serialized security descriptor, a formatted string, a registry value. It
returns:
- the length in bytes of the result on success (
>= 0); or -1on failure, with the reason inerrno.
These are the functions that use the two-call buffer protocol below. The returned length is always the full length of the result, which is what makes the protocol work.
For functions that format a string, the returned length excludes the
terminating NUL — exactly like snprintf. So a return of 41 means "41
characters plus a NUL"; size your buffer as len + 1.
1.2.3 Structured results — out-parameters #
When a call produces more than one value, or a value that isn't naturally a
length or an fd, it writes through out-parameters and returns int (0 /
-1). The access check is the archetype: it returns 0 when access is
granted and -1 with errno == EACCES when it is denied, and it writes the
granted access mask through an out-parameter either way.
uint32_t granted = 0;
int rc = ;
/* rc == 0: granted; rc == -1 && errno == EACCES: denied.
`granted` is populated in both cases. */
A denial is a normal, expected outcome, not a bug — which is why it is reported the same disciplined way as any other errno, rather than through a separate channel.
1.2.4 errno #
Failure is always reported through the standard C errno. The library sets
errno on every -1 return and uses ordinary, portable errno values — there
are no libpeios-specific or PKM-specific error numbers to learn. The ones you
will see most:
| errno | Meaning in libpeios |
|---|---|
EINVAL | Malformed input — a bad SID, an unparseable SDDL string, an argument out of range. |
ERANGE | Your output buffer was non-zero but too small. Nothing was written. (See the protocol below.) |
EACCES | An access check denied the request. |
ENOMEM | An allocation failed (for the heap-backed builders). |
EBADF, ESRCH, EFAULT | The usual Linux meanings — a bad fd or pidfd, a vanished process, a bad pointer. |
Because the values are standard, strerror, perror, and your language's
normal errno handling all work unchanged. Check the return value first, then
read errno — like any POSIX call, errno is only meaningful after a call
that signaled failure.
Nothing ever unwinds across the boundary. The library is compiled to abort rather than propagate a panic through the C ABI, so a call either returns a value you can inspect or the process dies — it never leaves you with a corrupt half-state to reason about.
1.3 The Two-call Buffer Protocol
Peios / Developing for Peios / SDK Reference / Library Conventions
Every function that returns variable-length bytes — anything with an ssize_t
return and an (out, cap) pair — follows the same getxattr-style
protocol. It is the single most important convention in the library, so it is
worth internalising.
The rule:
- Call with
cap == 0(or aNULLbuffer) to probe: the function writes nothing and returns the number of bytes the result needs. - Call with a buffer of at least that size to retrieve: the function fills the buffer and returns the number of bytes it wrote.
- Call with a non-zero but too-small buffer and it fails with
ERANGEand writes nothing — never a truncated or partial result.
That last point is the safety property that makes the protocol trustworthy: a too-small buffer is a clean, detectable error, not a silent truncation. You never have to wonder whether you got the whole thing.
The canonical two-call sequence:
/* 1. Probe for the size. */
ssize_t need = ;
if
/* 2. Allocate. For a string, add 1 for the NUL. */
char *buf = ;
/* 3. Retrieve. */
ssize_t n = ;
if
/* buf now holds the formatted SID; n is its length (excluding the NUL). */
When you already know a comfortable upper bound, you can skip the probe and
call once with a big-enough buffer. Some results have a fixed maximum the
library gives you a constant for — for example a SID is never larger than
PEIOS_SID_MAX_BYTES, so a stack buffer of that size always fits and never
needs a probe. Those shortcuts are called out where they apply; the two-call
protocol is always available as the general fallback.
1.4 Memory Ownership
Peios / Developing for Peios / SDK Reference / Library Conventions
libpeios never hands you an allocation to free(). Instead it uses two
ownership patterns — builders for constructing byte buffers and views
for reading them — and both keep the memory question simple: you own your
buffers, the library borrows or copies, and the two never get confused.
1.4.1 Builders — constructing buffers #
Anything you assemble (an ACL, a security descriptor, a token specification) is built with a builder: an opaque, heap-backed object you create, feed, take the bytes from, and free.
Builders have three properties worth knowing up front:
-
They are sticky-error. The incremental
add/setcalls returnvoid— they never fail inline. If one hits a problem (a bad input, an allocation failure), the builder latches the error and every later call is a no-op. You do not have to check each step. Instead you check once, at the end: either call the builder's_error()accessor (it returns the latched errno, or0if all is well), or notice that taking the bytes fails. This lets you write a long, clean sequence ofaddcalls without a conditional after every line. -
You free every builder you create. Each
_new()is paired with a_free(). Builders also have a_reset()that drops the accumulated content and clears the sticky error, so you can reuse one builder across several objects instead of churning allocations. -
Taking the bytes: borrow (and sometimes copy). Every builder has a
_bytes()that hands back a pointer into the builder — zero-copy, no allocation. That pointer is valid only until the next mutating call,_reset(), or_free()on that builder. Use it when you are going to consume the bytes immediately (for instance, pass them straight into a kernel call). The call comes in two shapes, and not every builder offers a copying counterpart:- The security builders (
peios_acl_builder_bytes,peios_sd_builder_bytes) return the pointer —NULLif the sticky error is set — and write the length through an optionallen_outpointer. Each is paired with a_finish()that copies the buffer into a caller-supplied buffer using the two-call protocol above, for when the bytes must outlive the builder. peios_token_builder_bytesandpeios_mp_writer_bytesare shaped the other way round: they return the length as anssize_t(-1witherrnoon a latched error) and write the borrowed pointer through an out-parameter (which can beNULLto get the length). Neither has a_finish()— copy the borrowed bytes yourself if they need to outlive the builder.
- The security builders (
A typical builder lifecycle:
peios_acl_builder *b = ; /* NULL on OOM */
; /* void — no check */
;
size_t len;
const void *acl = ; /* NULL if errored */
if
/* … use `acl` before the next mutation … */
;
1.4.2 Views — reading buffers #
Anything you parse (a security descriptor, an ACL, a SID array from a token) is read through a view: a small, caller-allocated struct that you point at a buffer you already hold.
Views have their own two rules:
-
You allocate the view; it is stack-friendly. A view type such as
peios_sd_viewis an opaque fixed-size struct — you declare one as a local variable and pass its address to the parse call. No heap, no free. The struct's fields are opaque: never read them directly; use the accessor functions. -
A view borrows the buffer it parses — zero-copy. The parse call does not copy the data; the view points into your buffer, and every accessor that yields a SID, a nested ACL, or a blob hands back a pointer into that same buffer. So the buffer must stay alive and unmodified for as long as the view — and anything you derived from it — is in use. Free or mutate the underlying buffer and every pointer the view gave you dangles.
peios_sd_view sd; /* on the stack */
if
const void *owner; size_t owner_len;
if
Views compose: parsing a security descriptor gives you a peios_sd_view, from
which you obtain a peios_acl_view for its DACL, from which you obtain each
peios_ace_view. Every one of them borrows the same original buffer, so
keeping that one buffer alive keeps the whole tree valid.
The symmetry is the thing to remember: builders own heap and must be freed; views own nothing and borrow your buffer. Constructing is builders, reading is views, and neither ever asks you to free something the library allocated.
1.5 File Descriptors
Peios / Developing for Peios / SDK Reference / Library Conventions
Handles that libpeios opens — tokens, registry keys, event streams — are raw
int file descriptors, the same kind open() gives you. You close them
with close(), poll them, and pass them across exec (or not) with the usual
fd machinery.
They are created O_CLOEXEC by default: a handle does not leak across an
exec unless you deliberately clear the flag with fcntl. This is the safe
default for security-sensitive handles — a token or key fd will not silently
end up in a child process you launch.
1.6 Constants
Peios / Developing for Peios / SDK Reference / Library Conventions
libpeios does not invent its own names for the kernel's wire constants.
The access-right bits, ACE types, control flags, and mapping structs all come
straight from the <pkm/*.h> UAPI headers, and you use those published names
directly: KACS_ACCESS_*, KACS_ACE_TYPE_*, KACS_SD_*, struct kacs_generic_mapping, and so on. There is no parallel PEIOS_* aliasing to
translate in your head — the name in the PSD, the name in the kernel header,
and the name you write in your code are the same name.
The handful of constants that are libpeios's own — buffer-size ceilings like
PEIOS_SID_MAX_BYTES, and enums for convenience selectors like enum peios_wks (well-known SIDs) — are prefixed PEIOS_ and documented with the
module that defines them.
1.7 The Conventions at a Glance
Peios / Developing for Peios / SDK Reference / Library Conventions
| Convention | The rule |
|---|---|
int return | fd or 0 on success; -1 + errno on failure. |
ssize_t return | byte length on success; -1 + errno on failure. Strings exclude the NUL. |
| Two-call protocol | cap == 0 / NULL probes for the size; too-small non-zero buffer → ERANGE, nothing written. |
| errno | standard values only; check the return first, then errno. |
| Access denial | -1 + EACCES, with the granted mask still written to the out-param. |
| Builders | heap-backed, sticky-error, void adders; check _error() at the end; _free() every one; _bytes() borrows, and the security builders add a _finish() that copies. |
| Views | caller-allocated (stack), opaque, borrow the parsed buffer; keep that buffer alive and unmodified. |
| File descriptors | raw int, O_CLOEXEC by default, closed with close(). |
| Constants | use the <pkm/*.h> KACS_* names directly; only libpeios's own additions are PEIOS_*. |
With these in hand, the module documentation reads as "what does this function do?" — the how of memory and errors is answered here, once, for all of them. Next: your first program, which puts the protocol and the error model to work in something you can compile.
2.1 Security Descriptors
Peios / Developing for Peios / SDK Reference / security.h — SIDs and Descriptors
<peios/security.h> is the shared vocabulary of the whole access-control
surface. SIDs, security descriptors, ACLs, and ACEs are the currency every
KACS interface trades in — tokens carry them, files are protected by them,
access checks evaluate them, and the registry secures keys with them. They
cross the kernel boundary as variable-length, self-relative byte buffers in
the MS-DTYP wire formats, and this module is the one place libpeios lifts that
raw wire form into something safe to handle from C.
Everything here assumes the library
conventions: ssize_t returns
are byte lengths using the two-call protocol, builders are heap-backed and
sticky-error, and views borrow the buffer they parse. This page does not
repeat those rules per function — read that page first.
The module has four parts:
- SIDs — build, parse, format, and compare security identifiers.
- ACLs and security descriptors — assemble them with builders.
- Parsing — read them back with zero-copy views.
- SDDL and inheritance — the text form and the userspace-only inheritance helpers.
The wire constants (KACS_SID_*, KACS_SD_*, KACS_ACE_*, and struct kacs_generic_mapping) come straight from <pkm/sid.h> and <pkm/sd.h>.
libpeios does not re-alias them — you use the published ABI names directly.
2.1.1 See also #
- Library conventions — the error, buffer, builder, and view rules this page builds on.
- SIDs and Security descriptors — the operator-side concepts behind this vocabulary.
<peios/token.h>,<peios/file.h>,<peios/access.h>— the KACS interfaces that consume this vocabulary, including the generic-mapping tablespeios_access_map_genericexpects.
2.2 SIDs
Peios / Developing for Peios / SDK Reference / security.h — SIDs and Descriptors
A SID (Security Identifier) is the unique binary name of a principal. For the full account of what a SID is — its string and binary forms, the mixed endianness, the equality rule — see the operator-side page on SIDs. This section is the API for handling them.
A SID is small and bounded. The largest possible encoding is
PEIOS_SID_MAX_BYTES (68) bytes, so a buffer of that size holds any valid SID
and the SID builders never need a two-call probe — you can always pass a
PEIOS_SID_MAX_BYTES stack buffer and skip straight to the retrieve call.
2.2.1 Constructing SIDs #
Each of these encodes a SID into your buffer and returns its length (or -1
with errno). Because a SID fits in PEIOS_SID_MAX_BYTES, the probe is
optional — but these are still ssize_t/two-call functions, so passing cap == 0 to probe works too.
| Function | Builds |
|---|---|
peios_sid_build(out, cap, id_authority, sub_auths, count) | An arbitrary SID from its parts: a 48-bit identifier authority (numeric, encoded big-endian) and count sub-authorities (encoded little-endian). count is 0..KACS_SID_MAX_SUB_AUTHORITIES. |
peios_sid_parse_string(out, cap, sddl) | A binary SID from its SDDL string form ("S-1-5-21-…"). |
peios_sid_integrity(out, cap, level_rid) | An integrity-label SID S-1-16-<rid> (see peios_integrity_level). |
peios_sid_logon(out, cap, session_id) | A logon SID S-1-5-5-<hi>-<lo> from a 64-bit session id. |
peios_sid_well_known(out, cap, which) | A well-known SID selected by enum peios_wks. |
ssize_t ;
ssize_t ;
ssize_t ;
ssize_t ;
ssize_t ;
peios_sid_build fails with EINVAL if count exceeds the maximum, and
(like all of these) with ERANGE if a non-zero cap is too small.
2.2.2 Formatting and inspecting SIDs #
| Function | Returns |
|---|---|
peios_sid_format(sid, len, out, cap) | The SDDL string form ("S-1-…"), as a string length excluding the NUL — allocate len + 1. |
peios_sid_valid(sid, len) | true if sid is a structurally valid SID of exactly len bytes. |
peios_sid_length(sid) | The encoded length of sid, read from its sub-authority count. You must have already validated sid, or bounded it to PEIOS_SID_MAX_BYTES — this trusts the buffer. |
peios_sid_equal(a, alen, b, blen) | true for exact binary equality — the only equality KACS defines for SIDs. |
peios_sid_rid(sid, len) | The RID (last sub-authority), or 0 if the SID has none. |
ssize_t ;
bool ;
size_t ;
bool ;
uint32_t ;
The split between peios_sid_valid and peios_sid_length is deliberate:
validation is the safe check that bounds an untrusted buffer;
peios_sid_length is the fast reader you use after you trust the bytes (or
when you have already capped the buffer at PEIOS_SID_MAX_BYTES). When in
doubt, validate first.
2.2.3 Well-known SIDs #
peios_sid_well_known constructs any of the standard system principals
without you memorising their numbers:
;
For the meaning of each principal, see Well-known principals.
2.2.4 Integrity levels #
Integrity-label SIDs have the form S-1-16-<rid>, where the RID names a
level. peios_sid_integrity takes that RID; the standard levels are:
;
These are the labels that appear in a SACL as a SYSTEM_MANDATORY_LABEL ACE
(see
peios_acl_builder_label).
2.3 Access Masks
Peios / Developing for Peios / SDK Reference / security.h — SIDs and Descriptors
An access mask is a 32-bit set of rights. Masks can contain four generic
bits (KACS_ACCESS_GENERIC_READ/WRITE/EXECUTE/ALL) that stand in for
object-specific rights until they are mapped to a concrete object class.
uint32_t ;
peios_access_map_generic folds the generic bits of mask into
object-specific rights using the mapping m, and clears the generic bits from
the result. Each object class publishes its canonical mapping as a data symbol
you pass here — peios_file_generic_mapping (from
<peios/file.h>) and
peios_token_generic_mapping (from
<peios/token.h>). Use it
when you have a mask written in generic terms (say, from an SDDL string using
GR/GW) and need the concrete rights for a specific object type.
2.4 Building ACLs
Peios / Developing for Peios / SDK Reference / security.h — SIDs and Descriptors
An ACL is an ordered list of ACEs. You assemble one with a
peios_acl_builder — create it, add ACEs, take the serialized bytes, free it.
Builders follow the sticky-error
rules: the adders return void, the
first error latches, and you check peios_acl_builder_error at the end.
typedef struct peios_acl_builder peios_acl_builder;
peios_acl_builder *; /* NULL on OOM */
void ;
void ;
peios_acl_builder_reset drops every accumulated ACE and clears the sticky
error, so you can reuse one builder for several ACLs.
2.4.1 Adding ACEs #
The common single-SID families have convenience adders. flags is a mask of
KACS_ACE_FLAG_* and is usually 0 — the flags carry inheritance semantics,
which matter only for container/inheritable ACEs.
void ;
void ;
void ;
| Adder | Appends |
|---|---|
_allow | An ACCESS_ALLOWED ACE — grants mask to sid. |
_deny | An ACCESS_DENIED ACE — denies mask to sid. Order matters: put denies before allows. |
_audit | A SYSTEM_AUDIT ACE — logs access by sid matching mask. Belongs in a SACL, not a DACL. |
For an integrity label there is a dedicated adder:
void ;
It appends a SYSTEM_MANDATORY_LABEL ACE for integrity level
S-1-16-<integrity_rid>. policy_mask is a mask of the
KACS_SYSTEM_MANDATORY_LABEL_NO_{READ,WRITE,EXECUTE}_UP bits (from
<pkm/sd.h>) that says which accesses a lower-integrity caller is denied.
Like _audit, a label ACE belongs in a SACL.
For everything else — object ACEs, callback ACEs, resource-attribute ACEs — there is the general adder and a fully-specified ACE struct:
;
void ;
Fill in only the fields the type uses; leave the rest NULL/0:
- Object ACEs (
KACS_ACE_TYPE_*_OBJECT) readobject_typeandinherited_object_type— each a 16-byte GUID, orNULLwhen absent. - Callback and resource-attribute ACEs carry trailing
app_data(which isNULLonly whenapp_data_lenis0). For callback ACEs this is the conditional-expression bytecode you can produce withpeios_sddl_parse_condition.
The convenience adders are exactly peios_acl_builder_add with a pre-filled
spec for the common cases; reach for _add when you need object, callback, or
resource-attribute ACEs.
The SDDL encoder includes zero padding after a variable-length payload so the
total AceSize is a multiple of four, as required by PCDS. This includes
resource claims ending in an odd-length octet or string payload. The padding
is included in AceSize; it does not change lengths or offsets within the
claim itself. The raw C ACL builder requires the supplied ACE body to already
be four-byte aligned; it rejects an unaligned body with EINVAL.
2.4.2 Taking the ACL bytes #
const void *;
ssize_t ;
int ;
peios_acl_builder_bytesborrows: it returns a pointer into the builder (valid until the next mutation,_reset, or_free), writing the length tolen_outif non-NULL. It returnsNULLif the sticky error is set.peios_acl_builder_finishcopies the serialized ACL out using the two-call protocol.peios_acl_builder_errorreturns the latched errno, or0if the builder is healthy.
The usual next step is to hand these bytes to peios_sd_builder_dacl or
_sacl.
2.5 Building Security Descriptors
Peios / Developing for Peios / SDK Reference / security.h — SIDs and Descriptors
A security descriptor binds an owner, a group, a DACL, a SACL, and control flags into one self-relative buffer. Its builder mirrors the ACL builder's shape.
typedef struct peios_sd_builder peios_sd_builder;
peios_sd_builder *;
void ;
void ;
2.5.1 Setting components #
void ;
void ;
void ;
void ;
void ;
void ;
- Owner / group. Omit the call to leave the component absent. That is
exactly what you want when building a partial SD to set only some
components through
kacs_set_sd— the SD then carries only what you set. - Control bits.
peios_sd_builder_controlsets the bits insetand clears those inclear(KACS_SD_DACL_PROTECTED, and friends). You do not manageSELF_RELATIVEor the*_PRESENTbits — the builder maintains those for you as you add components. - DACL / SACL. Pass ACL bytes, typically straight from
peios_acl_builder_bytes. An ACL with zero ACEs is a present-but-empty DACL, which grants only the owner's implicit rights.
The DACL has one subtlety worth stating plainly. KACS has no NULL-DACL
encoding — there is no "DACL present, pointer null" form; the kernel's
parser rejects it. So "grant everyone everything" is expressed as an
absent DACL (the DACL_PRESENT control bit clear).
peios_sd_builder_dacl_null requests exactly that: it clears any DACL you set
earlier and produces the same bytes as never setting a DACL at all. It exists
so you can state the grant-all intent explicitly rather than by omission — but
be clear that it means grant all, not deny all.
2.5.2 Taking the SD bytes #
Identical in shape to the ACL builder:
const void *;
ssize_t ;
int ;
_bytes borrows (valid until the next mutation/reset/free, NULL if
errored), _finish copies out getxattr-style, _error returns the latched
errno.
2.6 Parsing — Views
Peios / Developing for Peios / SDK Reference / security.h — SIDs and Descriptors
To read a security descriptor, ACL, or ACE you use zero-copy views. A view is a caller-allocated, opaque, stack-friendly struct that borrows the buffer you parse — see the view rules. Every accessor that yields a SID, a nested ACL, or a blob returns a pointer into the original buffer, so that buffer must outlive the view and everything derived from it.
typedef struct peios_sd_view peios_sd_view;
typedef struct peios_acl_view peios_acl_view;
typedef struct peios_ace_view peios_ace_view;
typedef struct peios_sid_array_view peios_sid_array_view;
The _opaque arrays are sized for stack allocation with headroom — declare a
view as a local and never read its fields.
2.6.1 Security-descriptor views #
int ;
uint16_t ;
int ;
int ;
int ;
int ;
peios_sd_parse validates a self-relative SD and populates out, returning
0 or -1 (EINVAL). peios_sd_view_control returns the raw control-bit
word.
The four component accessors return 0 with their out-params set on success,
or -1 if the component is absent. For the DACL and SACL, -1 also
covers the NULL-DACL case — since an absent DACL and a NULL DACL are the same
thing in KACS, a -1 from peios_sd_view_dacl uniformly means "no DACL
constrains this object."
2.6.2 ACL and ACE views #
You can also parse a bare ACL directly — a token's default DACL, for instance, arrives as an ACL, not wrapped in an SD:
int ;
unsigned ;
int ;
peios_acl_view_count gives the number of ACEs; peios_acl_view_ace
populates out for ACE i (0-based, in stored order), returning 0 or -1
(ERANGE for an out-of-range index). Iterate in the obvious way:
unsigned n = ;
for
Each ACE is read through its own accessors:
uint8_t ;
uint8_t ;
uint32_t ;
int ;
int ;
int ;
int ;
| Accessor | Yields |
|---|---|
_type / _flags / _mask | The ACE's KACS_ACE_TYPE_* type, KACS_ACE_FLAG_* flags, and 32-bit access mask. |
_sid | The trustee SID (a pointer into the buffer). 0 / -1. |
_object_type | The object GUID of an object ACE — 0 with *guid16 set to the 16 bytes, or -1 if not present / not an object ACE. |
_inherited_object_type | The inherited-object GUID, same convention. |
_app_data | Trailing application data of a callback or resource-attribute ACE — for a callback ACE, this is the conditional-expression bytecode you can render with peios_sddl_format_condition. |
2.6.3 SID-and-attributes arrays #
Several token classes — GROUPS, RESTRICTED_SIDS, DEVICE_GROUPS,
CAPABILITIES — return a packed [count][sid_len][sid][attrs]… blob rather
than an ACL. Parse those with the SID-array view:
int ;
unsigned ;
int ;
peios_sid_array_get yields the i-th entry's SID (a pointer into the blob),
its length, and its 32-bit attribute word (the KACS_SE_GROUP_* flags —
enabled, mandatory, deny-only, and so on).
2.7 SDDL Text Codec
Peios / Developing for Peios / SDK Reference / security.h — SIDs and Descriptors
The SDDL codec converts between the binary wire forms and their
human-readable SDDL text (MS-DTYP §2.5.1). This is a pure-userspace
facility — the kernel speaks only binary — so it lives entirely in libpeios.
All four entries use the two-call protocol (cap == 0 to probe) and fail with
EINVAL on malformed input.
ssize_t ;
ssize_t ;
peios_sddl_parse_sdparses SDDL text (for example"O:SYG:BAD:(A;;FA;;;BA)") into self-relative SD wire bytes.peios_sddl_format_sdrenders SD wire bytes back to a NUL-terminated SDDL string (length excludes theNUL, so allocatelen + 1).
These are the friendliest way to construct a descriptor when you have one written down — parse the string rather than assembling ACEs by hand — and the friendliest way to log or display one.
2.7.1 Conditional expressions #
Callback ACEs carry a conditional expression as compiled "artx" bytecode. The codec converts between that bytecode and its SDDL expression text:
ssize_t ;
ssize_t ;
peios_sddl_parse_conditioncompiles an expression such as@User.Title == "PM"into the bytecode you place in a callback ACE'sapp_data.peios_sddl_format_conditionrenders bytecode back to text (with no outer parentheses), length excluding theNUL.
So the round trip for a conditional ACE is: write the condition as text →
peios_sddl_parse_condition → put the bytecode in peios_ace_spec.app_data
with a callback ACE type → add it to an ACL builder.
2.7.2 Input limits and malformed data #
Conditional expressions have a maximum tree depth of 128. Each comparison,
existence check, membership test, logical operator, or composite operand adds
one level; scalar operands add none. For example, a comparison has depth one,
and adding 127 negations reaches the limit. Long && and || chains also
count because each operator adds a level to the resulting tree.
Text parsing also limits nested parentheses, negations, and composite braces to 128 levels along any one parsing path. Delimiters inside string literals do not count. These limits apply when parsing conditional ACEs inside a descriptor as well as when converting a standalone condition. The bytecode decoder applies the same tree limit, including nested composite operands.
Inputs beyond either limit fail with EINVAL; simplify the expression before
retrying. The C functions return -1 and leave the output buffer untouched.
GUID fields require ASCII hexadecimal digits in the standard hyphenated form.
Malformed Unicode GUID text fails with EINVAL. When reading resource claims,
the codec checks that the complete value-offset table fits inside the supplied
bytes before allocating storage for its entries. An impossible or truncated
table also fails with EINVAL.
2.7.3 Descriptor text and omitted components #
Sections use O:<sid>G:<sid>D:<acl>S:<acl>. Each is optional but can appear
only once. Formatting orders them as owner, group, DACL, and SACL.
D: is an empty, present DACL. D:NO_ACCESS_CONTROL and an omitted DACL
encode the absent-DACL state. The marker can accompany ACL flags but not
ACEs. The same representation rule applies to SACL absence. The formatter
can omit an absent ACL unless flags need preserving, and uses
D:NO_ACCESS_CONTROL for an otherwise empty descriptor.
These rules describe a complete supplied descriptor. In a tool that queried only selected components, an omitted section can instead mean "not queried." Formatting cannot recover missing components. Do not use matching partial SDDL strings as proof of complete descriptor equality or as a full backup.
An ACE has six semicolon-separated fields, or seven for a payload:
(type;flags;rights;object_guid;inherit_object_guid;account_sid;payload)
Object GUID fields apply to object ACEs; supplying them for other types is
an error. Callback payloads carry conditions, and resource-attribute payloads
carry claims. For example, O:SYG:SYD:(A;OICI;GA;;;SY) names SYSTEM as owner
and group and grants SYSTEM generic-all with object/container inheritance.
This explains the string; it does not select a suitable policy for every
object.
2.7.4 ACL control flags #
| Flag | Meaning |
|---|---|
P | Protected. The ACL does not inherit from its parent. |
AI | Auto-inherited. The ACL was produced by inheritance propagation. |
AR | Auto-inherit required. Requests that propagation be applied. |
2.7.5 ACE type codes #
| Code | ACE type |
|---|---|
A | Access allowed |
D | Access denied |
AU | System audit |
OA | Access allowed, object |
OD | Access denied, object |
OU | System audit, object |
XA | Access allowed, callback — carries a condition |
XD | Access denied, callback — carries a condition |
XU | System audit, callback — carries a condition |
ZA | Access allowed, callback object |
ZD | Access denied, callback object |
ZU | System audit, callback object |
AL | System alarm — continuous auditing |
OL | System alarm, object |
XL | System alarm, callback — carries a condition |
ZL | System alarm, callback object |
ML | Mandatory label — the integrity level |
TL | Process trust label |
RA | Resource attribute — carries a claim |
SP | Scoped policy identifier |
FL | Access filter — carries a condition |
2.7.6 ACE flag codes #
| Code | Meaning |
|---|---|
CI | Container inherit — child containers receive it. |
OI | Object inherit — child objects receive it. |
NP | No propagate — children receive it, grandchildren do not. |
IO | Inherit only — it does not apply to the object carrying it. |
ID | Inherited — this ACE arrived by propagation. |
SA | Audit successful access. |
FA | Audit failed access. |
2.7.7 Rights codes #
| Code | Right |
|---|---|
GA | Generic all |
GR | Generic read |
GW | Generic write |
GX | Generic execute |
| Code | Right |
|---|---|
SD | Delete |
RC | Read control — read the descriptor |
WD | Write DACL |
WO | Write owner |
| Code | Mask | Right |
|---|---|---|
FA | 0x001F01FF | All file access |
FR | 0x00120089 | File read |
FW | 0x00120116 | File write |
FX | 0x001200A0 | File execute |
| Code | Mask | Right |
|---|---|---|
KA | 0x000F003F | All key access |
KR | 0x00020019 | Key read |
KW | 0x00020006 | Key write |
KX | 0x00020019 | Key execute |
| Code | Right |
|---|---|
CC | Create child |
DC | Delete child |
LC | List children |
SW | Self write |
RP | Read property |
WP | Write property |
DT | Delete tree |
LO | List object |
CR | Control access |
| Code | Policy |
|---|---|
NW | No write up |
NR | No read up |
NX | No execute up |
2.7.8 Absolute SID aliases #
| Code | SID | Principal |
|---|---|---|
WD | S-1-1-0 | Everyone |
AN | S-1-5-7 | Anonymous |
IU | S-1-5-4 | Interactive |
NU | S-1-5-2 | Network logon |
SU | S-1-5-6 | Service |
RC | S-1-5-12 | Restricted code |
WR | S-1-5-33 | Write-restricted code |
PS | S-1-5-10 | Principal self |
ED | S-1-5-9 | Enterprise domain controllers |
AU | S-1-5-11 | Authenticated Users |
SY | S-1-5-18 | Local System |
LS | S-1-5-19 | Local Service |
NS | S-1-5-20 | Network Service |
AC | S-1-15-2-1 | All application packages |
| Code | SID | Principal |
|---|---|---|
CO | S-1-3-0 | Creator Owner |
CG | S-1-3-1 | Creator Group |
OW | S-1-3-4 | Owner rights |
| Code | SID | Principal |
|---|---|---|
LW | S-1-16-4096 | Low integrity |
ME | S-1-16-8192 | Medium integrity |
MP | S-1-16-8448 | Medium-plus integrity |
HI | S-1-16-12288 | High integrity |
SI | S-1-16-16384 | System integrity |
| Code | SID | Principal |
|---|---|---|
BA | S-1-5-32-544 | Administrators |
BU | S-1-5-32-545 | Users |
BG | S-1-5-32-546 | Guests |
PU | S-1-5-32-547 | Power users |
AO | S-1-5-32-548 | Account operators |
SO | S-1-5-32-549 | Server operators |
PO | S-1-5-32-550 | Printer operators |
BO | S-1-5-32-551 | Backup operators |
RE | S-1-5-32-552 | Replicator |
RU | S-1-5-32-554 | Pre-Windows 2000 compatible access |
RD | S-1-5-32-555 | Remote desktop users |
NO | S-1-5-32-556 | Network configuration operators |
MU | S-1-5-32-558 | Performance monitor users |
LU | S-1-5-32-559 | Performance log users |
IS | S-1-5-32-568 | IIS users |
CY | S-1-5-32-569 | Cryptographic operators |
ER | S-1-5-32-573 | Event log readers |
CD | S-1-5-32-574 | Certificate service DCOM access |
RA | S-1-5-32-575 | RDS remote access servers |
ES | S-1-5-32-576 | RDS endpoint servers |
MS | S-1-5-32-577 | RDS management servers |
HA | S-1-5-32-578 | Hyper-V administrators |
AA | S-1-5-32-579 | Access control assistance operators |
RM | S-1-5-32-580 | Remote management users |
2.7.9 Context-sensitive codes #
| Code | As a right | As an account | Elsewhere |
|---|---|---|---|
WD | Write DACL | Everyone | |
RC | Read control | Restricted code | |
AU | Authenticated Users | ACE type: system audit | |
RA | RDS remote access servers | ACE type: resource attribute | |
FA | All file access | ACE flag: audit failed access | |
SD | Delete |
2.7.10 Numeric masks and canonical formatting #
An entirely ASCII-digit rights field is an unsigned decimal mask. Leading
zeros remain decimal; signs, non-ASCII digits, overflow beyond 4294967295,
and mixing decimal text with mnemonic codes are rejected. Hexadecimal uses
0x and consumes the rest of the field, so it can follow mnemonic rights
only as the final portion. FRFX0x6 combines file read/execute with the two
additional bits.
The formatter prefers composite masks and does not preserve every accepted
spelling. KX has the same mask as KR; one spelling is emitted. Directory
object codes share bits with other vocabularies, so outside mandatory-label
ACEs formatting can use hexadecimal rather than guess an object class.
Mandatory-label masks use their label vocabulary. Unknown ACE types fail
formatting instead of silently disappearing.
XL and ZL are Peios callback-alarm extensions and are not portable Windows
ACE codes. Domain-relative aliases such as DA and machine-relative LA
cannot resolve without a base SID; the codec rejects them with an explanation.
Use an explicit full SID. BUILTIN aliases are absolute despite their names.
The null SID and protected-process integrity SID have no short alias.
A displayed f in the sd command's rights summary is that command's
shorthand, not the SDDL grammar or a hexadecimal nibble. Consult the tool's
manual before feeding rendered output back into a parser.
2.8 SD Inheritance
Peios / Developing for Peios / SDK Reference / security.h — SIDs and Descriptors
Inheritance — computing a child object's ACEs from its parent's inheritable ones — is also pure userspace (MS-DTYP §2.5.3.4). Both helpers take and produce self-relative SDs and use the two-call protocol.
ssize_t ;
ssize_t ;
peios_sd_reinherit recomputes a child SD's inherited ACEs from its
parent. It strips the ACEs carrying ACE_FLAG_INHERITED from the child DACL,
re-derives them from the parent DACL, and appends them after the child's
explicit ACEs; the child's owner, group, SACL, and control bits pass through
unchanged. is_container is non-zero if the child is itself a container
(which determines how container-inherit and object-inherit flags propagate).
This is what you call when a parent's ACL changed and you need to push the new
inheritance down to a child.
peios_sd_strip_inherited drops the ACE_FLAG_INHERITED ACEs from the
ACLs selected by info — a mask of *_SECURITY_INFORMATION bits, of which
DACL_SECURITY_INFORMATION and SACL_SECURITY_INFORMATION are honored and
the rest ignored (selecting neither copies the input verbatim). Owner, group,
and control bits pass through. Use it to reduce a descriptor to its explicit
ACEs — for example before storing a "protected" descriptor that should not
carry inherited entries.
Both return the new SD's byte length, or -1 with EINVAL (malformed input)
or ERANGE (a non-zero buffer too small).
3.1 Tokens and Sessions
Peios / Developing for Peios / SDK Reference / token.h — Tokens
<peios/token.h> is the token surface of KACS. A token is the runtime
object that carries an identity — a user SID, group SIDs, privileges, an
integrity level, claims — and every access decision is made against one. This
module lets you open the tokens that already exist (your own, another
process's, a socket peer's), mint new ones, read their contents, transform
them, and install or impersonate them.
A token handle is a file descriptor. Every open/create/duplicate call
returns a raw int fd, O_CLOEXEC by default, that you close with close().
The access argument several calls take is the desired handle-right mask
(KACS_TOKEN_*), access-checked against the token's own security descriptor
and cached on the fd — a handle only lets you do what its rights allow.
The wire constants (KACS_TOKEN_*, KACS_IMLEVEL_*, KACS_SE_*_PRIVILEGE,
KACS_TOKEN_CLASS_*, KACS_LOGON_TYPE_*) and the ioctl arg structs
(kacs_priv_entry, kacs_group_entry) come from <pkm/token.h>. Query
payloads that are SID arrays or ACLs are read with the views in
<peios/security.h>.
The module divides into: opening & creating, the token-spec builder, query, adjust/transform, and logon sessions.
3.1.1 See also #
<peios/security.h>— the SID/ACL/SD vocabulary and the views used to parse group and privilege query payloads.<peios/access.h>— checking access with a token fd.- Tokens and Impersonation — the operator-side model.
3.2 Opening and Creating Tokens
Peios / Developing for Peios / SDK Reference / token.h — Tokens
Each of these returns a token fd (or -1 with errno).
int ;
int ;
int ;
int ;
int ;
| Function | Opens |
|---|---|
peios_token_open_self | The calling thread's token. flags can be KACS_TOKEN_OPEN_REAL to get the primary token even while the thread is impersonating; otherwise you get the effective (impersonation-aware) token. access is the desired handle rights. |
peios_token_open_process | The primary token of the process named by pidfd. Subject to a process-query access check and PIP dominance over the target. |
peios_token_open_thread | Thread tid's impersonation token if it is impersonating, else the process primary token. |
peios_token_open_peer | The peer-identity token captured at connect() on a connected Unix stream/seqpacket socket conn_fd — how a server learns who is on the other end of a socket. Reads the KACS_SO_PEER_TOKEN socket option (level SOL_KACS, <pkm/socket.h>). The handle carries fixed `QUERY |
peios_token_create_raw | Mints a token from a pre-built token-spec buffer. This is the escape hatch — prefer the builder below. Requires SeCreateTokenPrivilege. |
Errors, per call:
peios_token_open_self—EINVAL(unknownflags; empty or unknownaccessbits),EACCES(the token's own SD deniesaccess).peios_token_open_process—EACCES(any of the three checks failed — process-query right, PIP dominance, or the token SD; deliberately indistinguishable),EBADF(invalid pidfd),ESRCH(target exited),EINVAL(empty or unknownaccessbits).peios_token_open_thread— the_open_processset, plusESRCH(thread exited, or not inpidfd's process) andEINVAL(tid <= 0).peios_token_open_peer—ENOTCONN(not connected),ENODATA(connected but no captured identity — a socketpair end),EOPNOTSUPP(a datagram or non-Unix socket),ENOTSOCK(not a socket),EBADF(invalid fd).peios_token_create_raw—EPERM(privilege missing),EINVAL(spec failed kernel validation),EFAULT(bad spec pointer),ENOMEM(allocation failed).
peios_token_open_peer is the cornerstone of local authentication: accept a
connection, open the peer token, and you have the caller's identity to query
or impersonate — no password, no handshake, the kernel's word for who
connected.
3.2.1 Peer identity on sockets #
int ;
int ;
int ;
int ;
int ;
peios_token_impersonate_peerispeios_token_open_peerfollowed bypeios_token_impersonateand aclose— the one-call form for a handler that impersonates, works, and reverts on a single thread. It returns 0 or -1; the errno is whichever step failed.peios_socket_set_impersonation_levelis the client's side of the exchange: it sets theKACS_SO_IMPERSONATION_LEVELsocket option (KACS_IMLEVEL_*), bounding the level at which the peer can capture this socket's identity — Identification to be known but not acted as, Anonymous to withhold identity entirely. Usually set beforeconnect(); it can change at any time and bounds every capture from then on. The default isKACS_IMLEVEL_IMPERSONATION. Errors:EINVAL(unknown level),EOPNOTSUPP(a non-Unix socket).peios_socket_get_impersonation_levelreads the level back into*level.peios_socket_restampreplaces the identity a listening socket conveys to connecting clients — captured whenlisten()was called — with the caller's own (KACS_SO_RESTAMP;EINVALif the socket is not listening). Capture is symmetric: a client'speios_token_open_peeron its own socket right afterconnect()returns the listener's identity at Identification level, which is how a client verifies the service it reached. A service that receives listeners it did not create (from the descriptor store after a restart, or from a broker) restamps them before accepting.peios_socket_set_pass_tokenturns on per-message identity for a sending socket (KACS_SO_PASS_TOKEN): every send then carries the sender's effective identity as aKACS_SCM_TOKENancillary message, and the peer'speios_token_open_peerfollows whoever was impersonating at each send. This is what makes a pooled or multiplexed connection convey the right identity per request without the client library knowing. To attach a specific token to one message instead — a router forwarding for many clients, or a submitter handing a job manager the identity a job should run as — usepeios_socket_send_messagebelow.
3.2.2 Per-message identity and descriptors #
A message on a Unix socket can carry two things beside its bytes: a token the
kernel attests the sender could act as (KACS_SCM_TOKEN, level SOL_KACS)
and a set of file descriptors (SCM_RIGHTS). Building the control buffer by
hand and walking it back is the same twenty lines in every program that does
it, and a wrong CMSG_ALIGN is silent; these calls do it once.
;
ssize_t ;
ssize_t ;
int ;
peios_socket_send_messagesendslenbytes frombufonsock_fdwith onesendmsg(2), attachingtoken_fdas aKACS_SCM_TOKENwhen it is>= 0andfds[0..fd_count]asSCM_RIGHTSwhenfd_count > 0;flagsaresendmsgflags. Returns the bytes sent. The kernel gates the token attach exactly as it gates impersonating it — the handle needsTOKEN_IMPERSONATE, and the token travels at the sending socket's impersonation level (peios_socket_set_impersonation_level, default Impersonation), which can only lower what the token already carries: if attaching would have to lower the token's level the send fails rather than downgrading. Ownership is unchanged by a send — the caller keepstoken_fdand every entry offds; the kernel duplicates them into the receiver on delivery.peios_socket_recv_messagereceives one message withrecvmsg(2)intobuf/cap, with room for one attached token andmsg->fd_capdescriptors written into the caller-ownedmsg->fds(passNULLwithfd_cap == 0to accept none).MSG_CMSG_CLOEXECis always added toflags, so every descriptor delivered isO_CLOEXEC. Returns the bytes received (0at end of stream). On return the caller ownsmsg->token_fd(when>= 0) andmsg->fds[0..fd_count]and closes each; the token handle carriesQUERY | IMPERSONATE | DUPLICATE, the same fixed rights aspeios_token_open_peer. Nothing leaks on any path: a second token in one message, or a descriptor pastfd_cap, is closed by the library before it returns, andmsg->flagsreports the loss asPEIOS_SOCKET_MSG_CTRUNCATED;PEIOS_SOCKET_MSG_TRUNCATEDmeans the bytes did not fitcap(on aSOCK_SEQPACKETsocket the tail is gone). A receiver that cannot accept a truncated message closes what it was handed. On-1nothing was consumed and*msgis untouched.fd_capabove the kernel'sSCM_MAX_FD(253) is capped silently. The truncation flag also covers handles that fit in the syscall's ancillary buffer but exceed the caller's capacity. For example,fd_cap == 0closes any received rights and reports control truncation. This flag is retained alongside payload truncation when both occur.peios_socket_peer_pidfdreturns a new pidfd (O_CLOEXEC) for the process on the other end of a connected Unix socket —getsockopt(SOL_SOCKET, SO_PEERPIDFD), a Linux ≥ 6.5 facility that libpeios only wraps; the option itself comes from the kernel UAPI and glibc. It is the kernel's handle on the peer, which is whatpeios_token_open_processtakes to open the peer's primary token — the identity a process has, as distinct from the identity it conveyed atconnect()(peios_token_open_peer) — and never a PID the peer named, so a recycled PID can never be opened by mistake.
Errors: peios_socket_send_message — EINVAL (NULL buffer with len > 0,
NULL fds with fd_count > 0, or fd_count above SCM_MAX_FD), EACCES
(token_fd lacks TOKEN_IMPERSONATE), EPERM (attaching would lower the
token's level), EBADF (a descriptor in fds is not open), plus the
sendmsg set (ENOTCONN, EPIPE, EMSGSIZE, EAGAIN).
peios_socket_recv_message — EINVAL (NULL msg), plus the recvmsg set
(ENOTCONN, EAGAIN, EBADF). peios_socket_peer_pidfd — ENODATA (no
connected peer to name), ENOPROTOOPT (a kernel without SO_PEERPIDFD),
ENOTSOCK, EBADF, EMFILE.
The client side of a job submission (PSPU §7) is the archetype — one record, one identity, two descriptors:
const char *request = "{\"command\":\"submit\",\"image_path\":\"/usr/bin/backup\","
"\"descriptors\":[\"control\"],\"output\":true}";
int fds = ; /* named descriptors first, output sink last */
/* `job_token` is a token I hold with TOKEN_IMPERSONATE; the job runs as it. */
if
/* I still own job_token, control_sock and my stdout. */
and the manager's side, receiving it:
char buf;
int fds;
struct peios_socket_message msg = ;
ssize_t n = ;
if
if
if
if else
/* msg.fds[0..msg.fd_count] and msg.token_fd are mine to use and close */
3.3 The Token-spec Builder
Peios / Developing for Peios / SDK Reference / token.h — Tokens
Minting a token means assembling a 192-byte-header wire format with many
optional sections. The builder is the ergonomic path — typed setters, no
hand-packed offsets — and follows the standard sticky-error builder
rules: the setters return void,
the first error latches, you check peios_token_builder_error at the end, and
you _free every builder.
typedef struct peios_token_builder peios_token_builder;
peios_token_builder *;
void ;
void ;
3.3.1 The index convention #
Three fields — the owner, the primary group, and the restrict/deny indices — refer to SIDs by index into the token's own SID list rather than by value. The convention is fixed:
Index 0 is the user SID. Indices 1..N are the 1st..Nth group you added with
peios_token_builder_add_group, in order.
So to make the second group the primary group, you set primary_group_index
to 2. Do not add the logon SID yourself — the kernel injects it.
3.3.2 Core fields #
void ;
void ;
void ;
void ;
void ;
void ;
void ;
void ;
void ;
| Setter | Sets |
|---|---|
_user | The user SID (index 0). |
_add_group | Appends a group SID with its KACS_SE_GROUP_* attribute word (enabled, mandatory, deny-only, …). Call once per group, in the order you want them indexed. |
_privileges | The privilege bitmasks: present (which privileges the token holds) and enabled (which are on). Bits are KACS_SE_*_PRIVILEGE. |
_type | The token type (KACS_TOKEN_TYPE_* — primary or impersonation) and the impersonation level imp_level (KACS_IMLEVEL_*). Choose the level deliberately: it caps every identity derived from the token, including a primary. CreateToken accepts all four levels; Identification permits peers to identify the process without acting as it, and Anonymous hides its identity from peers. The process still acts as its own user. Older kernels reject primary levels below Impersonation. DuplicateToken retains its separate Impersonation floor for primary results. |
_integrity | The integrity level, as the RID of an S-1-16-<rid> label (see peios_integrity_level). |
_session | The logon session id the token references. |
_owner_index / _primary_group_index | Which SID (by index) is the default owner / primary group. |
_default_dacl | The default DACL applied to new objects the token creates (ACL bytes, for example from a peios_acl_builder). |
3.3.3 Advanced fields #
These cover the rest of the token-spec and can be left unset. They are marked
[adv] in the header for a reason — most tokens need none of them.
void ;
void ;
void ;
void ;
void ;
void ;
void ;
void ;
void ;
| Setter | Sets |
|---|---|
_mandatory_policy | The mandatory-integrity policy bits governing how the integrity label is enforced. |
_projected_ids | The POSIX uid/gid this token projects into the Linux-compatibility layer. |
_expiration | An absolute expiry time after which the token is not valid. |
_source | The token's source: an 8-byte name and a source_id, recording who issued it (appears in audit). |
_audit_policy | Per-token audit policy bits. |
_add_restricted_sid | Appends a restricting SID (a write-restricted / restricted token intersects these against the normal SIDs). |
_add_device_group | Appends a device group SID (the device/machine side of a claim-aware token). |
_confinement | The confinement/AppContainer package SID that sandboxes the token. |
_supp_gids | Replaces the projected supplementary GIDs (pass NULL, 0 to clear). |
3.3.4 Token flags #
The four boolean token-spec flags are set together, so a designated initializer reads clearly:
;
void ;
write_restricted— the token's restricting SIDs are checked only for write access.user_deny_only— the user SID is usable for deny ACEs but not to grant access.isolation_boundary— marks an isolation boundary for confinement.confinement_exempt— the token is exempt from confinement checks.
3.3.5 Claims #
A claim is a named, typed, multi-valued security attribute — the input to conditional (callback) ACEs. Claims come in user and device flavors; both share the same shape.
;
;
void ;
void ;
The value_type selects which member of each value carries the data:
value_type | Value member |
|---|---|
KACS_CLAIM_TYPE_INT64 / _UINT64 / _BOOLEAN | scalar (a boolean is 0 or 1). |
KACS_CLAIM_TYPE_STRING | bytes/len — a UTF-8 string (transcoded to UTF-16LE on the wire). |
KACS_CLAIM_TYPE_SID | bytes/len — a binary SID. |
KACS_CLAIM_TYPE_OCTET | bytes/len — an opaque blob. |
Each claim you add is round-tripped through the kernel's own claim parser
before acceptance, so a malformed claim latches EINVAL on the builder
immediately — you find out at build time, not at token-create time.
3.3.6 LCS registry credentials #
The final optional section grants the token registry-layer powers: which layer scopes it can resolve and which private layers it owns.
;
void ;
Setting it replaces any prior credentials; it is emitted as the last
token-spec section. See
<peios/registry.h>
for what layers and scopes mean.
3.3.7 Finishing the builder #
ssize_t ;
int ;
int ;
peios_token_builder_bytesreturns the serialized length and, ifoutis non-NULL, writes a pointer into the builder (valid until the next reset/free) through it. Use this if you want the raw token-spec bytes.peios_token_builder_createdoes it in one step: serialize and mint, returning the new token fd. This is the usual call. It requiresSeCreateTokenPrivilege.peios_token_builder_errorreturns the latched errno, or0.
Errors: _bytes and _create first surface any latched builder error —
EINVAL (malformed field, SID, claim, or index) or ENOMEM (allocation
failed). A clean _create then adds the peios_token_create_raw set: EPERM
(privilege missing), EINVAL (spec failed kernel validation), ENOMEM.
peios_token_builder *tb = ;
;
;
;
;
;
int tok = ; /* -1 on failure */
if
;
3.4 Query
Peios / Developing for Peios / SDK Reference / token.h — Tokens
You read a token's contents by information class. The generic reader handles any class getxattr-style; typed convenience wrappers cover the common ones.
ssize_t ;
ssize_t ; /* CLASS_USER */
peios_token_queryreads the classinfo_class(KACS_TOKEN_CLASS_*) intobufusing the two-call protocol. Classes that return SID arrays or ACLs are parsed afterward with the<peios/security.h>views — for example readCLASS_GROUPSinto a buffer, thenpeios_sid_array_parseit.peios_token_useris the same two-call read specialized to the user SID (CLASS_USER): probe withsid_buf == NULL, cap == 0, then retrieve.
For the common scalar classes there are typed helpers that write through a
mandatory non-NULL out-pointer and return 0 / -1:
;
;
int ; /* CLASS_TYPE */
int ; /* CLASS_IMPERSONATION_LEVEL */
int ; /* CLASS_INTERACTIVITY_SCOPE */
int ; /* CLASS_GUID */
int ; /* CLASS_STATISTICS */
int ; /* CLASS_INTEGRITY_LEVEL */
int ; /* CLASS_PRIVILEGES */
peios_token_impersonation_level reads the token's impersonation level
(KACS_IMLEVEL_*): the ceiling on everything captured from, conveyed by, or
duplicated out of it — on a primary token as much as an impersonation one,
since the level only ever ratchets down (Kernel TRM §3.5.1). A manager handed
a token over a socket reads this before deciding what the token can become; a
token below Impersonation cannot be turned into a primary token for a new
process.
peios_token_interactivity_scope reads the token's interactive-environment
scope. It is not a logon-session identifier. To read the token's uint64_t
LogonSession LUID, use peios_token_statistics and inspect auth_id; that
helper returns the complete fixed-width statistics record.
peios_token_guid writes the immutable 16-byte token GUID used by KMES. The
caller supplies 16 writable bytes; the helper leaves them unchanged on
failure. The result contains raw bytes in KMES order. The query requires
TOKEN_QUERY; kernels predating KACS_TOKEN_CLASS_GUID return
EINVAL. Deploy the supporting kernel before consumers. The statistics record
and its LUID remain unchanged.
peios_token_privileges returns all four privilege words at once: which
privileges are present, which are enabled, which are enabled_by_default,
and which have been used (the audit trail of privilege use).
Errors (all query calls): EACCES (handle lacks QUERY), EINVAL (unknown
class), ERANGE (non-probe buffer too small), EFAULT (bad buffer pointer).
The typed helpers add EINVAL (NULL out-pointer, or an unexpected payload
shape).
3.5 Adjust and Transform
Peios / Developing for Peios / SDK Reference / token.h — Tokens
These change a token or derive a new one from it. Deriving calls return a new
fd; in-place adjustments return 0 / -1.
3.5.1 Privileges and groups #
int ;
int ;
int ;
int ;
peios_token_adjust_privilegesenables/disables the privileges named inentries(each akacs_priv_entry); ifprev_enabledis non-NULLit receives the prior enabled mask, so you can restore it later.peios_token_reset_privilegesrestoresenabled := enabled_by_default. Errors:EACCES(handle lacksADJUST_PRIVILEGES),EINVAL(empty or oversized batch, duplicate entry, enabling an absent privilege, unknown attribute bits),EFAULT(bad entries pointer).peios_token_adjust_groupsis the group analogue.prev_state, if non-NULL, points at a caller array ofKACS_TOKEN_GROUP_MASK_WORDSuint64_twords that receives the prior enabled bitmask.peios_token_reset_groupsrestores the default group state. Errors:EACCES(handle lacksADJUST_GROUPS),EINVAL(mandatory, deny-only, or logon-SID group targeted; duplicate or out-of-range index; empty batch),EFAULT(bad entries pointer).
3.5.2 Duplicate and restrict #
int ;
;
int ;
peios_token_duplicatecopies the token, returning a new fd with handle rightsaccess, tokentype(KACS_TOKEN_TYPE_*), and impersonation levelimp_level(KACS_IMLEVEL_*). This is how you turn a primary token into an impersonation token, an impersonation token into a primary one for a process launched as that identity, or narrow a handle's rights.imp_levelis a ratchet: it can equal or lower the source's level, never raise it, whichever direction the type goes. Errors:EACCES(handle lacksDUPLICATE, or the new token's SD deniesaccess),EINVAL(unknowntype/imp_level, a level above the source's, a primary requested belowKACS_IMLEVEL_IMPERSONATION, empty or unknownaccessbits),ENOMEM(allocation failed).peios_token_restrictcreates a filtered token — the sandboxing primitive. It can delete privileges (privs_to_delete), demote groups to deny-only (deny_group_indices, by index), add restricting SIDs (restrict_sids/restrict_sid_lens), and setKACS_TOKEN_RESTRICT_WRITE_RESTRICTED. The result is a strictly less-powerful token you can hand to less-trusted code. Errors:EACCES(handle lacksDUPLICATE),EINVAL(duplicate or out-of-range deny index, malformed restricting SID, unknownflags,NULLspec, or arrays),ENOMEM(allocation failed).
3.5.3 Impersonation and installation #
int ;
int ;
int ;
peios_token_installmakes this primary token the calling process's primary token. Errors:EACCES(handle lacksASSIGN_PRIMARY, orSeAssignPrimaryTokenPrivilegemissing),EINVAL(not a primary token),EAGAIN(thread set changed mid-install — retry),ENOMEM(allocation failed).peios_token_impersonatemakes this impersonation token the calling thread's effective identity — subsequent access checks on that thread run as the impersonated identity. Errors:EACCES(handle lacksIMPERSONATE),EINVAL(not an impersonation token),EPERM(restricted→unrestricted same-user — the one hard deny),ENOMEM(allocation failed).peios_token_revertundoes it: it clears the thread's impersonation token so checks run as the thread's real (primary) identity again. It takes no argument and is a no-op (reported as success) if the thread was not impersonating. This is the inverse ofpeios_token_impersonate— always pair them, ideally withrevertin the cleanup path. Errors: none in normal operation.
The archetypal server flow: peios_token_open_peer the caller →
peios_token_impersonate it → do the work as them → peios_token_revert.
peios_token_impersonate_peer (see Opening and creating
tokens) fuses the first two
steps and the close.
3.5.4 Linked tokens and defaults #
int ;
int ;
int ;
int ;
peios_token_linklinks an elevated + filtered primary-token pair inlogon_session_id— the UAC-style split-token model, where a filtered token is the everyday identity and its elevated linked token is available on demand.peios_token_get_linkedopens the linked token offd, returning a new fd. Errors (_link):EACCES(SeTcbPrivilegemissing, or either handle lacksDUPLICATE),EINVAL(self-link, role/logon-session/user-SID mismatch, not primary tokens, unknownlogon_session_id, or an fd that is not a token fd),EBADF(invalid fd). Errors (_get_linked):EACCES(handle lacksQUERY),ENOENT(not part of a linked pair, or the pair was destroyed),ENOMEM(allocation failed).peios_token_adjust_defaultreplaces the token's default DACL, owner/primary-group indices, or both.dacl == NULLleaves the DACL unchanged (and ignoreslen);dacl != NULLwithlen == 0clears it; an index of0xFFFFleaves that index unchanged. Errors:EACCES(handle lacksADJUST_DEFAULT),EINVAL(out-of-range index; malformed or oversized DACL),EFAULT(bad DACL pointer).peios_token_set_interactivity_scopechanges the token'suint32_tinteractive-environment scope (requiresSeTcbPrivilege). This is deliberately separate from the token'suint64_tLogonSession LUID (auth_id) and does not move the token between logon sessions. Errors:EACCES(handle lacksADJUST_INTERACTIVITY_SCOPE, orSeTcbPrivilegemissing).
3.6 Logon Sessions
Peios / Developing for Peios / SDK Reference / token.h — Tokens
A logon session is the lightweight kernel bookkeeping a token references —
the "logon" a token belongs to. Creating and destroying them requires
SeTcbPrivilege.
;
int ;
int ;
peios_session_createcreates a logon session of typelogon_type(KACS_LOGON_TYPE_*— interactive, network, service, …) foruser_sid, attributing it toauth_package.id_outis mandatory and receives the new session id, which you then pass topeios_token_builder_session. Errors:EPERM(SeTcbPrivilegemissing),EINVAL(NULLspec,id_out, or field; malformed SID; oversized spec),EFAULT(bad pointer),ENOMEM(allocation failed).peios_session_destroy_emptydestroys a session that has no live tokens — it fails rather than orphaning tokens. Clean up sessions only after every token referencing them is closed. Errors:EPERM(SeTcbPrivilegemissing),ENOENT(no such session),EBUSY(live tokens, linked-pair state, or in-flight references).
3.6.1 Listing sessions #
;
peios_logon_sessions *;
int ;
void ;
The kernel's own list of every live logon session, from
/sys/kernel/security/kacs/sessions. Reading it needs
BUILTIN\Administrators or SYSTEM.
peios_logon_sessions_opentakes the whole listing at once, so a walk sees one moment.NULLwitherrnoon failure:EACCES(not an administrator),ENOENT(securityfs not mounted),ENOMEM.peios_logon_sessions_nextfillsoutwith the next session and returns1, or0when there are no more. The pointers inoutstay valid until the next call.-1withEPROTOmeans a line it could not read; call again to step past it.peios_logon_sessions_closefrees the reader.
A session is listed while anything holds it, which includes a session nothing
has used yet, so a listing can hold sessions with no process in them. SYSTEM's
session is 999. To find a session's processes, read each process's token's
auth_id (TokenStatistics) and match it.
peios_logon_sessions *s = ;
struct peios_logon_session one;
while
;
;
3.7 The Generic Mapping
Peios / Developing for Peios / SDK Reference / token.h — Tokens
extern const struct kacs_generic_mapping peios_token_generic_mapping;
The canonical generic→specific rights mapping for the token object class.
Pass it to peios_access_map_generic or
as the mapping in a peios_access_request
when the object under check is a token.
4.1 Access Checks
Peios / Developing for Peios / SDK Reference / access.h — Access Checks
<peios/access.h> answers the central question of the whole access-control
model: can this subject perform this access on this object? You hand it a
token, a security descriptor, and a desired access mask, and it runs the full
KACS AccessCheck pipeline and tells you whether access is granted and exactly
which rights were granted.
Two things are worth saying up front:
- These calls are advisory. They evaluate, they do not enforce.
peios_access_checktells you what the answer would be; enforcement of a real operation always runs inside the kernel against the subject's own process security block. Use these when your code is the resource manager — you hold an object, you have its security descriptor, and you need to make the grant/deny decision yourself. - A denial is a normal result, not an error. Per the library
conventions,
a denied check returns
-1witherrno == EACCES, and the granted mask is still written out. Only a genuine failure (a bad token fd, a malformed SD) is an error in the usual sense.
4.1.1 See also #
<peios/security.h>— building the security descriptors and reading the generic-mapping tables this check consumes.<peios/token.h>— obtaining thetoken_fdto check, andpeios_token_generic_mapping.- Access decisions — the operator-side account of how KACS reaches a grant/deny decision.
4.2 The Request
Peios / Developing for Peios / SDK Reference / access.h — Access Checks
Every check is described by a single struct peios_access_request. Only the
first block is needed for an ordinary check; everything below the divider is
advanced and can be left zero/NULL. For every pointer/length pair, NULL is
valid only when the matching length or count is zero.
;
4.2.1 The core fields #
| Field | Meaning |
|---|---|
token_fd | The subject token to evaluate. -1 means the caller's own effective token — the common case when you are checking access for yourself. Otherwise pass a token fd from <peios/token.h>. |
sd / sd_len | The object's security descriptor, as self-relative wire bytes — typically from a peios_sd_builder or read off the object. |
desired | The access mask you want checked. It can contain generic bits; the mapping resolves them. |
mapping | The object class's generic mapping (a struct kacs_generic_mapping), so generic rights in desired and in the SD's ACEs fold to the right object-specific bits. Use the class's published table — for example peios_file_generic_mapping or peios_token_generic_mapping. |
4.2.2 The advanced fields #
Leave these zero/NULL unless you need them:
| Field | Meaning |
|---|---|
self_sid / self_sid_len | The SID to substitute for PRINCIPAL_SELF (S-1-5-10) in ACEs — the "self" the object belongs to. |
privilege_intent | Backup/restore intent bits, letting SeBackupPrivilege / SeRestorePrivilege widen the granted mask as they would for a real backup or restore. |
object_tree / object_tree_count | An object-type tree for a per-property check (object ACEs with type GUIDs). Mandatory for peios_access_check_list. |
local_claims / local_claims_len | An @Local claim array to evaluate conditional ACEs against, beyond the claims already on the token. |
pip_type / pip_trust | Process-integrity-protection trust label to evaluate against; pip_type == 0 uses the subject's own PSB. |
audit_context / audit_context_len | The identity of the object a daemon is guarding, for the audit record of the check: one MessagePack map holding kind and, under a key equal to the kind, the object's identifying fields — {kind: "service", service: {name: "jellyfin"}} — as PGSS §6.7 defines. The kernel accepts only that shape and fails the check with EINVAL otherwise. It copies the map into the kacs.audit.access.checked record as object.kind and object.<kind>.*, and marks the record fields.attestation.userspace, because the values are the caller's claim. Build it with peios_audit_context_encode. Both check calls validate a non-NULL context before the syscall and fail with EINVAL if the kernel would refuse it. |
4.3 The Check
Peios / Developing for Peios / SDK Reference / access.h — Access Checks
int ;
Runs the full AccessCheck pipeline. Returns:
0if every right indesiredis granted;-1witherrno == EACCESif any desired right is denied;-1with another errno on a real error (for exampleEBADFfor a badtoken_fd,EINVALfor a malformed SD).
granted, if non-NULL, always receives the granted access mask — even
on denial. This is the useful part: you can request a broad desired and read
back exactly which subset was granted, rather than probing one right at a
time. audit, if non-NULL, receives the audit
outputs.
struct peios_access_request req = ;
uint32_t granted = 0;
int rc = ;
if else if else
libpeios owns the versioned struct kacs_access_check_args under the hood —
it sets caller_size and zeroes the reserved fields so the request stays
forward-compatible across kernel versions. You only ever fill in the
peios_access_request above.
4.3.1 A supplied identity without a token #
int ;
Use this separate entry point when a trusted identity authority supplies a
principal SID, source groups and disclosed claims without creating an OS logon
token. libpeios packs the facts for the stateless kernel query, syscall 1028.
An older kernel returns ENOSYS; no userspace fallback runs. Supplying
SYSTEM's SID computes a hypothetical result; it conveys no SYSTEM authority.
The SD must be valid and have an owner. Set subject.size to its structure size and request.token_fd to -1. Here -1 is a required sentinel and never selects the caller's token. The privilege-intent, PIP, and request-local claim fields must be zero or NULL; local claim knowledge belongs in subject.
Subject group entries contain a SID span and KACS group attributes, including enabled and deny-only flags. A NULL list with zero count is unknown. A non-NULL list with zero count is a complete empty set. A NULL list with nonzero count is invalid. Group, claim, and known-absence arrays are bounded to 1024 entries. Group SIDs must be unique.
Each optional claim context contains typed peios_token_claim values, explicit known-absent names, and a complete flag. These use the same claim encoding and validation as the token builder. With complete equal to zero, any name not in the values or known-absent list remains unknown. With complete equal to one, omitted names are absent. Values and absence assertions must not contradict one another; equivalent names must be unique. Absent names are UTF-8 strings of 1–255 bytes. An omitted claim context is unknown, not an empty set.
Name equivalence follows the KACS conditional evaluator's Unicode lowercase mapping. An absence assertion must cover that entire equivalence class. A source using different name rules needs an adapter; copying its named absence responses directly can turn an existing equivalent claim into an apparent absence. Updated PGSS named disclosure uses this same rule, so its explicit absent_claims supply partial knowledge. Clients and authority must both use the updated Unicode name contract; the superseded ASCII-only development contract is incompatible for this purpose. A complete AllPermitted result can supply complete knowledge; a Filtered result supplies values with partial coverage and no invented absences. Conflicting equivalent values are invalid.
The return value is zero for all three decisions. Inspect out.decision:
| Decision | Meaning |
|---|---|
| PEIOS_SUBJECT_ACCESS_GRANTED | All requested rights were granted |
| PEIOS_SUBJECT_ACCESS_DENIED | The supplied facts establish denial |
| PEIOS_SUBJECT_ACCESS_MISSING_CONTEXT | More context is needed for a safe answer |
Missing-context results carry a zero granted mask and a category bitmask in out.missing. They do not identify restricted claim names or values. A service must not admit a caller using a provisional or partial answer. Missing-data detection is conservative and can request context from an irrelevant branch. Errors return -1 with errno; do not use a returned decision after an error.
The initial identity-only interface reuses KACS DACL, group, conditional, and object-list semantics. It does not invent process privileges, integrity, confinement, or a logon session. Explicit integrity/trust labels, scoped policy, and privilege-sensitive rights report missing execution context. Resource claims can be read from the supplied SD's SACL. This is not a replacement for the full token pipeline or kernel object enforcement.
For object ACEs, supply the object tree and select the node with object_index. Without a tree, the index is zero and GUID-scoped ACEs report missing object context instead of being interpreted as global grants.
Matching SACL audit ACEs emit kacs.audit.subject.checked when the actual
caller holds enabled SeAuditPrivilege. The event's subject describes that
caller; source.supplied-subject.sid is explicitly hypothetical. An optional
AuditContext names the guarded object. No context leaves it unnamed.
Audit-only missing facts require more context while auditing is active; they
do not block the decision when the privilege gate suppresses records or the
extended entry point peios_access_check_subject_ex receives
PEIOS_SUBJECT_NO_AUDIT. Mandatory SACL labels still require execution
context in either mode. Missing-context decisions emit no completed-check
record. Detected audit preparation or submission errors fail the query;
successful submission carries the existing KMES guarantees, without a
durability promise. A service separately records its actual admission outcome.
The kernel copies one bounded request and validates that owned copy. A concurrent writer can produce a torn copy, which is still treated as untrusted input. Requests larger than 1 MiB, excessive collections, conflicting facts, and malformed sections are rejected whole. Typed claims are bounded to 64 KiB per namespace and 1024 values per attribute. The aggregate sum of encoded entry bytes multiplied by max(value count, 1), including descriptor resource claims, cannot exceed 1 MiB; this bounds repeated-offset decoding before allocation. No facts are silently truncated.
The safe Rust wrapper exposes AccessCheck::check_subject and
check_subject_by_type with SuppliedSubject, SuppliedClaims, and an explicit
SubjectAccessDecision. Use audit_context to label the guarded object and
subject_no_audit(true) to suppress this query's audit records. That setter
does not alter real-token checks or service admission events.
4.4 Audit Outputs
Peios / Developing for Peios / SDK Reference / access.h — Access Checks
;
When you pass a non-NULL audit, the check reports:
continuous_audit— the OR of the masks of anySYSTEM_ALARMACEs that matched. An enforcement point that keeps this mask on a handle emits akacs.audit.handle.usedevent for each later operation whose required access overlaps it.staging_mismatch—1if evaluating the staged central access policy would have produced a different result than the active one. This is the signal you watch when rolling out a central access policy change: a non-zero value means the pending policy would decide this access differently. The kernel records the same difference as akacs.caap.staging.divergedevent.
These are the outputs the check hands back to you. The audit records it writes
to the event stream — kacs.audit.access.checked and
kacs.audit.privilege.used — go to KMES, not to this struct. They name the
object you checked only if the request carried an audit
context, the map {kind: "<kind>", "<kind>": {…}}; anything else in that field fails the check with EINVAL.
4.5 The Object-type-list Variant
Peios / Developing for Peios / SDK Reference / access.h — Access Checks
int ;
peios_access_check_list is the AccessCheckByTypeResultList form — a
per-node check over an object-type tree, for objects whose properties or
property sets carry their own object ACEs (a directory-service-style object,
say). It evaluates the whole tree in one call and reports a separate result
for each node.
req->object_tree/object_tree_countare mandatory here — they describe the tree ofkacs_object_type_entrynodes to evaluate.resultsreceives onekacs_node_resultper node, in preorder, andcountmust equalreq->object_tree_count.- Returns
0/-1(EINVALifcountdoesn't match, and the usual errors otherwise).
Each kacs_node_result carries that node's granted mask and status, so you
can discover, for example, that a caller can read most of an object but not
one protected property — in a single check rather than one per property.
4.6 The Audit Context
Peios / Developing for Peios / SDK Reference / access.h — Access Checks
A daemon that guards objects of its own (a service manager's services, an
event store's namespaces) makes each access decision through
peios_access_check. The kernel records that decision in a
kacs.audit.access.checked event when the descriptor's SACL asks for one, but
the kernel cannot tell what the descriptor belongs to. The audit context
tells it. It is the request's audit_context field: one MessagePack map
holding kind and, under a key equal to the kind, the fields that identify
the object.
{kind: "service", service: {name: "jellyfin"}}
The kernel copies it into the record as object.kind and
object.service.name, and marks the record fields.attestation.userspace,
because the kernel did not observe those values: they are the daemon's claim.
It refuses any other shape with EINVAL. PGSS
§6.7 is the specification. A component
that guards objects must pass one, and each field it names must be defined, as
asserted, in that component's catalog fragment.
4.6.1 Encoding one #
;
;
ssize_t ;
peios_audit_context_encode writes the map for an object of kind kind,
identified by count fields, using the two-call
protocol: pass cap == 0 to learn the size. With no fields (fields can then be NULL), the
context is {kind: <kind>}.
kind and every key must be a single segment of an event name: kebab-case,
[a-z][a-z0-9]*(-[a-z0-9]+)*, so service, log-namespace or unit-name. A
value is a scalar in one of the event wire forms:
a string, an unsigned or signed integer, a boolean, or binary. A SID goes in
as PEIOS_AUDIT_BIN with its binary bytes, never as SDDL text. There is no
nil: a field with no value is left out of the array.
struct peios_audit_field fields = ;
uint8_t ctx;
ssize_t n = ;
if
struct peios_access_request req = ;
uint32_t granted = 0;
int rc = ;
The encoder fails with EINVAL when:
- the kind or a key is not a segment, or a key is
NULL; - a key appears twice;
value_typeis not one of the five, or a boolean'sscalaris not 0 or 1;- a string is not valid UTF-8, or
bytesisNULLwhilelenis not zero; - the encoded map would be longer than
KACS_ACCESS_CHECK_MAX_AUDIT_CONTEXT_LEN(4096 bytes).
The kernel itself allows a nil value, a nested value, or a key that appears
twice inside the body. The encoder refuses all three. A field with no value is
left out (PGSS §6.5), an identifying field is a
scalar, and a repeated key would make object.<kind>.<key> ambiguous.
4.6.2 Validating one built another way #
int ;
If you build the map yourself, for example with the msgpack
writer, peios_audit_context_validate checks it
against the kernel's own rules. It returns 0 if the kernel would accept it,
and -1 with EINVAL otherwise, including for NULL or empty input. The
rules are:
- the top level is a map holding a string
kindthat is one segment, and at most one other key; - that key, if present, equals the kind, and its value is a non-empty map whose keys are segments;
- nothing follows the map;
- the bytes are well-formed MessagePack (UTF-8 strings, no reserved
0xC1byte), nested no deeper than 31 levels. That is the event nesting limit less one, because the context lands one level below the record's root; - the map is at most 4096 bytes.
peios_access_check and peios_access_check_list apply the same check to any
non-NULL audit_context before they make the syscall. A malformed context
therefore fails there with EINVAL, without reaching the kernel. A non-NULL
pointer with a zero length is refused too, as the kernel refuses it.
4.6.3 Language bindings #
Audit Contexts in Rust explains
owned encoding and AccessDecision results.
Audit Contexts in Go uses the
maintained access package and its explicit denial errors.
5.1 File Security
Peios / Developing for Peios / SDK Reference / file.h — File Security
<peios/file.h> is the file surface of KACS. Where ordinary POSIX open()
gives you a file descriptor governed by mode bits, peios_file_open performs
a native KACS open — an NtCreateFile-shaped call carrying a desired
access mask, a create disposition, create options, the sharing it allows
other opens, and an optional creator security descriptor — and hands back
an ordinary Linux file fd whose granted access mask is fixed for the fd's
lifetime. Because the grant is baked into
the fd, it can be delegated safely by dup, SCM_RIGHTS, or across exec:
whoever holds the fd holds exactly the access it was opened with, no more.
Alongside the open, this module:
- reads back what an open was granted, sets its file's delete disposition and renames the link it names (Working through a handle);
- takes NT byte-range locks and leases through it (Locks and leases);
- reads and sets a file's read-only flag and Created At (Special attributes);
- reads and writes a file's security descriptor, by path or by fd; and
- governs how a superblock without native SD storage is treated.
The wire constants and argument structs (KACS_DISPOSITION_*,
KACS_CREATE_OPT_*, KACS_FILE_*, KACS_OPEN_*, KACS_RENAME_*,
KACS_LOCK_*, KACS_LEASE_*, KACS_SATTR_*, KACS_SECINFO_*,
KACS_MOUNT_POLICY_*, KACS_STATUS_*, struct kacs_open_info,
struct kacs_lease_break, struct kacs_sattr) come from <pkm/file.h> and
<pkm/sd.h>. The security descriptors these calls exchange
are built and parsed with
<peios/security.h>.
5.1.1 See also #
<peios/security.h>— building the creator SDs and parsing the SDs these calls return.<peios/access.h>— evaluating a file SD withpeios_file_generic_mapping.- File access and Mount policies — the operator-side model of native file security.
- Sharing and Deletion — the kernel's rules for share modes, delete-pending files and pinning.
5.2 Opening a File
Peios / Developing for Peios / SDK Reference / file.h — File Security
peios_file_open requests an explicit access mask and creation policy.
The returned descriptor represents the access granted by the kernel. The
kernel native-open guide
describes the kernel's validation and file creation behavior.
;
int ;
peios_file_open opens path relative to dirfd (the usual *at convention — an absolute path ignores dirfd, and AT_FDCWD means the current
directory). It returns a file fd, or -1 with errno.
Zero-initialize the struct and set the fields you need. share_access and the
lease fields are read only when flags carries their flag, so a zeroed struct
opens the way a plain open(2) does: sharing read, write, and delete.
The parameters:
| Field | Meaning |
|---|---|
desired_access | The access mask you are requesting — KACS_FILE_* object rights, standard rights, or generic bits the file class maps. Every right named has to be granted, or the open fails with EACCES. MAXIMUM_ALLOWED asks for everything you can have, and can be named alone. |
disposition | What to do about existence: KACS_DISPOSITION_* — open-existing, create-new, open-or-create, supersede, overwrite, and so on. This is the create/open decision open() splits across O_CREAT/O_EXCL/O_TRUNC. |
options | KACS_CREATE_OPT_DIRECTORY and KACS_CREATE_OPT_DELETE_ON_CLOSE; other bits fail with EINVAL. No-follow belongs in flags, not options. |
flags | AT_SYMLINK_NOFOLLOW; the privilege-intent flags KACS_BACKUP_INTENT / KACS_RESTORE_INTENT; and the flags that switch on the fields below. |
sd / sd_len | The creator security descriptor — the SD to stamp on a newly created file. Pass NULL when opening an existing file (or to let the parent's inheritance decide the new file's SD). |
share_access | With KACS_OPEN_SHARE_ACCESS: which kinds of access other opens of the file can have while this one is open — KACS_FILE_SHARE_READ, _WRITE, and _DELETE. |
lease_fd / lease_key | With KACS_OPEN_LEASE_KEY: a lease manager and the key this opener holds leases under. Opening does not break leases held under the same manager and key (Locks and leases). |
KACS_OPEN_PIN_ANCESTORS keeps the directories above the file from being
renamed or removed while the open lasts, as Windows does for a file it has
open. It needs SeLockParentagePrivilege enabled, and fails with EPERM
without it.
5.2.1 What the descriptor can do #
The descriptor's access is fixed when it opens. Read it back with
peios_file_query_open, which is
how you learn what a MAXIMUM_ALLOWED open received.
The descriptor is readable if it was granted FILE_READ_DATA and writable if
it was granted a write right. An open granted neither is a control
handle: it cannot read or write the file's contents, but it can read
attributes, read and change the security descriptor, set a delete
disposition, and rename. You do not need to ask for a data right to get
a descriptor.
An open that creates the file gets the access it asked for, even where the new file's descriptor would not grant it, as in Windows. You can create a file with a restrictive descriptor and still write it, in one step. Integrity labels, restricted tokens and confinement still apply, and later opens are checked against the descriptor as normal.
DELETE and FILE_READ_ATTRIBUTES can come from the parent directory: from
FILE_DELETE_CHILD and FILE_LIST_DIRECTORY on it, as NTFS grants them.
5.2.2 Sharing #
Every open of a regular file or directory takes part in share checking,
including plain open(2). An open that conflicts with another fails with
EBUSY. Without KACS_OPEN_SHARE_ACCESS your open shares everything; with
it, other opens are refused the kinds of access you leave out — but only
those you could exercise yourself, so a reader cannot lock others out of a
file it could not change. See Sharing and
Deletion for the
rules.
5.2.3 Status and errors #
status_out, if non-NULL, receives a KACS_STATUS_* code telling you what
happened — whether the file was opened, created, superseded, overwritten. For
OPEN_IF with no creator SD (sd = NULL, sd_len = 0), this distinguishes
"created a new file" from "opened the existing one" without a separate stat
race. Supplying a creator SD changes the existing-file behavior described
by the disposition rules.
When the open fails for a reason errno alone cannot tell apart, status_out
names it:
| Status | errno | Condition |
|---|---|---|
KACS_STATUS_SHARING_VIOLATION | EBUSY | Another open's sharing conflicts with this one. |
KACS_STATUS_DELETE_PENDING | EBUSY | The file is marked to be deleted when its last open closes. |
KACS_STATUS_CANNOT_DELETE | EPERM | Delete-on-close on a read-only file. |
Other errors include EACCES (a requested right denied), EEXIST
(create-new and the file exists), ENOENT (open-existing and it doesn't),
ENOTDIR (directory option, non-directory target), ELOOP (native open with
no-follow and a final symlink), EPERM (pinning without the privilege),
EINVAL (unsupported create-option bits, a field set without its flag,
malformed creator SD, NULL path/p, sd == NULL with sd_len != 0), and
EBADF (bad dirfd, or a lease_fd that is not a lease manager).
Supplying a creator SD with OPEN fails with
EOPNOTSUPP, and with OVERWRITE fails with EINVAL. With OPEN_IF or
OVERWRITE_IF, it fails with EINVAL when the path resolves to an existing
object. The SDK forwards the disposition and SD; it does not silently drop the
SD on that branch. See the kernel native-open guide for
disposition rules.
Use create-only when an explicit creator SD is required:
struct peios_open_params p = ;
uint32_t status = 0;
int fd = ;
if
/* On success, status == KACS_STATUS_CREATED. */
To open an existing file for reading while nobody else writes or deletes it:
struct peios_open_params p = ;
uint32_t status = 0;
int fd = ;
if
To open an existing object, use KACS_DISPOSITION_OPEN with sd = NULL and
sd_len = 0. If create-only returns EEXIST, decide whether opening the
existing object is appropriate before issuing that separate call. A
create/open retry is not an atomic transaction; neither is a stat-then-open
check.
The wrapper forwards options, flags, the share access, the lease fields
and the creator descriptor to the kernel, and zeroes reserved fields.
Supplying an option through the library does not make an unsupported kernel
option valid.
5.3 Reading and Writing a File's Security Descriptor
Peios / Developing for Peios / SDK Reference / file.h — File Security
A file's SD can be accessed by path or by fd. In both cases secinfo
is a mask of KACS_SECINFO_* bits selecting which components (owner, group,
DACL, SACL, …) the operation touches — you read or write the parts you name
and leave the rest alone.
The rights required scale with the components you touch (see Managing file security):
Component (KACS_SECINFO_*) | Reading needs | Writing needs |
|---|---|---|
OWNER / GROUP | READ_CONTROL | WRITE_OWNER (plus owner-SID validation) |
DACL | READ_CONTROL | WRITE_DAC |
SACL | ACCESS_SYSTEM_SECURITY | ACCESS_SYSTEM_SECURITY |
LABEL | READ_CONTROL | WRITE_OWNER (the label cannot rise above the caller's integrity without SeRelabelPrivilege) |
ACCESS_SYSTEM_SECURITY is itself gated by SeSecurityPrivilege;
READ_CONTROL and WRITE_DAC are implicitly granted to the owner. SACL and
LABEL cannot be combined in one call (EINVAL). The check is
all-or-nothing: if any requested component fails its check, the whole call
fails.
5.3.1 By path #
ssize_t ;
int ;
peios_file_get_sdreads thesecinfo-selected components ofpath's SD intobuf, getxattr-style (two-call protocol — probe withcap == 0, and a too-small non-zero buffer failsERANGEwithout truncating).at_flagsacceptsAT_SYMLINK_NOFOLLOW; in the kernel interface, it queries the terminal symlink's own SD instead of following it. Errors:EACCES(component right missing),EINVAL(SACL+LABELtogether;NULLpath, orNULLbuffer with non-zerocap),ERANGE(non-probe buffer too small),ENOENT(path doesn't exist),ELOOP(a path-resolution failure, not a blanket rejection of a terminal symlink under no-follow).peios_file_set_sdwrites thesecinfocomponents ofsdontopath, preserving the components you did not select. So to change only the DACL, build an SD with a DACL, passsecinfo = KACS_SECINFO_DACL, and the owner/group/SACL are untouched. Errors:EACCES(component right missing),EPERM(owner-SID validation failed withoutSeRestorePrivilege; label raised withoutSeRelabelPrivilege; MANDATORY attribute removed withoutSeTcbPrivilege),EINVAL(malformed SD,SACL+LABELtogether,NULLor zero-lengthsd),ENOENT,ELOOP.
Path flags belong to the operation that receives them. A no-follow file open and a no-follow security query have different purposes: the query can select the terminal link's descriptor. Do not infer one operation's behavior from another. Use an owned handle when the application needs to avoid a second path lookup.
5.3.2 By fd #
ssize_t ;
int ;
The same operations against the object fd already refers to. The access
check they perform depends on the fd type: a normal file fd is checked against
its cached granted mask (the one baked in at open), while an O_PATH,
pidfd, or token fd triggers a live check. That distinction — cached for
the fixed-grant file fd, live for the others — is documented in the Peios
Kernel TRM §3.9, FACS; the practical upshot is that a file fd already opened
with the right access can get/set its SD without a second path resolution.
The required rights and errors match the by-path calls, minus the
path-resolution failures (ENOENT/ELOOP), plus EBADF (bad fd).
5.3.3 By IPC kind and ID #
ssize_t ;
int ;
System V message queues, shared memory segments, and semaphore arrays carry
security descriptors too (Peios Kernel TRM §3.11), but have neither a path nor
an fd. kind is one of KACS_SD_AT_SYSV_SHM, KACS_SD_AT_SYSV_MSG or
KACS_SD_AT_SYSV_SEM from <pkm/ipc.h>, and id is what shmget, msgget
or semget returned. The object is looked up in the caller's IPC namespace
and the check is always live against its descriptor: READ_CONTROL (or
ACCESS_SYSTEM_SECURITY for the SACL) to read, WRITE_DAC / WRITE_OWNER to
write, with the same preserve-unselected-components merge as the file calls.
Errors as for the by-fd calls, with EINVAL for an id that names nothing and
EIDRM for an object that has been removed.
5.4 Mount Policy
Peios / Developing for Peios / SDK Reference / file.h — File Security
Not every filesystem can store native security descriptors. The mount
policy governs how KACS treats a superblock that has no native SD storage —
whether files there get a synthesised SD, a template SD, or are denied. These
calls target the superblock the object fd lives on. At the pinned kernel
revision below, both require enabled SeManageVolumePrivilege or
SeTcbPrivilege, with successful privilege-use marking.
;
int ;
int ;
peios_mount_get_policyreads the policy forfd's superblock intoout. The template SD is returned into yourtmpl_bufgetxattr-style: on successout->template_sdpoints intotmpl_bufwhen that buffer was large enough, or isNULLif the superblock has no template. ANULLtemplate buffer (ortmpl_cap == 0) is valid only when you don't need the template bytes. A too-small template buffer is not an error — the call still succeeds, reports the true length inout->template_sd_len, and leavesout->template_sdNULLso you can size a retry. Errors:EPERM(neither accepted privilege enabled, or privilege-use marking failed),EBADF(bad fd),EINVAL(NULLout, orNULLtmpl_bufwith non-zerotmpl_cap),EFAULT(bad buffer pointer),ENOMEM(allocation failed).peios_mount_set_policyinstallspas the superblock's policy.policyis aKACS_MOUNT_POLICY_*value;template_sd/template_sd_lensupply the template SD when the policy calls for one.flagsandgenerationmust be zero on set — the kernel manages the generation counter itself and rejects a non-zero input. Errors:EPERM(neither accepted privilege enabled, or privilege-use marking failed),EINVAL(unknown or unmanagedpolicy, non-zeroflags/generation, malformed or oversized template,NULLtemplate with non-zero length),EOPNOTSUPP(superblock not KACS-managed),EBADF(bad fd),EFAULT(bad pointer).
5.5 The Generic Mapping
Peios / Developing for Peios / SDK Reference / file.h — File Security
extern const struct kacs_generic_mapping peios_file_generic_mapping;
The canonical generic→specific rights mapping for the file object class.
Pass it to peios_access_map_generic, or
as the mapping in a peios_access_request
when checking access against a file's SD — for example to pre-flight whether a
caller could open a file before you actually open it.
5.6 Working through a Handle
Peios / Developing for Peios / SDK Reference / file.h — File Security
These calls act on the file an open descriptor refers to, rather than on a
name. Each is authorized by the access the descriptor was granted when it
opened, so they work on the file you opened even if someone has since renamed
it, and they cannot hit a different file that has taken the old name. They
need a descriptor from peios_file_open;
any other descriptor fails with EOPNOTSUPP.
5.6.1 Reading back the grant #
int ;
Fills out from the open:
| Field | Meaning |
|---|---|
granted_access | The access mask the descriptor carries. After a MAXIMUM_ALLOWED open, this is what you received. |
share_access | The KACS_FILE_SHARE_* sharing the open allows others. |
flags | KACS_OPEN_INFO_MANAGED; _DELETE_PENDING if the file is marked for deletion; _DELETE_ON_CLOSE if this open will mark it when it closes; _ANCESTORS_PINNED if the open pins its parent directories. |
The call needs no right: it reports only what the descriptor already carries.
5.6.2 Deleting through the handle #
int ;
Sets the file's delete disposition — what happens to it once nothing has
it open. The open needs DELETE, or the call fails with EACCES. The
flags are those of NT's FILE_DISPOSITION_INFORMATION_EX:
| Flag | Meaning |
|---|---|
KACS_DISPOSITION_DELETE | Mark the file delete-pending: it is removed when its last open closes, from whichever process. Without this flag, the call clears the mark. |
KACS_DISPOSITION_POSIX_SEMANTICS | With DELETE: remove the name now, as unlink(2) does. Open descriptors carry on with the file. |
KACS_DISPOSITION_ON_CLOSE | Set or clear this open's own delete-on-close instead: the file becomes delete-pending when this open closes. |
KACS_DISPOSITION_IGNORE_READONLY | Delete a read-only file. Needs FILE_WRITE_ATTRIBUTES too. |
While a file is delete-pending its name stays and still lists, but every new
open of it fails with EBUSY and the status KACS_STATUS_DELETE_PENDING.
The removal is authorized by whoever set the mark, not by whoever closes the
file last.
A read-only file fails with EPERM unless KACS_DISPOSITION_IGNORE_READONLY
is given. A directory has to be empty when it is removed.
/* Delete the file once everyone has finished with it. */
if
;
5.6.3 Renaming through the handle #
int ;
Moves the link fd names to newpath, resolved relative to newdirfd as by
renameat2(). The open needs DELETE; the destination directory is checked
as for any rename. The flags are those of NT's FILE_RENAME_INFORMATION_EX:
| Flag | Meaning |
|---|---|
KACS_RENAME_REPLACE_IF_EXISTS | Replace an existing file at newpath. Without it, an existing name fails with EEXIST. |
KACS_RENAME_POSIX_SEMANTICS | Replace a file that is open, if all its opens share delete. |
KACS_RENAME_IGNORE_READONLY | Replace a read-only file. |
A directory is never replaced. A file that is open, delete-pending, or
read-only without the flag fails with EBUSY or EPERM. If the handle's link
has been removed, the call fails with ENOENT. Both names have to be on the
same mount, or the call fails with EXDEV.
5.6.4 See also #
- Sharing and Deletion — the kernel's rules for delete-pending files and renaming through a handle.
5.7 Locks and Leases
Peios / Developing for Peios / SDK Reference / file.h — File Security
5.7.1 Byte-range locks #
int ;
An NT byte-range lock reserves part of a file for one open. Unlike
Linux's fcntl and flock locks, which programs can ignore, these are
enforced: a read or write that conflicts with another open's lock fails
with EAGAIN, whichever program issued it.
op is one of:
| Operation | Meaning |
|---|---|
KACS_LOCK_EXCLUSIVE | Keep every other open from reading or writing length bytes from offset. |
KACS_LOCK_SHARED | Keep everyone, this open included, from writing the range. |
KACS_LOCK_UNLOCK | Release a lock this open holds on exactly that range; ENOLCK if it holds none. |
KACS_LOCK_CANCEL | Cancel the waiting request named by cookie. |
A conflicting request waits for the range to come free, unless flags carries
KACS_LOCK_FAIL_IMMEDIATELY, when it fails with EAGAIN. Give a waiting
request a cookie so that another thread can cancel it. Locks are released
when the open closes.
A lock blocks other opens' reads and writes only if the open that took it could write the file. A reader's lock still conflicts with other locks, so cooperating readers can coordinate, but it cannot stop anyone's I/O. Memory mappings are not covered.
5.7.2 Leases #
A lease lets a program cache a file — its contents, its pending writes, or an open handle to it — while nobody else needs it. When another operation would make the cached state wrong, the kernel breaks the lease: it tells the holder to flush and give up some of its state, and the operation waits until the holder acknowledges. A file server holds leases for its clients and relays the breaks to them.
int ;
int ;
ssize_t ;
A lease manager is a descriptor that receives the break notices for the
leases held under it. flags takes KACS_LEASE_MANAGER_CLOEXEC and
_NONBLOCK. timeout_ms bounds how long a break waits for acknowledgment
before the kernel completes it itself; zero gives the default of 35 seconds.
peios_file_lease requests a lease on fd's file, held under the manager and
a 16-byte key that identifies the holder. *state is the state asked for — any of KACS_LEASE_READ, _WRITE, and _HANDLE — and on return the
state granted, which can be less. Opens made with the same manager and key,
through KACS_OPEN_LEASE_KEY, do not
break it.
peios_lease_manager_read reads up to count break notices and returns how
many it read. Each names the lease by key, file, current state and the state
it is being broken to, with the reason (KACS_LEASE_BREAK_*) and an epoch
that counts the lease's breaks. Notices are never dropped, and the manager
descriptor is pollable. Answer a notice with peios_file_lease, flags =
KACS_LEASE_ACKNOWLEDGE, and a state no greater than the notice's new state,
through an open of the same file under the same key; the waiting operation
then proceeds.
5.7.3 See also #
- Byte-Range Locks and Leases — the kernel's rules, including what breaks a lease.
5.8 Special Attributes
Peios / Developing for Peios / SDK Reference / file.h — File Security
KACS keeps two attributes for every file on a managed mount:
- Read-only. A read-only regular file cannot be opened for writing or deleted, by anyone, its owner included, until the flag is cleared.
- Created At, a settable creation date. It differs from the filesystem's
birth time, which
statxreports and nobody can set: Created At is the date a person sees, which a copy or a restore can carry across.
int ;
int ;
int ;
int ;
struct kacs_sattr holds both:
| Field | Meaning |
|---|---|
version | KACS_SATTR_VERSION. |
valid | On a write, which fields to change: KACS_SATTR_VALID_ATTRIBUTES, KACS_SATTR_VALID_CREATED_AT. A read sets both. |
attributes | KACS_SATTR_READONLY. |
flags | KACS_SATTR_CREATED_AT_SET if Created At is set. |
created_at_sec, created_at_nsec | Created At, since the Unix epoch. |
A read always fills the struct: a file that has never had either attribute
set reads as not read-only with no Created At. A write changes only the fields
its valid mask names, so two programs changing different attributes cannot
undo each other. The struct means the same in both directions: a write with
KACS_SATTR_VALID_CREATED_AT sets Created At if flags carries
KACS_SATTR_CREATED_AT_SET, and unsets it if not. A struct read from one file
can therefore be written to another to copy both attributes exactly.
Reading needs FILE_READ_ATTRIBUTES and writing FILE_WRITE_ATTRIBUTES:
through the descriptor's grant for the fd forms, or a live check for the path
forms. at_flags accepts AT_SYMLINK_NOFOLLOW.
/* Make a file read-only, leaving its Created At alone. */
struct kacs_sattr a = ;
if
5.8.1 The creation date #
int ;
int ;
A file's creation date is its Created At while that is set, and its birth time
otherwise. These calls apply that rule, so a program showing or copying a
creation date does not have to. They fail with ENODATA if the file has
neither, as on a filesystem that records no birth time.
A tool that copies files and wants the copy to keep its creation date should
read it with peios_file_creation_time and set it on the copy as Created At.
5.8.2 See also #
- Special Attributes — the kernel's rules, including what read-only refuses.
6.1 Process Security
Peios / Developing for Peios / SDK Reference / process.h — Process Security
<peios/process.h> is the process-security surface of KACS. Today it is a
small module with two jobs: turning on process mitigations — the hardening
controls that live on a process's security block (PSB) — and reading a
process's PSB back. More process-security surface will land here as it
appears.
The mitigation bits are the KACS_MIT_* flags from <pkm/psb.h>
(KACS_MIT_WXP through KACS_MIT_SML, with KACS_MIT_ALL as the mask of all
valid bits). KACS_MIT_CFI is a legacy alias that expands to KACS_MIT_CFIF | KACS_MIT_CFIB. The full catalog and semantics are in the Peios Kernel TRM
§3.3, the Process Security Block.
6.1.1 Setting mitigations #
int ;
Turns on the mitigation bits named in mitigations (a mask of KACS_MIT_*).
Returns 0 on success, or -1 with errno.
Three properties define how this call behaves, and each matters:
- It is one-way. Mitigation bits can only be set, never cleared. Once a protection is on, it stays on for the life of the process. This is deliberate — a mitigation you could turn off is a mitigation an attacker could turn off — so treat each call as a permanent, additive commitment.
- It targets a process by pidfd.
pidfd == -1targets the calling process, which is the common case: a program hardens itself early in startup. Targeting another process requiresPROCESS_SET_INFORMATIONon it plus PIP dominance over it — you cannot harden (or interfere with) a process you don't already dominate. - It is activation-backed and fails closed. If a requested protection
cannot actually be activated, the call fails without mutating anything —
you never end up believing a mitigation is on when it isn't. Either every
requested bit is activated and the call succeeds, or nothing changes and it
returns
-1.
/* Harden the current process: enforce W^X and speculation mitigation lock, refuse to
proceed if either can't be activated. */
if
Because the call is all-or-nothing, request the bits you require together and check the result once: a success means the whole set is active, a failure means none of this call's bits were applied (bits set by earlier successful calls remain on).
6.1.2 Reading a PSB #
;
int ;
Reads process pid's PSB, from /proc/<pid>/psb, into *out. pid <= 0
reads your own. Returns 0, or -1 with errno.
- Your own is always readable.
- Another process's needs
PROCESS_QUERY_LIMITEDon its descriptor — which the default process descriptor gives Everyone — and not PIP dominance. A protected process's PIP type and trust are therefore readable when nothing else about it is, which is what lets a tool explain why it cannot see more.
mitigations is the committed set: bits a call asked for but could not
activate are not in it, and neither is the KACS_MIT_CFI alias.
process_guid identifies the process for its whole life, unlike its pid, and
is what events carry.
Errors: ENOENT (no such process, or it has exited), EACCES (refused),
EPROTO (a line this library cannot read), EINVAL (NULL out).
struct peios_psb psb;
if
;
6.1.3 See also #
<peios/token.h>— Token identity is separate from the caller's PSB-derived PIP. Process targeting can require both identity-based rights and PIP dominance.- Process mitigations — the operator-side account of each mitigation and what it defends against.
7.1 The Registry (LCS)
Peios / Developing for Peios / SDK Reference / registry.h — the Registry
<peios/registry.h> is the client surface of LCS — the Layered
Configuration Subsystem, Peios's kernel-mediated registry. LCS is modeled on
the Windows registry: a hierarchy of keys (each with an immutable GUID
identity and secured by its own KACS security descriptor) holding typed
values. Its distinguishing feature is layers: every write is tagged
with a precedence-ordered layer, and the effective view of a value resolves
to the highest-precedence entry. That is what lets a base configuration, a
site overlay, and a machine-local override coexist on one key and resolve
deterministically.
This header is the registry client: open keys, read and write values,
enumerate, watch, secure, back up, and run transactions. It does not cover
the registry source (the storage backend) side — REG_SRC_REGISTER and the
RSI framed protocol — which is a separate library,
librsi. A client speaks only the
syscalls and ioctls here.
Handles are fds. Three calls create file descriptors —
peios_reg_open_key, peios_reg_create_key, and
peios_reg_begin_transaction; everything else is an operation on a key fd or
transaction fd, gated on the access right granted when the key was opened. The
wire constants — value types (REG_SZ … REG_QWORD), key access rights
(KEY_*), open/create flags, transaction states (REG_TXN_*), watch filters
(REG_NOTIFY_*), and security-info bits — come from <pkm/lcs.h>.
7.1.1 See also #
<peios/security.h>— building and parsing the SDs that secure keys.- Library conventions — the base error and buffer rules the descriptor reads specialize.
- The registry — the operator-side model of layers, hives, and precedence.
7.2 The Buffer Convention Here
Peios / Developing for Peios / SDK Reference / registry.h — the Registry
Most of libpeios returns variable-length data with an ssize_t and the
two-call protocol. The
registry's reads use the same idea but express it through descriptor
structs rather than a return value, because a single read often fills more
than one buffer (a value's data and its layer name, say). The pattern:
- Each read takes a descriptor struct with
*_capfields (in) and*_lenfields (out), plus buffer pointers. - On success it returns
0and writes the actual length into each*_len. - If a buffer is too small it returns
-1witherrno == ERANGEand writes the required length into the matching*_len— so a zero-capacity buffer probes the size. - A
NULLbuffer is valid only with zero capacity;NULLwith a nonzero capacity isEINVAL. - For a read with two buffers,
ERANGEis returned if either is too small, and both required lengths are reported, so one probe sizes everything.
Everything else follows the usual Linux convention: 0 / -1 + errno.
7.3 Opening and Creating Keys
Peios / Developing for Peios / SDK Reference / registry.h — the Registry
int ;
int ;
Both resolve path (NUL-terminated) against parent_fd — a key fd for a
relative path, or < 0 for an absolute path — and return a key fd whose
granted access mask is fixed for its lifetime (like a file fd, so it can be
delegated). desired_access is the requested KEY_* rights, checked against
the key's SD.
peios_reg_open_keyopens an existing key.flagscan beREG_OPEN_LINKto open a symlink key itself rather than following it. Errors:ENOENT,EACCES,EINVAL,ELOOP,ENAMETOOLONG,ETIMEDOUT,EIO,ENOMEM.peios_reg_create_keyopens an existing key or creates a new one.flagscan combineREG_OPTION_VOLATILE(a key that does not survive reboot) andREG_OPTION_CREATE_LINK(create a symlink key).layernames the target layer to create in (NUL-terminated), orNULLfor the base layer.txn_fdenlists the create in a transaction, or-1to auto-commit.disposition_out, if non-NULL, receivesREG_CREATED_NEWorREG_OPENED_EXISTING. Errors addENOSPCandEPERM(privileged symlink creation) to the set above.
7.4 Values
Peios / Developing for Peios / SDK Reference / registry.h — the Registry
A value is named (length-counted; an empty name is the key's default
value), typed (REG_*), and written into a layer. A base-layer target
is layer == NULL with layer_len == 0; a non-NULL pointer with a zero
length is rejected EINVAL.
7.4.1 Reading a value #
;
int ;
peios_reg_query_value reads the effective value name on key_fd — the
winner of the layer precedence resolution. name_len == 0 reads the default
value; txn_fd reads within a transaction, or -1 for none. It fills
v->data with the value bytes and v->layer with the name of the layer that
won, and reports the resolved type and sequence. Pass a NULL layer
buffer if you don't care which layer won. Errors: ENOENT (no effective
value, or a tombstone masks it), ERANGE, EACCES, EINVAL.
7.4.2 Writing, deleting, tombstoning #
int ;
int ;
int ;
peios_reg_set_valuewrites valuenameoftypeinto a specificlayer(NULL/0= base).typecan beREG_TOMBSTONEto place a per-value tombstone that masks lower layers.expected_seqis a compare-and-swap guard:0disables it; otherwise the write applies only if the value's current sequence matches, elseEAGAIN. This is how you do lost-update-safe read-modify-write — read thesequencefrompeios_reg_query_value, then set withexpected_seqset to it. Errors:EINVAL,EAGAIN,ENOSPC,ENAMETOOLONG,EPERM,EACCES.peios_reg_delete_valueremoves a layer's entry forname(NULL/0= base). It is idempotent, and removing a layer's entry lets any lower-layer value re-emerge — deletion is per-layer, not global.peios_reg_blanket_tombstonesets (set != 0) or clears (set == 0) a blanket tombstone on a layer, masking all lower-precedence values of this key on that layer at once — the wholesale version of a per-value tombstone.setmust be0or1(elseEINVAL).
7.4.3 Enumerating values #
int ;
;
int ;
Two ways to read every effective value of a key:
peios_reg_query_values_batchreads them all into onebufin a single call — the efficient path. Each record is packed little-endian, back to back:[name_len: u32][name][type: u32][data_len: u32][data], forcountrecords.len_outreceives the bytes written (or the required size onERANGE);count_outreceives the record count. Both can beNULL.peios_reg_enum_valuereads one value at a time byindex, dense over the key's tombstone-resolved values — walk from0untilENOENT. Use it when you want to process values incrementally rather than buffer them all.
7.5 Subkeys, Metadata, and Watches
Peios / Developing for Peios / SDK Reference / registry.h — the Registry
7.5.1 Enumerating subkeys #
;
int ;
peios_reg_enum_subkey reads the child key at index, dense over visible
children — walk from 0 until ENOENT. There is no per-child access
check during enumeration (you see the names and counts; opening a child
still checks its SD).
7.5.2 Key metadata #
;
int ;
peios_reg_query_key_info reads the key's leaf name and its metadata (needs
READ_CONTROL). Note the ordering wrinkle: the kernel reports the metadata
only once the name fits, so a too-small (or zero-capacity) name buffer
returns ERANGE with the required name_len and no metadata — size the
name buffer from that, then call again to get everything. The max_* fields
are sizing hints for enumerations; hive_generation is a per-hive change
epoch you can watch to detect that anything under the hive changed.
7.5.3 Deleting and hiding keys #
int ;
int ;
Both need DELETE access, take a layer (NULL/0 = base) and an optional
txn_fd, and cannot target a hive root (EINVAL).
peios_reg_delete_keyremoves this key's path entry in a layer; lower-layer entries re-emerge. It fails withENOTEMPTYif the key has visible children.peios_reg_hide_keycreates aHIDDENpath entry that masks the key in a layer; removing that layer makes the key reappear. This is the key-level analogue of a tombstone — hide rather than destroy.
7.5.4 Watching for changes #
int ;
int ;
peios_reg_notifyarms change watches onkey_fd(needsKEY_NOTIFY).filteris a mask ofREG_NOTIFY_VALUE/REG_NOTIFY_SUBKEY/REG_NOTIFY_SD(orREG_NOTIFY_ALL);subtree(0/1) extends the watch to descendants.filter == 0disarms. Once armed, the key fd itself becomes pollable —EPOLLINsignals pending events, andread()on the fd returns the change records. So a watch integrates directly into anepollloop with no side channel. Errors:ENOENT(orphaned key),EINVAL,EACCES.peios_reg_flushforces the source to persist this key's hive's pending writes (needsKEY_SET_VALUE) and returns once persistence is confirmed — the durability barrier.
The change records. A read() on an armed key fd returns as many
complete records as fit in your buffer — records are never split across
reads. If the buffer is too small for even the next record the read fails
EINVAL (so size it generously — a few KiB), and a non-blocking fd with
nothing pending fails EAGAIN. Each record is a little-endian, possibly
unaligned byte stream (Peios Kernel TRM §5.6, Watches, with the header offsets
in §5.A):
| Offset | Size | Field | Meaning |
|---|---|---|---|
| 0 | 4 | total_len | Record size in bytes — advance by this to the next record (future versions can append fields). |
| 4 | 2 | event_type | REG_WATCH_VALUE_SET / _VALUE_DELETED / _SUBKEY_CREATED / _SUBKEY_DELETED / _SD_CHANGED / _KEY_DELETED / _OVERFLOW. |
| 6 | 2 | name_len | Byte length of name; 0 for the no-name events (SD_CHANGED, KEY_DELETED, OVERFLOW). |
| 8 | name_len | name | The changed value or subkey name (UTF-8, not NUL-terminated). |
A subtree watch appends two further fields after name: path_depth
(u16) and that many length-prefixed path components (u16 length + UTF-8
bytes), locating the changed key relative to the watched key — depth 0 means
the watched key itself.
Delivery is best-effort with an overflow fallback: if records accumulate
faster than you read them, the oldest are dropped and a REG_WATCH_OVERFLOW
record is queued — on seeing one, re-read the watched key (and subtree) to
recover current state rather than trusting the stream. Records describe
effective (layer-resolved) changes, and uncommitted transactions produce
none — events fire at commit.
7.6 Key Security Descriptors
Peios / Developing for Peios / SDK Reference / registry.h — the Registry
int ;
int ;
Keys are KACS-secured, so their SDs are read and written with the same
<peios/security.h>
vocabulary as files and tokens; security_info selects components
(owner/group/DACL/SACL).
peios_reg_get_securityreads the selected components intosd(KACS binary form), writing the length to*sd_len_out(can beNULL); a too-small buffer returnsERANGEwith the required size there, and a zerocapprobes. Owner/group/DACL needREAD_CONTROL; the SACL needsACCESS_SYSTEM_SECURITY.peios_reg_set_securityapplies the selected components ofsd, merging with the rest (the kernel parses and validates). The DACL needsWRITE_DAC, the ownerWRITE_OWNER, the SACLACCESS_SYSTEM_SECURITY. Heretxn_fdgives atomicity, not layer qualification (SDs are not layered), or-1to apply immediately. SD changes affect only future opens — handles already open keep their fixed grant.
7.7 Backup and Restore
Peios / Developing for Peios / SDK Reference / registry.h — the Registry
int ;
int ;
peios_reg_backupexports the key and its entire subtree tooutput_fd(needsSeBackupPrivilege). It takes a read-only snapshot and performs no per-key access check — the privilege is the gate. Errors:EPERM/EACCES,EBADF(output not writable),ENOENT,ENOTSUP,EBUSY.peios_reg_restorereplaces the key and its entire subtree frominput_fd(needsSeRestorePrivilege), applied in one transaction. Errors:EPERM/EACCES,EBADF(input not readable),EINVAL(malformed stream),EEXIST(GUID collision),EOVERFLOW.
7.8 Transactions
Peios / Developing for Peios / SDK Reference / registry.h — the Registry
A transaction batches key creates and mutating value/key operations into an atomic unit.
int ;
int ;
int ;
int ;
peios_reg_begin_transactionstarts one and returns a transaction fd (initially unbound; it binds to a source on first use), or-1/ENOMEM. Pass this fd as thetxn_fdargument to the create and mutating calls to enlist them. Closing the fd without committing aborts the transaction — so a transaction is abort-by-default, which makes error paths safe.peios_reg_commitatomically applies everything enlisted. On success the fd is terminal — close it. Errors tell you what to do:EINVAL(already committed / never bound),EBUSY(write-lock contention — the transaction stays active, retry the commit),EIO(source failure — stays active),ETIMEDOUT.peios_reg_txn_statusreads a transaction's state:state_outreceives theREG_TXN_*state, andterminal_errno_outreceives the errno that ended it (0while active or after a clean commit). Both can beNULL.
The lifecycle: begin → enlist operations by passing txn_fd → commit
(retry on EBUSY/EIO) → close, or close to abort.
peios_reg_begin_read_transaction instead begins a read-only snapshot. The
first read binds one hive and fixes data and layer selection. Reads and
enumeration accept its fd directly; key opening, metadata, and security reads
use their _transacted forms. Mutations fail EROFS. A capture race returns
EAGAIN; repeat the complete read with a fresh transaction. Closing releases
it. Normal transaction timeouts and read-only source quotas apply.
8.1 Events (KMES)
Peios / Developing for Peios / SDK Reference / event.h — Events
<peios/event.h> is the client surface of KMES — Peios's sole event path.
The kernel stamps every event with trusted metadata (timestamp, per-CPU
sequence, CPU id, identity GUIDs) and writes it into a per-CPU lock-free
ring buffer. There is no other way to emit or observe events: audit records,
subsystem events, and your own application events all flow through the same
rings. Producers emit; consumers attach to the rings and drain them.
Each event payload is a single MessagePack value — build and parse it with
<peios/msgpack.h>.
Two privileges gate the module: emitting requires SeAuditPrivilege, and
consuming (attaching to a ring) requires SeSecurityPrivilege.
8.1.1 See also #
<peios/msgpack.h>— building and parsing the payloads events carry.- Auditing — the operator-side view of the event and audit stream.
8.2 Emitting Events
Peios / Developing for Peios / SDK Reference / event.h — Events
int ;
Emits a single event. event_type is a length-counted UTF-8 event type
such as "org.example.backup.snapshot.created", named as PGSS §6.3 requires —
not NUL-terminated, and its length must be non-zero. payload is
payload_len bytes of MessagePack (one well-formed value). The kernel
validates the payload (one well-formed MessagePack value within the configured
size and nesting limits) and stamps origin_class = userspace. Returns 0,
or -1 with errno:
| errno | Cause |
|---|---|
EPERM | No SeAuditPrivilege. |
EINVAL | Zero-length type, or a malformed payload. |
ENOSPC | Payload exceeds the size caps. |
EAGAIN | Rate-limited. |
EFAULT | Bad pointer. |
Since the kernel's payload check matches
peios_mp_validate, you can validate in
userspace first and turn a would-be EINVAL into a check you control.
/* Build a payload, then emit. */
peios_mp_writer *w = ;
; /* {outcome: {success: true}} */
;
;
; ;
static const char type = "org.example.backup.snapshot.created";
const void *buf; ssize_t n = ;
if
;
;
8.2.1 The emission policy #
typedef struct peios_event_policy peios_event_policy;
peios_event_policy *;
void ;
int ;
An emitter must not write an event whose type the emission policy has switched
off (PGSS §6.9), and should find that
out before it builds the payload. peios_event_policy_enabled answers it: 1
means build and emit, 0 means build nothing. tier is the tier the type
declares in its fragment. An essential type is always 1, without reading
anything.
peios_event_emit does not check the policy itself. By the time it is called
the payload is built, and skipping that work is the point of asking.
The handle caches each type's answer and watches Machine\Generic\Events, so
a change an administrator commits applies to your next decision. If that key
does not exist yet, it watches for its creation; if nothing can be watched, it
reads the policy again at least once a second. If the registry cannot be read
at all, the answer is the tier's default: on for standard, off for verbose
and debug.
peios_event_policy_open fails only with ENOMEM; it does not need the
registry to be there. peios_event_policy_enabled returns -1 with EINVAL
only for caller error: a NULL handle or type, a malformed type (empty, not
UTF-8, an empty segment, or a \, / or NUL in a segment), or an unknown
tier. Registry failures never make it fail.
Use a handle from one thread at a time, and don't use it across fork(): the
child shares the parent's watch descriptor and would take the parent's
notifications. A child opens its own handle.
8.2.2 Batch emit #
;
int ;
peios_event_emit_batch emits several events in one call, amortising the
per-call overhead — a single timestamp capture, identity capture, and
consumer wake cover the whole batch. count is in [1, KMES_BATCH_MAX_ENTRIES]. It returns 0 if all count were emitted, or -1
with the errno of the first entry that failed, with *emitted_out (if
non-NULL) set to how many entries preceded the failure — so you know exactly
where to resume. Rate-limiting is all-or-nothing here: an EAGAIN emits
none of the batch.
8.3 Consuming Events
Peios / Developing for Peios / SDK Reference / event.h — Events
A consumed event is described by struct peios_event. The kernel-stamped
header is copied to you by value; the two variable parts point into the ring
mapping.
;
The trusted metadata is the point of KMES: the timestamp, the identity GUIDs
(the effective and true tokens, and the process), and the origin_class are
stamped by the kernel and cannot be forged by the emitter. sequence is
per-CPU, per-boot monotonic — a gap in it means events were lost
(overwritten before you drained them).
Lifetime: The high-level reader in libpeios 0.5.12 and later keeps a private event snapshot until the next read or close. Low-level
peios_event_ring_event_atpointers still borrow the ring mapping; callers must copy their data and reject slots overwritten during the copy before interpreting that data.
8.3.1 Attaching to a ring #
int ;
The low-level primitive: attach to CPU cpu_id's ring buffer, returning a fd
and writing the data-region capacity to *capacity_out. Discover the CPU
count by counting up from 0 until peios_event_attach returns -1 with
errno == EINVAL. Requires SeSecurityPrivilege (EPERM otherwise). You
then mmap the fd through peios_event_ring_map. Most
callers should use the high-level reader instead, which does the attach and
mmap for you.
8.3.2 The high-level reader #
typedef struct peios_event_reader peios_event_reader;
peios_event_reader *;
void ;
int ;
int ;
uint64_t ;
The reader owns the attach + mmap and hides the whole lock-free drain — memory
barriers, lapping recovery, sequence-gap (lost-event) accounting, buffer
resize/generation handling, and the futex wait. You loop next/wait.
peios_event_reader_openattaches tocpu_idand maps its ring, ready to drain (NULLwitherrnoon failure).peios_event_reader_closetears it down.peios_event_reader_nextfetches the next event intoout(non-NULL). Returns1(event filled),0(none available right now — considerwait), or-1witherrno. Theoutpointers are valid only until the next call.peios_event_reader_waitblocks until events are available ortimeout_mselapses (negative = forever). Returns1(callnext),0(timeout/interrupted), or-1.peios_event_reader_lostreturns the cumulative count of lost events (from sequence gaps) — poll it to monitor whether you're draining fast enough.
The canonical consume loop, per CPU:
peios_event_reader *r = ;
for
;
To consume the whole machine, run one reader per CPU (discover the count as above), each typically on its own thread.
8.3.3 The low-level ring #
For callers that want to drive the drain themselves — integrating the rings into a custom event loop, say — the ring API exposes the mapping directly. The accessors apply the correct memory barriers; you own the read position and the empty/lapping/generation checks.
; /* opaque */
int ;
void ;
uint64_t ;
uint64_t ; /* acquire */
uint64_t ; /* acquire */
uint64_t ;
void ;
ssize_t ;
int ;
peios_event_ring_mapmaps and validates a ring fd frompeios_event_attach;ringmust be zeroed or previously unmapped (remapping an active ring failsEBUSY).peios_event_ring_unmapreleases it.- Positions are free-running byte counters.
write_posis where the producer will write next (acquire-loaded);tail_posis the oldest still-live byte (advances as the ring laps); an event lives at(read_pos & (capacity - 1)). You drain by walkingread_posfromtail_postowardwrite_pos.generationchanges when the buffer is resized — re-readcapacitywhen it does. peios_event_ring_event_atparses the event atread_posintooutand returns its byte size (advanceread_posby that), or-1if the slot is corrupt. You must have confirmedread_posis in[tail_pos, write_pos)first. Passout == NULLto validate a slot and get its size without borrowing theevent_type/payloadpointers.- Before sleeping, arm the advisory wake flag with
peios_event_ring_set_need_wake(ring, 1), thenpeios_event_ring_waitfutex-waits until events pastread_poscan be available ortimeout_mselapses (negative = forever):1(drain now),0(timeout/interrupted),-1.
The low-level loop mirrors the high-level one but with the position bookkeeping in your hands:
uint64_t rp = ;
for
Reach for this only when the high-level reader's loop doesn't fit your event
model; for almost everything, peios_event_reader_* is the right tool.
9.1 MessagePack Codec
Peios / Developing for Peios / SDK Reference / msgpack.h — Encoding
<peios/msgpack.h> is a small, self-contained
MessagePack codec. It exists because KMES event
payloads are MessagePack: the kernel only structurally validates a payload
on emit — it does not build or interpret it — so userspace owns the encode and
decode. This codec is that path, and its validator's acceptance is
deliberately matched to the kernel's emit-time check, so a payload this
codec produces and validates is guaranteed to be accepted by
peios_event_emit.
You can use it as a general MessagePack codec, but its reason for being is events.
It has three parts: a heap-backed writer, a stack-allocatable reader, and a validator.
9.1.1 See also #
<peios/event.h>— the KMES events these payloads travel in.- Library conventions — the sticky-error builder model the writer follows.
9.2 Conventions
Peios / Developing for Peios / SDK Reference / msgpack.h — Encoding
A few rules hold across the codec:
- Integers are written in their smallest MessagePack form automatically —
you write an
int64/uint64and the encoder picks the compact encoding. strvalues must be valid UTF-8. Usebinfor arbitrary bytes. The reader enforces this onstrreads too.- A valid payload is exactly one top-level value, and an empty buffer is not valid. (A map or array at the top counts as that one value.)
- The writer is sticky-error, exactly like the
<peios/security.h>builders: the write calls cannot fail individually; the first error latches and surfaces atpeios_mp_writer_bytes/peios_mp_writer_error.
9.3 Writer
Peios / Developing for Peios / SDK Reference / msgpack.h — Encoding
typedef struct peios_mp_writer peios_mp_writer;
peios_mp_writer *;
void ;
void ;
Create a writer, append values, take the bytes, free it (or reset to reuse).
All the append calls return void — errors latch.
9.3.1 Scalars #
void ;
void ;
void ;
void ;
void ;
void ; /* UTF-8 */
void ;
Use peios_mp_write_int for signed and peios_mp_write_uint for unsigned
values; both are stored in the smallest form. peios_mp_write_str takes UTF-8
with an explicit length (no NUL needed); peios_mp_write_bin takes arbitrary
bytes.
9.3.2 Containers #
void ;
void ;
Write the header, then exactly the promised number of values. A map of
count needs 2 * count values — count key/value pairs — written key,
value, key, value…. An under- or over-filled container is not caught at the
write call; it surfaces at peios_mp_writer_bytes, when the whole structure
is validated.
/* {"user": "alice", "ok": true} */
;
; ;
; ;
9.3.3 Extensions and raw bytes #
void ;
void ;
peios_mp_write_extwrites a MessagePack extension value with a signed type id.peios_mp_write_rawappends pre-encoded MessagePack bytes verbatim — the escape hatch for splicing in a value you already have encoded. The result is still structurally validated as a whole atpeios_mp_writer_bytes, so you can't smuggle malformed bytes through it.
9.3.4 Taking the bytes #
ssize_t ;
int ;
peios_mp_writer_bytes confirms the buffer is exactly one well-formed
top-level value, then borrows it: it writes a pointer to the encoded bytes
through out (valid until the next mutating call on w) and returns the
length. Pass out == NULL to validate and get the length without borrowing.
It returns -1 with errno — EINVAL on a latched error or a
malformed/under-filled structure, ENOMEM on a prior allocation failure.
peios_mp_writer_error returns the latched errno directly, or 0.
Because this call validates, a successful peios_mp_writer_bytes is your
guarantee the bytes are emit-ready.
9.4 Reader
Peios / Developing for Peios / SDK Reference / msgpack.h — Encoding
The reader is a cursor over a borrowed buffer — stack-allocatable, no heap, no free. It decodes one value at a time, advancing the cursor.
; /* opaque — do not inspect */
void ;
size_t ;
Declare a struct peios_mp_reader locally and peios_mp_reader_init it over
your buffer before use. buf can be NULL only when len is zero. Borrowed
str/bin/ext pointers the reader hands back point into the original
buffer and are valid for as long as it lives. peios_mp_reader_remaining
reports the unconsumed byte count.
9.4.1 Peeking #
;
int ;
peios_mp_peek returns the peios_mp_type of the next value without
consuming it, or -1 at end-of-input or on an invalid lead byte. Note that
integers of every width and sign report as PEIOS_MP_INT — read them with
peios_mp_read_int or peios_mp_read_uint as you prefer. Peek is how you
drive a dispatch over a value whose type you don't know ahead of time.
9.4.2 Reading scalars #
int ;
int ;
int ;
int ;
int ;
Each consumes one value on success (returns 0) and leaves the cursor
untouched on a type mismatch or truncation (-1 with errno == EINVAL) —
so a failed read is safe to follow with a different-typed read or a peek.
The out pointer is optional: pass NULL to consume/type-check a value
without receiving its payload.
9.4.3 Reading strings, bytes, containers, extensions #
ssize_t ;
ssize_t ;
ssize_t ;
ssize_t ;
ssize_t ;
int ;
peios_mp_read_str/peios_mp_read_binborrow the bytes (a pointer into the reader's buffer throughout) and return the length, or-1. Strings are not NUL-terminated — use the length — andpeios_mp_read_strrejects invalid UTF-8.peios_mp_read_arrayreturns the element count;peios_mp_read_mapreturns the key/value pair count (so read2 * countvalues). After the header you read that many values yourself.peios_mp_read_extborrows an extension value's bytes, reporting its signed type id throughtype_out(bothtype_outandoutare independently optional), and returns the data length.peios_mp_skipconsumes exactly one complete value, descending into nested containers — the way to ignore a value (or a whole subtree) you don't care about.0/-1.
struct peios_mp_reader r;
;
ssize_t pairs = ; /* top-level map */
for
9.5 Validator
Peios / Developing for Peios / SDK Reference / msgpack.h — Encoding
int ;
peios_mp_validate confirms buf/len is exactly one well-formed
MessagePack value: UTF-8 strings, nesting bounded by max_depth, no
trailing bytes, non-empty. Returns 0 if valid, -1 with errno == EINVAL
otherwise.
Crucially, its acceptance matches the kernel's emit-time check, so a 0
return means the event emit calls
will accept the payload — at this depth bound. Pass
KMES_CONFIG_MAX_NESTING_DEPTH_DEFAULT (32) for the default emit limit; the
top-level value is depth 1. Validate before emitting when a payload comes from
an untrusted or dynamic source, so you turn a would-be EINVAL from the
kernel into a check you control.
10.1 Becoming a Source
Peios / Developing for Peios / SDK Reference / rsi/source.h — Becoming a Source
<rsi/source.h> is where a registry source begins. A source is a storage
backend for the LCS registry — the provider
counterpart to libpeios's registry client. Where a client opens keys and
reads values, a source is what actually holds those keys and values and
answers the kernel's requests for them.
This header has one job: registration. You declare which hives your
process backs, register with the kernel, and get back a source fd. From
that point on you serve the RSI (Registry Source Interface) protocol on that
fd — reading
requests and writing
responses.
Registration requires SeTcbPrivilege. The RSI wire constants
(RSI_HIVE_PRIVATE, RSI_*) come from <pkm/lcs.h>.
This is part of librsi, a separate library from libpeios — link -lrsi
and include <rsi.h> (or the individual <rsi/*.h>). It follows the same
library conventions: raw fds,
int returning 0/-1+errno, and the errno passed straight through from the
kernel.
10.1.1 See also #
- Registry sources overview — what a source is and how the RSI protocol flows.
- The registry — the operator-side model of hives, layers, and sources.
10.2 Describing a Hive
Peios / Developing for Peios / SDK Reference / rsi/source.h — Becoming a Source
A hive is a subtree of the registry with its own root key. A source
declares one struct rsi_hive per hive it backs:
;
| Field | Meaning |
|---|---|
name / name_len | The hive's name, length-counted (not NUL-terminated). |
flags | RSI_HIVE_PRIVATE for a private (scoped) hive, or 0 for a global one. |
root_guid | The GUID of the hive's root key — the anchor every path in the hive resolves from. |
scope_guid | For a private hive, the scope GUID that bounds who can resolve it; zero for a global hive. |
A global hive is visible system-wide; a private hive is scoped by
scope_guid and resolvable only by tokens holding that scope (see the token
LCS
credentials).
Set RSI_HIVE_PRIVATE and a non-zero scope_guid together for a private
hive; leave both clear for a global one.
10.3 Registering
Peios / Developing for Peios / SDK Reference / rsi/source.h — Becoming a Source
int ;
Opens /dev/pkm_registry and registers all count hives in one call,
returning the source fd — the descriptor you then read(2) requests and
write(2) responses on — or -1 with errno.
| Argument | Meaning |
|---|---|
hives / count | The hives this source serves. count must be >= 1; the kernel enforces its configured MaxHivesPerSource limit. |
max_sequence | The highest sequence number this source has already persisted. The kernel resumes its global sequence counter past this value, so a source that has durable state from a previous run must report it here to avoid reusing sequence numbers. A fresh source with no persisted state passes 0. |
Errors include EPERM (no SeTcbPrivilege), EINVAL, ENOSPC (over the
hive limit), ENOMEM, EFAULT, and any error from the underlying
/dev/pkm_registry open(2).
struct rsi_hive hive = ;
int src = ;
if
/* `src` is now the source fd — serve the RSI protocol on it. */
The max_sequence parameter is the one piece of state a durable source must
get right: on restart, scan your persisted data for the highest sequence you
ever wrote and pass it, so the kernel never hands out a sequence number you've
already used.
10.4 What Comes Next
Peios / Developing for Peios / SDK Reference / rsi/source.h — Becoming a Source
Registration is the whole of this header. Once you hold the source fd, the serve loop lives in the other two:
<rsi/request.h>— read and decode the requests the kernel sends.<rsi/response.h>— build and send the replies.
The serving requests guide ties them together into a working serve loop.
11.1 Decoding Requests
Peios / Developing for Peios / SDK Reference / rsi/request.h — Decoding Requests
<rsi/request.h> is the receiving half of a registry source's serve loop. The
kernel sends your source RSI requests —
"look up this child", "store this value", "begin this transaction" — as framed
messages on the source fd. This header reads one frame, splits its header from
its payload, and decodes the payload into a flat, typed struct you can act on.
The shape of the loop is always: read a frame → parse the header → dispatch on the op-code → decode the payload with the matching parser. The decoders are thin wrappers over the kernel's own RSI parsers, so your wire handling is guaranteed compatible with what the kernel sent.
Borrowing: every decoded name/data field is a
(ptr, len)pair that borrows into your frame buffer. The pointers are valid only until you reuse that buffer for the nextrsi_read_request. Copy out anything you need to keep across iterations. This is the same borrow discipline as libpeios's views.
Op-code and field constants (RSI_LOOKUP, RSI_WRITE_KEY_FIELD_*,
RSI_TXN_*) come from <pkm/lcs.h>.
11.1.1 See also #
<rsi/response.h>— building the reply each op expects.- Serving requests — the read/parse/dispatch/respond loop in full.
11.2 Reading and Parsing a Frame
Peios / Developing for Peios / SDK Reference / rsi/request.h — Decoding Requests
;
ssize_t ;
int ;
rsi_read_requestreads one framed request from the source fd intobuf— a thinread(2)wrapper that blocks until a request is queued, then returns the frame length (pass it torsi_parse_request). It returns0at EOF (the source is closing — leave the loop) or-1witherrno, notablyEMSGSIZEifcapis smaller than the pending frame (sizebufgenerously, or grow and retry).rsi_parse_requestsplits a frame into its header and payload view, fillingoutwith therequest_id(which you must echo in the response), thetxn_id(0when the request is not inside a transaction), theop_codeto dispatch on, and a borrowedpayloadpointer. Returns0, or-1witherrno(EINVALon NULL args,EBADMSGon a malformed frame).
11.3 The Decoders
Peios / Developing for Peios / SDK Reference / rsi/request.h — Decoding Requests
Each decoder takes the parsed req and fills a flat struct: GUIDs by value,
names, and data as borrowed (ptr, len) pairs. All return 0, or -1 with
errno — EINVAL if the arguments are NULL or the decoder doesn't match
req->op_code (so calling the wrong decoder for an op is a clean error), and
EBADMSG on a malformed payload. You dispatch on req.op_code and call
the matching one.
11.3.1 Path and entry operations #
These operate on the name→GUID bindings that make up the key hierarchy. A child is named under a parent GUID, and entries live in layers.
/* LOOKUP — is child_name visible under parent_guid? */
;
int ;
/* CREATE_ENTRY — bind child_name → child_guid in layer_name. */
;
int ;
/* HIDE_ENTRY — tombstone child_name in layer_name. */
;
int ;
/* DELETE_ENTRY — remove child_name's entry in layer_name. */
;
int ;
/* ENUM_CHILDREN — list the children of parent_guid. */
;
int ;
| Op | You must | Reply with |
|---|---|---|
LOOKUP | Resolve child_name under parent_guid across your layers. | rsi_respond_lookup |
CREATE_ENTRY | Bind child_name → child_guid in layer_name at sequence. | status |
HIDE_ENTRY | Place a tombstone for child_name in layer_name. | status |
DELETE_ENTRY | Remove child_name's entry in layer_name. | status |
ENUM_CHILDREN | List every child of parent_guid. | rsi_respond_enum_children |
11.3.2 Key operations #
These operate on key metadata records — the non-layered facts about a key (its name, parent, security descriptor, flags).
/* CREATE_KEY — create the metadata record guid under parent_guid. */
;
int ;
/* READ_KEY / DROP_KEY — a request carrying just a key GUID. */
;
int ;
int ;
/* WRITE_KEY — update the mutable fields of guid named by field_mask. */
;
int ;
| Op | You must | Reply with |
|---|---|---|
CREATE_KEY | Store the metadata record for guid (its name, parent, sd, and the volatile_key/symlink flags). | status |
READ_KEY | Return the metadata of guid. | rsi_respond_read_key |
DROP_KEY | Delete the metadata record for guid. | status |
WRITE_KEY | Update only the fields selected in field_mask — the SD when RSI_WRITE_KEY_FIELD_SD is set, the last_write_time when its bit is set — leaving the rest untouched. | status |
WRITE_KEY's field_mask is the important detail: sd is NULL unless the
SD bit is set, and last_write_time is meaningful only when the time bit is
set, so consult the mask before reading either.
11.3.3 Value operations #
These operate on the typed values stored on a key, each written into a layer.
/* QUERY_VALUES — read value_name (or all values when query_all) of guid. */
;
int ;
/* SET_VALUE — store value_name in layer_name with the given type/data. */
;
int ;
/* DELETE_VALUE_ENTRY — remove value_name's entry in layer_name. */
;
int ;
/* SET_BLANKET_TOMBSTONE — set or clear a blanket tombstone on layer_name. */
;
int ;
| Op | You must | Reply with |
|---|---|---|
QUERY_VALUES | Return value_name — or every value when query_all is 1 (then value_name is ignored) — plus any blanket tombstones. | rsi_respond_query_values |
SET_VALUE | Store value_name of value_type in layer_name. Honor expected_sequence as a compare-and-swap guard (0 disables it) — reject with a non-OK status if the current sequence differs. | status |
DELETE_VALUE_ENTRY | Remove value_name's entry in layer_name. | status |
SET_BLANKET_TOMBSTONE | Set (set == 1) or clear a blanket tombstone on layer_name, masking all lower values at once. | status |
11.3.4 Transaction operations #
The kernel drives transaction boundaries; your source honors them so a group of writes commits or aborts atomically.
/* BEGIN_TRANSACTION — open transaction_id in mode. */
;
int ;
/* COMMIT_TRANSACTION / ABORT_TRANSACTION — a request carrying just a transaction id. */
;
int ;
int ;
| Op | You must | Reply with |
|---|---|---|
BEGIN_TRANSACTION | Open transaction_id in mode (RSI_TXN_READ_WRITE or RSI_TXN_READ_ONLY); buffer subsequent writes tagged with this id. | status |
COMMIT_TRANSACTION | Atomically apply everything buffered under transaction_id. | status |
ABORT_TRANSACTION | Discard everything buffered under transaction_id. | status |
Requests that belong to a transaction carry its id in req.txn_id; a txn_id
of 0 means the request is outside any transaction.
11.3.5 Layer operations #
/* DELETE_LAYER / FLUSH — a request carrying just a length-prefixed name. */
;
int ;
int ;
| Op | You must | Reply with |
|---|---|---|
DELETE_LAYER | Remove the entire named layer, reporting the GUIDs of any keys it orphaned. | rsi_respond_delete_layer |
FLUSH | Durably persist pending writes for the named hive, replying only once persistence is confirmed. | status |
12.1 Building Responses
Peios / Developing for Peios / SDK Reference / rsi/response.h — Building Responses
<rsi/response.h> is the sending half of a source's serve loop. After you
handle a request, you reply on the source fd with a framed response. This
header builds those frames for you: you pass the result as flat arrays, and
librsi validates and heap-encodes the wire frame — you never hand-pack a byte.
Every response echoes the request's id and its op-code (OR'd with the response
bit) and carries an RSI_* status. Most operations are status-only; five
carry a payload on success. Any operation can report a non-OK status with
the status-only helper.
For the wire, a response is a 14-byte header (echoed request id, op-code |
RSI_RESPONSE_BIT) plus a 4-byte RSI_* status, followed by an op-specific
payload for payload-bearing successes; multi-byte integers are little-endian
and names/data are length-prefixed. You don't assemble any of that — the
helpers do. Status and target-type constants (RSI_OK,
RSI_PATH_TARGET_GUID, …) come from <pkm/lcs.h>.
12.1.1 See also #
<rsi/request.h>— decoding the request each of these replies to.- Building responses — choosing and filling the right responder.
12.2 Status Codes
Peios / Developing for Peios / SDK Reference / rsi/response.h — Building Responses
Every response carries exactly one of these statuses. The kernel translates a non-OK status into the errno the registry client sees, so send the code that matches what actually happened:
| Code | When to send it |
|---|---|
RSI_OK | The operation succeeded. Status-only ops report it through rsi_respond_status; the five payload-bearing ops must use their own helper. |
RSI_NOT_FOUND | The requested key, entry, value, or layer does not exist in your store (client sees ENOENT). |
RSI_ALREADY_EXISTS | A create collided with something that already exists (client sees EEXIST). |
RSI_STORAGE_ERROR | Your backing store failed — I/O error, corruption, anything the client can't fix (client sees EIO). |
RSI_NOT_EMPTY | The operation needs the key to have no children, and it has some (client sees ENOTEMPTY). |
RSI_TOO_LARGE | The data exceeds what the source is willing or able to store (client sees ENOSPC). |
RSI_TXN_BUSY | A transaction can't proceed right now — for example write-lock contention; the operation can be retried (client sees EBUSY). |
RSI_INVALID | The request is well-formed RSI but violates the source's rules or refers to something malformed (client sees EINVAL). |
RSI_CAS_FAILED | A sequence-guarded write's expected_sequence did not match the current entry — the compare-and-swap lost (client sees EAGAIN and retries). |
RSI_TXN_NOT_SUPPORTED | Reply to BEGIN_TRANSACTION from a source that does not implement transactions (client sees ENOTSUP). |
12.3 The Response Contract
Peios / Developing for Peios / SDK Reference / rsi/response.h — Building Responses
All rsi_respond_* helpers return 0, or -1 with errno. A set of rules
applies to every helper, and violating one is an EINVAL caller-contract
error:
(ptr, len)pairs: a pointer can beNULLonly when its length/count is zero.- Boolean fields (
volatile_key,symlink, target types) must be exactly0or1. - Hidden path targets (
RSI_PATH_TARGET_HIDDEN) must carry an all-zerotarget_guid. LOOKUP/ENUM_CHILDRENmetadata must exactly cover the GUID path targets referenced — no missing metadata, no duplicates, no unreferenced entries.DELETE_LAYERorphan GUIDs must be nonzero and unique.
Beyond EINVAL, any helper can also fail with ENOMEM (during validation or
frame allocation), EOVERFLOW (validation arithmetic or the assembled frame
too large), EIO (a short write), or the raw write(2) errno. Per-helper
EINVAL additions are noted below.
12.4 Sending a Pre-built Frame
Peios / Developing for Peios / SDK Reference / rsi/response.h — Building Responses
ssize_t ;
Writes one already-built response frame to the source fd — a thin write(2)
wrapper returning the bytes written, or -1 with errno. Most callers never
need this; the rsi_respond_* helpers build and send. It exists for callers
assembling frames by other means.
12.5 Status-only Responses
Peios / Developing for Peios / SDK Reference / rsi/response.h — Building Responses
int ;
The workhorse. Use it for:
- status-only ops on success — pass
status = RSI_OK; and - any op reporting a non-OK status — a
LOOKUPthat found nothing, aSET_VALUEthat failed a compare-and-swap, a permission error: reply with the appropriateRSI_*status here, whatever the op.
It fails with EINVAL on a bad req, an unknown status, or RSI_OK given
for a payload-bearing op (those must use their own helper on success), plus
EIO / the write error.
The rule of thumb: on failure, always rsi_respond_status; on success,
rsi_respond_status unless the op is one of the five below.
12.6 Payload-bearing Responses
Peios / Developing for Peios / SDK Reference / rsi/response.h — Building Responses
Five operations return data on success. Each takes the result as flat arrays and encodes the frame for you.
12.6.1 LOOKUP #
;
;
int ;
Answers a LOOKUP with the resolved path entries for the child — one per
layer that has a view of it, each either a GUID target or a HIDDEN
(tombstone) target — plus the metadata for every key the entries reference.
A RSI_PATH_TARGET_HIDDEN entry must carry an all-zero target_guid; the
metadata must exactly cover the GUID targets. EINVAL if req is not a
LOOKUP, a nonzero count has a NULL array, or an entry has invalid
target/boolean fields, missing/duplicate metadata, or unreferenced metadata.
12.6.2 ENUM_CHILDREN #
;
int ;
Answers an ENUM_CHILDREN with each child — its name and the path
entries that resolve it — plus the metadata for every referenced
key. The same target/boolean/metadata-coverage rules as LOOKUP apply.
EINVAL on the same conditions, scoped to ENUM_CHILDREN.
12.6.3 READ_KEY #
int ;
Answers a READ_KEY with the key's non-layered metadata: its name,
parent_guid, security descriptor (sd), the volatile_key/symlink flags,
and last_write_time. EINVAL if req is not a READ_KEY, parent_guid is
NULL, or a boolean field is invalid.
12.6.4 QUERY_VALUES #
;
;
int ;
Answers a QUERY_VALUES with the value entries — each value's name, the
layer it lives in, its type, data, and sequence — plus the blankets (the
blanket tombstones on this key, each a layer and sequence). The kernel
resolves precedence across the layers you report. EINVAL if req is not a
QUERY_VALUES or a nonzero count has a NULL array.
12.6.5 DELETE_LAYER #
int ;
Answers a DELETE_LAYER with the GUIDs of the keys the deleted layer orphaned — a flat orphaned_count * 16-byte array. The GUIDs must be nonzero and
unique. EINVAL if req is not a DELETE_LAYER or a nonzero count has a
NULL array, a nil GUID, or a duplicate.
12.7 The Five at a Glance
Peios / Developing for Peios / SDK Reference / rsi/response.h — Building Responses
| Success response | Op | Payload |
|---|---|---|
rsi_respond_lookup | LOOKUP | path entries + referenced key metadata |
rsi_respond_enum_children | ENUM_CHILDREN | children (name + path entries) + metadata |
rsi_respond_read_key | READ_KEY | one key's non-layered metadata |
rsi_respond_query_values | QUERY_VALUES | value entries + blanket tombstones |
rsi_respond_delete_layer | DELETE_LAYER | orphaned key GUIDs |
Every other op — and every failure of these — is rsi_respond_status.