Developing for Peios
Build software for Peios: the SDK and platform APIs, desktop apps, packaging and documentation, and testing.
Single-page view · as markdown
The Peios C SDK
Peios / Developing for Peios / SDK Basics
The Peios C software development kit (SDK) provides libraries for programs that use Peios security, registry, and event services. Use libpeios for application services and librsi for a registry storage backend.
Both libraries expose a C application binary interface (ABI). C++ and other languages can call that interface without depending on the libraries' internal Rust implementation.
Choosing a library #
The libraries have separate roles and can be linked into the same program:
| Library | Role | Header | Link option |
|---|---|---|---|
| libpeios | Security, registry clients, and events | <peios.h> | -lpeios |
| librsi | Registry storage backends | <rsi.h> | -lrsi |
The internal peios-cabi crate supplies allocation, error handling, and
system-call helpers. Applications do not link it directly.
The SDK repository releases these components together. The shared objects
retain separate compatibility boundaries: libpeios.so.0 and librsi.so.0.
A package version identifies a release; the shared object's SONAME identifies
its binary interface. An SDK release does not imply a kernel release.
Portable data and kernel services #
Security identifiers, access control lists, security descriptors, and MessagePack values can be built and parsed in userspace. These operations do not need a running Peios kernel.
Opening tokens, accessing registry keys, and sending or receiving kernel events require the corresponding Peios kernel services. Building a program on a development host does not establish that these operations work there.
The SDK pins kernel headers and shared semantic crates when it is built. That source pin identifies the build input. It is not a requirement to run that exact kernel commit, and it does not establish compatibility with every kernel version.
Starting with C #
Begin with installing and linking, then compile a complete program. Read library conventions before managing buffers or file descriptors.
For a registry backend, start with registry sources. The installed headers own the complete function declarations and parameter contracts. The SDK reference explains how to use those contracts.
Installing and Linking
Peios / Developing for Peios / SDK Basics
Link your application to the library whose services it uses. Install the matching development package when compiling, and the runtime package on machines that run the resulting executable.
Before you start #
Prepare these build inputs:
- A C or C++ compiler for the target system.
- The development package for libpeios, librsi, or both.
- The Peios kernel userspace API headers required by those packages.
pkg-configconfigured to find the target system's package metadata.
Choosing packages #
Each library has the same package split. Replace libpeios with librsi
for registry source development:
| Package | Contents | Needed for |
|---|---|---|
dev.peios.libpeios | Versioned shared library | Running dynamically linked programs |
dev.peios.libpeios-devel | Headers, linker symlink, and peios.pc | Compiling programs |
dev.peios.libpeios-static | Static archive | Static linking |
dev.peios.libpeios-debuginfo | Separate debugging information | Debugging library code |
dev.peios.libpeios-debugsource | Source files for debugging | Stepping through library code |
Use headers and libraries from the same SDK package set. Do not combine
headers from an arbitrary kernel checkout with an unrelated library build.
The library headers include <pkm/*.h> definitions; the directory name is
part of the installed include interface.
Linking an application #
Use the complete first.c program from
compiling a first program:
- Include
<peios.h>or the individual<peios/*.h>headers that the application uses. - Obtain the compiler and linker options from the
peiospkg-config module. Put the library options after the source files or object files. - Build the program for the same target as the installed library.
For librsi, use <rsi.h> and the rsi pkg-config module. Applications that
serve registry data and also access other Peios services can link both.
Checking the result #
A successful compile confirms that the headers are available. A successful link confirms that the required symbols are present in the selected library. Run the first-program example to check portable data handling.
Calls that access tokens, registry keys, or kernel events need a Peios kernel with the required services. Test those calls on the target system with the privileges and objects described by their guides.
Static linking #
The static package contains libpeios.a or librsi.a. Select that archive
explicitly when constructing the linker command. Static linking includes
the SDK code in the executable; the application's other dependencies still
follow their own linking rules.
Rebuild statically linked applications when adopting an SDK fix. Updating the shared-library package alone does not replace code in those programs.
Debugging static builds #
The packaged static archives retain linker symbols but omit DWARF debugging information. Each library's debug package describes its shared object; it does not supply the missing SDK internals for a statically linked program.
To debug statically linked SDK code, use the unstripped archive the SDK's build gives, or rebuild the matching source with its recorded compiler and dependency inputs. Keep those inputs with the binary so that debugger source paths and layouts match the executable.
Compiling a First Program
Peios / Developing for Peios / SDK Basics
Parse a security descriptor, read its owner, and print the owner's security identifier (SID). This example runs entirely in userspace and does not open tokens or change system security.
Before you start #
Prepare these inputs:
- A C compiler and
pkg-config. - The libpeios development package and its matching runtime library.
- A writable directory for the source and executable.
Creating the program #
Save this complete program as first.c:
int
The Security Descriptor Definition Language (SDDL) string sets the owner and group to Administrators. Its discretionary access control list (DACL) grants that group full file access. Parsing this string does not grant any access to the process running the example.
Building and running #
-
Compile the source with the package's compiler and linker options:
-
Run the executable:
Checking the result #
The program prints:
security descriptor: 84 bytes
owner: S-1-5-32-544
The owner SID identifies Administrators. The byte count describes the encoded descriptor produced by this example, including its owner, group, and access control list.
Understanding ownership #
The program probes the output size before allocating each variable-sized buffer. The string allocation adds one byte for the terminating NUL.
The parsed view and owner pointer borrow the descriptor allocation. The program frees that allocation after formatting the owner, so every borrowed pointer remains valid throughout its use.
Read library conventions for the result and ownership rules used by the other SDK functions.
Using the SDK from Rust
Peios / Developing for Peios / SDK Basics
Use the peios crate to access Peios through Rust handles and Result
values. The peios-sys crate exposes the underlying unsafe C functions.
Both use the public C application binary interface (ABI).
Before you start #
- Install Rust and Cargo.
- Install matching libpeios headers and libraries, version 0.5.12 or later.
- Install pkg-config and libclang for binding generation.
- Place the
peios-rscheckout beside your application for this example. - Run token operations on a Peios kernel.
Add the dependency #
-
Add a local dependency to your application's
Cargo.toml:[] = { = "../peios-rs/peios" } -
Create
src/main.rs:use ; -
Run
cargo run. The token handle closes when it leaves scope.
Check the result #
The program prints the caller's security identifier (SID). A native-call error on another kernel does not indicate a successful Peios access check.
Generate the API reference with cargo doc -p peios --open from the SDK
checkout. The repository's docs/building.md covers SDK discovery and
host tests.
Linking and types #
Use dynamic linking for ordinary Rust applications. The C static archive
contains its own Rust runtime, which can conflict with a Rust executable's
runtime. The static feature only selects that archive; it does not remove
those conflicts.
The optional uapi feature re-exports kernel types through peios_sys.
Those types come from the recorded kernel snapshot. Import them through
that re-export when sharing values with these bindings: a separately
compiled copy of the same structure has a different Rust type identity.
Names without regard to case #
peios::casefold compares names as the registry compares them: Unicode
Simple Case Folding, pinned to Unicode 16.0, with no normalisation. Windows
matches names the same way, so use it wherever a program must match names
as Windows clients expect, as a file server does. fold folds one
character; eq and cmp compare whole names. Code that must build without
libpeios, such as a protocol engine tested on another system, can depend on
the peios-casefold crate itself, which peios::casefold re-exports.
Identity and event ownership #
A scoped impersonation guard belongs to the thread that creates it. Rust
rejects moving or sharing the guard across threads. Keep identity-dependent
work on that thread, and call revert when you need to check restoration.
Dropping the guard attempts restoration but cannot return an error.
Impersonations do not nest: restoration clears the impersonation rather
than restoring an earlier impersonated identity.
Events own their type names and payloads. You can retain them after the
next read or after closing the reader. A low-level read returns EAGAIN
if its slot is empty, overwritten, or changes generation during copying.
After a generation change, attach and map the ring again.
Event emission checks names, payload lengths, and batch counts before
converting them to the C ABI's fixed-width fields. Values that do not fit
return EINVAL. Socket receive calls also reject an unrepresentable handle
capacity before allocating its buffer or consuming a message.
Access checks and request identity #
Audit Contexts in Rust explains object descriptions and denial results. Token Messages in Rust covers received-handle ownership, truncation, and explicit peer-identity fallback.
Using the SDK from Go
Peios / Developing for Peios / SDK Basics
Use peios-go to read Peios security formats and call native Peios
operations. The module uses Go directly; applications do not need a C
compiler or an installed C SDK library at runtime.
Before you start #
- Install Go 1.26 or later.
- Place the SDK checkout beside your application for this local example.
- Run native operations on a Peios kernel. Portable format parsers also work on other systems.
Add the dependency #
-
Add these entries to your application's
go.mod:require github.com/peios/peios-go v0.0.0 replace github.com/peios/peios-go => ../peios-goThe version is a local placeholder. Before publishing your application, use a published commit or release and remove the local replacement.
-
Create
main.go:package main import ( "fmt" "github.com/peios/peios-go/security" ) func main() -
Run
go run .from your application directory.
Check the result #
The program prints the descriptor size. This example parses Security Descriptor Definition Language (SDDL) without changing a system object. Parsing validates structure; the kernel separately checks your authority when you apply a descriptor.
Use go doc github.com/peios/peios-go/security for the package reference.
The repository's docs/building.md describes SDK development and tests.
Audited access checks #
Audit Contexts in Go uses the
maintained access package and explains how to handle denial separately from
an unsuccessful check.
Audit Contexts in Rust
Peios / Developing for Peios / SDK Basics
An audit context names the object behind an access check. The Rust
AuditContext type owns the encoded description and lends it to an
AccessCheck. The kernel can then include that description in an audit
record when the applicable audit policy calls for one.
The description is the daemon's claim, not independently observed identity. It does not grant access or replace the security descriptor. See The Audit Context for the shared format and Access Decisions for the rules governing audited objects.
Build and use a context #
This helper checks a service object using a supplied caller token, descriptor, access mask, and object-specific generic mapping:
use BorrowedFd;
use ;
use ;
The example names an illustrative service. Replace its name with the actual object being checked, and define asserted object fields in the owning event catalog fragment. Do not label an arbitrary request as another component's object merely because its name is convenient.
A completed check returns an AccessDecision. Inspect allowed: denial is
an ordinary decision, not a Rust Err. An error means the check itself could
not complete. The check evaluates access; your daemon still enforces the
result before performing the operation.
Values and ownership #
Field values convert from &str, u64, u32, i64, i32, bool, &[u8],
and &SidRef. A security identifier (SID) uses its binary representation.
Use the declared field type rather than converting every value to a string.
Leave absent fields out instead of supplying nil or a placeholder value.
The constructor copies the encoding into owned storage. Temporary field
slices need not outlive the returned context. AccessCheck borrows that
context for the check; as_bytes lends the encoded bytes without transferring
ownership.
Invalid kind or key names, repeated keys, and oversized encodings are rejected
with EINVAL. Names are single kebab-case segments, and the encoded context
is limited to 4096 bytes. Other construction failures remain errors to handle.
Accept an existing encoding #
AuditContext::from_bytes takes a Vec<u8>, validates the encoded context,
and adopts it on success. It applies the shared validator's structural rules,
which are broader than the scalar-only constructor. Passing validation does
not prove that fields are cataloged, truthful, or appropriate for this object.
Keep the caller token and descriptor associated with the same request while constructing and checking the context. Neither a successfully encoded context nor a successful audit write is an authorization decision by itself.
Audit Contexts in Go
Peios / Developing for Peios / SDK Basics
The github.com/peios/peios-go/access package provides portable audit-context
encoding and native access checks. Attach the encoded object description to
access.Request so the kernel can identify the object in an audit record.
The context does not grant authority or replace the security descriptor.
The Audit Context defines the common encoding. Access Decisions explains when a daemon supplies it and how its claims are marked.
Encode and check #
This helper checks an illustrative service using an existing token handle and security descriptor. Native checks require a Peios kernel on Linux/amd64.
package example
import (
"syscall"
"github.com/peios/peios-go/access"
"github.com/peios/peios-go/security"
)
func CheckService(
caller syscall.Conn,
descriptor []byte,
desired security.AccessMask,
mapping security.GenericMapping,
) (access.Result, error)
Use the actual service name and its object-specific mapping. Define the
asserted fields in the owning event catalog fragment. A nil Token selects
the calling thread's effective token; it does not mean an anonymous client.
Pass the intended caller explicitly when checking another principal's access.
access.Check returns syscall.EACCES for denial, retaining the granted
subset and audit outputs in its result. Other errors mean the check could not
complete. This differs from the Rust wrapper, which represents denial in
AccessDecision.allowed. Do not ignore a Go error because a result was
returned.
CheckList returns per-node decisions for an object tree. Inspect each node's
Status; a successful call does not mean every node grants the requested
access.
Encode values deliberately #
Each access.Field pairs a name with a value. The encoder accepts strings,
booleans, byte slices, and signed or unsigned integer types. Pass a SID's
Bytes() result for a binary security identifier, not the SID object or its
text form. Floating-point values, nested objects, and nil are not constructor
field values.
Names are single kebab-case segments, repeated keys are rejected, and the
encoded context is limited to 4096 bytes. An empty field list emits only the
object kind. The encoder returns access.ErrAuditContext for invalid context
structure and can also return an encoding error.
The returned byte slice owns its encoding. Keep its contents unchanged until the check completes. Do not reuse it concurrently as a mutable work buffer.
Validate an existing map #
Call access.ValidateAuditContext when another encoder built the bytes.
Its structural validation is broader than the scalar-field constructor; it
is not proof that the values match the catalog or describe the real object.
Both native check variants validate a non-nil Request.AuditContext before
calling the kernel. Nil omits the context; a non-nil empty slice is invalid.
For a daemon-owned object that requires an audit context, omission is not a
substitute for handling an encoding error.
The historical libp-go/sd constructors and CheckRequest examples do not
apply to this API. Use access.AuditContext, access.Field, and
access.Request from the maintained module.
Token Messages in Rust
Peios / Developing for Peios / SDK Basics
The Rust socket helpers send and receive per-message identity with file
descriptors. ReceivedMessage owns each received descriptor, including its
optional token, so rejecting a message can release those resources by dropping
it. The request bytes remain in the caller's receive buffer.
Use Per-Message Identity for the shared interface contract. A conveyed token identifies the authority the sender could convey; it does not authorize every requested operation.
Send one identity with a request #
For a connected socket and an existing user token, the sending call is:
use AsFd;
use socket;
let sent = send_message?;
The caller retains its descriptors. Check the returned byte count according to the transport's framing rules. On a stream, a partial write is not a complete request. Do not blindly replay the whole request and its ancillary data after a partial write.
Receive and reject incomplete requests #
This helper requires an attached identity and rejects truncation. The application chooses an 8-descriptor bound; choose a bound appropriate to your own protocol and validate the number and purpose of descriptors after receipt.
use Error;
use ;
use socket;
use ;
This is an identity/ownership helper, not a stream message decoder. A stream read can contain only part of the application's frame. Reassemble and validate the frame before interpreting its contents. Do not use zero-length data as an identity-only request with this helper.
Returning an error drops descriptors already received. Moving the token or
OwnedFd values out transfers their ownership to the caller; those handles
close when their new owners drop them. Do not close their raw descriptor
numbers separately. Received handles are close-on-exec.
The example requires at least the local impersonation level because its server intends to act for the caller. An identification-only protocol needs its own explicit contract. Checking the level does not enter impersonation or perform an access check.
Choose fallback identity explicitly #
A protocol can instead specify that an absent attached token means the connected peer's primary token. In that case, obtain the peer process handle from the kernel and open the token through it:
use AsFd;
use socket;
use ;
let peer = peer_pidfd?;
let identity = open_process?;
This is the connected peer's primary identity, not necessarily the identity of a client that peer represents. Do not substitute a process number named in the payload. Do not use fallback after truncation, an invalid attached token, or a failed token query; those are failures rather than absence.
Apply the protocol's level and authorization checks to a fallback token too. Opening a primary token does not convert it into an impersonation token or enter impersonation. If acting under it is required, use the token duplication and scoped impersonation interfaces described by the SDK.
A scoped impersonation guard stays on its creating thread. It does not carry identity safely across arbitrary async task migration. Explicitly revert when you need to handle restoration failure; dropping the guard cannot report it.
Access Control Overview
Peios / Developing for Peios / Access Control
KACS — the Kernel Access Control Subsystem — is the heart of Peios's security model, and it is the part of the SDK you are most likely to reach for. This section is a tour: it explains how the pieces fit together and points you at the right guide (and the right reference page) for each task. If you have not yet read the library conventions, read those first — everything here assumes the error and buffer rules they describe.
The four nouns #
Almost everything in KACS is built from four things:
| Noun | What it is | SDK home |
|---|---|---|
| SID | The unique binary name of a principal — a user, group, machine, or well-known system actor. | security.h |
| Security descriptor (SD) | What protects an object: its owner, its group, and the ACLs that grant or deny access. Built from ACEs, each naming a SID and an access mask. | security.h |
| Token | The runtime object that carries an identity — a user SID, groups, privileges, an integrity level, claims. Every access decision is made against a token. A token is a file descriptor. | token.h |
| Access check | The act of deciding whether a token can perform a desired access on an object, given the object's SD. | access.h |
The relationship is simple to state: an access check asks whether a token (the subject) is granted some access to an object protected by a security descriptor, and both the token and the SD are expressed in terms of SIDs.
The shape of a decision #
When you need to make an authorization decision in your own code, the pattern is almost always the same three steps:
- Get the subject's token. Usually the caller's — often through
peios_token_open_peeron a socket, so you learn who connected — or your own effective token (token_fd = -1). - Get the object's security descriptor. You either hold it already, read
it off a file with
peios_file_get_sd, or build one with apeios_sd_builder. - Run the check.
peios_access_checktells you whether the desired rights are granted, and exactly which subset was granted.
The checking access guide walks that end to end.
Advisory versus enforced #
There is one distinction worth internalising early. The SDK's access check is advisory: it computes what the answer would be. It does not enforce anything — enforcement of a real operation (opening a file, adjusting a token) happens inside the kernel against the subject's own process security block.
So you use peios_access_check when your code is the resource manager:
you own some object — a record in your database, a slot in your service — that
isn't a kernel object, and you want to make the grant/deny decision using
Peios identities and the same rules the kernel would apply. For actual kernel
objects (files, tokens, registry keys), you don't pre-check and then act; you
act, and the kernel enforces, returning EACCES if denied.
Identity is not always your identity #
A recurring theme in KACS is acting as someone other than yourself:
- Impersonation lets a service temporarily adopt a caller's identity so its access checks run as them — the way a server does work "on behalf of" a client without running as root and hand-rolling permission logic. See working with tokens.
- Restricted tokens let you drop power — derive a strictly less-privileged token to hand to less-trusted code.
- Integrity levels and confinement bound what a token can touch regardless of its SIDs.
These are what make KACS more than POSIX uid/gid, and the token module is where you reach for them.
Where to go in this section #
- Working with tokens — who am I, who is calling me, and how to act as someone else.
- Checking access — building a security descriptor and making a decision end to end.
- Securing files — the native open and reading/writing file security descriptors.
- Hardening a process — turning on process mitigations.
For the exhaustive per-function detail behind any of these, the reference section documents every symbol.
Working with Tokens
Peios / Developing for Peios / Access Control
A token is the runtime carrier of an identity, and it is a file
descriptor. This guide covers the everyday token tasks;
token.h is the exhaustive
reference for every call and field.
Choosing a token #
To inspect your own identity, open your effective token and query it:
int tok = ;
if
unsigned char sid;
ssize_t n = ; /* the user SID */
uint32_t il;
; /* integrity level RID */
struct peios_privilege_set privs;
; /* held/enabled privileges */
;
peios_token_open_self gives you the effective token — if your thread is
impersonating, that's the impersonated identity. Pass KACS_TOKEN_OPEN_REAL
in the flags to get your process's real primary token regardless. The access
argument is the handle rights you want; KACS_TOKEN_QUERY is enough to read.
Group SIDs and other list-valued classes come back as buffers you parse with
the security.h
views: read
CLASS_GROUPS with peios_token_query, then
peios_sid_array_parse it.
Who is calling me #
The most useful token trick in a service is learning the identity of whoever
connected to your socket. When a client connects over a Unix stream or
seqpacket socket, KACS captures their token at connect() time, and you open
it from the accepted connection:
int conn = ;
int caller = ; /* QUERY | IMPERSONATE rights */
if
/* Now query the caller's identity, or impersonate them (below). */
This is local authentication with no passwords and no handshake — the kernel
vouches for who is on the other end. The handle comes with fixed QUERY | IMPERSONATE | DUPLICATE rights — enough to inspect the caller, act as them,
and (for a process launched on their behalf) turn the identity into a primary
token, but never to adjust it.
It works in the other direction too: right after connect(),
peios_token_open_peer(sock) on the client's socket returns the identity of
whoever is listening (at Identification level — enough to check, not to act
as), so a client can verify it reached the genuine service and not something
else that bound the path.
Acting as the caller #
Once you hold a caller's (impersonation) token, you can impersonate them: adopt their identity on your current thread so every subsequent access check runs as them, not as your service. This is how you do work on a client's behalf without running privileged and re-implementing their permissions.
if
/* ... do the work here: file opens, access checks, etc. all run as the caller ... */
; /* back to your own identity */
;
Always pair peios_token_impersonate with
peios_token_revert,
ideally in the cleanup path, so a failure partway through can't leave your
thread wearing someone else's identity. peios_token_revert is a safe no-op
if you weren't impersonating.
The full flow for a request handler is: accept → peios_token_open_peer →
peios_token_impersonate → serve the request → peios_token_revert →
close. When the handler runs start to finish on one thread and has no other
use for the token, peios_token_impersonate_peer(conn) collapses the open,
impersonate and close into one call.
A client decides how far its identity travels:
peios_socket_set_impersonation_level(sock, KACS_IMLEVEL_IDENTIFICATION) lets
the server learn who it is without being able to act as it. And a client that
writes on behalf of many identities over one connection — a service
impersonating its callers through a connection pool — turns on
peios_socket_set_pass_token(sock, true), after which every send carries
whoever is impersonating at that moment and the server's
peios_token_open_peer tracks it request by request.
Handing an identity to a manager #
Impersonation acts as someone on your thread. The other shape is handing an identity to another process so it can act — the pattern behind the Peinit jobs socket (PSPU §7): a submitter such as backupd holds a token for the user whose data it is backing up, and wants Peinit to run the backup job as that user, not as backupd. Nothing is impersonated; the token itself is attached to the request, and the kernel vouches that the sender could have acted as it.
int jobs = ;
; /* who may submit is who may connect */
const char *req = "{\"command\":\"submit\",\"image_path\":\"/usr/bin/backup\"}";
if
Three things make this safe, and none of them is the manager's to get wrong:
- The kernel gates the attach like an impersonation. You need
TOKEN_IMPERSONATEon the handle, and the token arrives at the sending socket's impersonation level — so a token the sender could only identify, never act as, cannot be smuggled through. Peinit refuses anything below Impersonation. For a job that must reach remote systems as the user, set the socket to Delegation first:peios_socket_set_impersonation_level(jobs, KACS_IMLEVEL_DELEGATION)— and the attach then only succeeds if the token itself is at Delegation, since the level only ratchets down. - The receiver owns what it is handed.
peios_socket_recv_messagegives the manager a token handle withQUERY | IMPERSONATE | DUPLICATE— enough to inspect the identity, check its level withpeios_token_impersonation_level, and duplicate it into a primary token for the new process, but never to adjust it. - No token means the sender's own. A request that attaches nothing is run
as the connecting process's primary token: the manager opens it through
peios_socket_peer_pidfdandpeios_token_open_process— the kernel's handle on the peer, never a PID the peer named — which isfork-like and needs no privilege on the submitter's part.
Descriptors travel the same way: pass a socket for the job to serve on, or a
pipe to receive its output, as SCM_RIGHTS on the same message. The full
protocol — what the manager does with them and how the job is managed
afterward — is PSPU §7; the calls
are in the
reference.
Dropping power #
To run less-trusted code with less authority than you hold, derive a
restricted token and hand it over. peios_token_restrict can delete
privileges, demote groups to deny-only, and add restricting SIDs:
struct peios_token_restrict spec = ;
int weak = ;
The result is a strictly less-powerful token. Combined with integrity levels and confinement (both set when minting a token), this is the basis of sandboxing on Peios.
Minting tokens #
Creating a token from scratch requires SeCreateTokenPrivilege and is the
province of authentication authorities, not ordinary programs. When you do
need it, the token-spec builder is
the ergonomic path — typed setters for the user SID, groups, privileges,
integrity, claims, and the rest, then peios_token_builder_create. Mind the
index
convention for
owner/primary-group references, and don't add the logon SID yourself — the
kernel injects it.
Next #
- Checking access — use a token to make an authorization decision.
token.hreference — every token call in full.- Impersonation — the operator-side model and its two gates.
Keep request identity bound to the work #
Capture is not a promise of usable impersonation. Query the effective granted level after admission: the primary-token identity gate and integrity ceiling can reduce it to Identification even when installation succeeds. A restricted server cannot escape through an unrestricted same-user client. A privilege that satisfies the identity gate does not bypass the integrity ceiling. The kernel admission reference defines the exact result.
Scope impersonation around the complete client operation and revert on every exit path, including errors. Reverting an inner scope does not restore an outer impersonation stack; it returns to the primary identity. Keep service maintenance outside that client scope. Thread-pool reuse and asynchronous migration need explicit handling because impersonation is thread-local.
A pooled connection can carry different senders over time. Connection-level capture alone cannot identify every forwarded request. Enable per-message identity deliberately, and bind the token returned with a receive to that message when consumers can run concurrently. A later peer-token query can observe a later received identity. The transport reference defines stream boundaries, seqpacket behavior, datagram attachment, and unsupported transport cases; ordinary pipes are not peer-token sockets.
A client should verify the server identity returned by peer capture before sending sensitive requests. Possession of a familiar socket path is not a substitute. Delegation level permits further conveyance where an implemented network authentication mechanism supports it; the level alone does not supply remote credentials or implement that mechanism.
SDK token opens use close-on-exec descriptors by default. Distinguish that handle flag from the thread's impersonation state, which exec reverts. Intentionally passing a token handle across exec does not install it as the new program's effective identity.
Checking Access
Peios / Developing for Peios / Access Control
This guide walks a complete access decision: you have an object to protect, a
caller to check, and you want KACS to tell you what they're allowed. The
exhaustive detail lives in
access.h and
security.h; here you
put them together.
When to use this #
Reach for peios_access_check when your
program is the resource manager — you own something that isn't a kernel object
(a document, an API route, a record) and you want to gate it with Peios
identities and rules. For actual kernel objects, don't pre-check; perform the
operation and let the kernel enforce.
Remember the check is advisory: it computes the answer, you enforce it.
When an identity authority supplies facts without an OS token, use the separate supplied-identity check. It preserves unknown versus known-empty groups and filtered versus complete claims. It never adopts the service's own token or creates a user session. Only an explicit granted decision permits admission; missing context requires more facts or refusal. Its initial backend runs inside libpeios and does not need a kernel rebuild. The token-based instructions below remain unchanged.
Step 1 — describe what protects the object #
An object is protected by a security descriptor. If you don't already have one, build it. Say the resource should be readable and writable by its owner and read-only for a "viewers" group:
/* An ACL: allow OWNER full, allow VIEWERS read. */
peios_acl_builder *acl = ;
;
;
size_t acl_len;
const void *acl_bytes = ;
/* Wrap it in a security descriptor with an owner. */
peios_sd_builder *sd = ;
;
;
size_t sd_len;
const void *sd_bytes = ;
(You can also write the descriptor as SDDL text and parse it — often easier when the policy is fixed.)
Step 2 — identify the subject #
The subject is a token. Most often it's the caller you opened from a
socket, or
your own effective token. In the request you pass either a token fd or -1
for your own effective token.
Step 3 — run the check #
Fill in a request and call. desired is what you're testing; mapping folds
any generic rights to the object class's specific bits (use the class's
published mapping — here you'll treat the object like a file):
struct peios_access_request req = ;
uint32_t granted = 0;
int rc = ;
Step 4 — interpret the result #
if else if else
The key idea: a denial is not an error to log and bail on — it's the
expected "no". And because granted is filled even on denial, you can ask for
a broad set of rights in one call and read back exactly which subset the
subject has, rather than probing right by right. Clean up the builders
(peios_acl_builder_free, peios_sd_builder_free) and the token fd when
done.
Intent is not an authorization ticket #
For a resource managed by the application, set backup or restore intent only when that resource operation actually has the corresponding purpose. The subject must still hold the enabled privilege, and the complete pipeline can narrow its contribution. The request's intent does not change the token.
A successful advisory check does not grant rights to a later filesystem open,
write, or descriptor update. Those operations enforce their own contracts.
Do not implement backup as "pre-check with backup intent, then assume any
ordinary open is authorized." Use the kernel object's supported operation
and retain its actual result. Likewise, a prior WRITE_OWNER result does
not eliminate the descriptor-update rules about the new owner SID.
For MAXIMUM_ALLOWED, inspect the returned mask rather than treating success
as a grant of every possible bit. Result-list checks apply object-type-tree
semantics; they are not a collection of unrelated scalar checks. A caller
that cannot reproduce local claims, PIP, mapping, or audit context should
record that gap instead of presenting a rehearsal as the original decision.
Per-property checks #
If your object has properties or property-sets with their own object ACEs,
evaluate the whole tree in one call with
peios_access_check_list:
supply an object-type tree and get one result per node, so you learn (for
instance) that a caller can read most of an object but not one protected field — without a separate check per field.
Auditing a decision #
Pass a non-NULL peios_access_audit to
learn what a SYSTEM_AUDIT ACE match would log, and whether a staged
central access policy would decide differently — the signal you watch when
rolling out a policy change.
If your daemon guards objects of its own, name the object in the request's audit context, so the kernel's audit record of the decision says what was checked:
struct peios_audit_field name = ;
uint8_t ctx;
ssize_t n = ;
req.audit_context = ctx;
req.audit_context_len = n; /* check n >= 0 first */
Do not write an event of your own recording the grant or the refusal. The kernel's record is the audit record, and a SACL on the object decides whether it is written (PGSS §6.7).
Next #
access.hreference — every field of the request and the audit outputs.- Access decisions — the operator-side account of how KACS reaches a verdict (and how to debug a surprising denial).
Securing Files
Peios / Developing for Peios / Access Control
Use libpeios to open a file with explicit access or to read and change its security descriptor. Select the descriptor components needed by the task so that an update preserves unrelated security settings.
Before you start #
Prepare the required authority and inputs:
- A Peios kernel with the Kernel Access Control Subsystem (KACS).
- A process token with the rights needed for the requested operation.
- The libpeios headers and matching library.
- A validated security descriptor for operations that supply one.
Opening a file #
A native file open requests a specific access mask. The resulting handle carries the access granted at open. Choose that mask deliberately before passing the handle to another process.
- Initialize
struct peios_open_paramsto zero. - Set
desired_accessto the file rights the caller needs. - Choose the disposition that matches the operation. Use
KACS_DISPOSITION_CREATEwhen an existing path must be an error, orKACS_DISPOSITION_OPENwhen the file must already exist. - For creation, supply the creator descriptor when required by the
application's security policy. For an existing file, leave
sdasNULLandsd_lenas zero. - Call
peios_file_openand check its return value before using the descriptor or the status output. - Close the returned descriptor when its ownership ends.
If a create-only operation reports EEXIST, decide whether the application
can accept the existing object before opening it separately. A preceding
path-existence check cannot make creation and opening atomic.
Supply a new file's descriptor when you create it, rather than creating the file and then setting its descriptor. Between those two calls the file exists with whatever descriptor it inherited. The handle a creating open returns has the access it asked for, even where the new descriptor would not grant it to the creator, so you can create a file only others can read and still write it through that handle.
To keep other processes from writing or deleting the file while you use it,
set KACS_OPEN_SHARE_ACCESS in flags and name what you allow in
share_access.
See opening a file for the parameter contract and the kernel's supported create options.
Reading a security descriptor #
The KACS_SECINFO_* selection identifies which components to read. A
request for the owner and discretionary access control list (DACL) does
not also request the system access control list (SACL).
- Choose
peios_fd_get_sdwhen the application already owns a suitable handle. Otherwise, usepeios_file_get_sdwith the intended path policy. - Probe the required length with a zero-capacity buffer and check for
failure before converting the result to
size_t. - Allocate the buffer and check that allocation succeeded.
- Repeat the query. If the descriptor grows and the call reports
ERANGE, probe again or stop according to the application's retry policy. - Parse only the bytes returned by a successful query.
- Keep the buffer unchanged while using parsed views, then release it.
A size probe does not reserve the descriptor or prevent another process from changing it. Do not use the probe's length as though it were the length returned by the second call.
Changing selected components #
Use peios_sd_builder to construct the descriptor that carries the
replacement components:
- Create a builder and check that it is not
NULL. - Add the replacement components, such as the DACL.
- Obtain the encoded bytes and check for a retained builder error.
- Call
peios_fd_set_sdorpeios_file_set_sdwith the correspondingKACS_SECINFO_*selection. - Check the result before reporting success, then free the builder.
Selecting only KACS_SECINFO_DACL preserves the owner, group, and SACL.
Changing an owner or integrity label has additional permission checks;
possessing a syntactically valid descriptor does not satisfy those checks.
Checking the result #
Read the selected components again through the intended object handle and
compare them with the requested values. Distinguish a failed update from a
failed verification query, and preserve the relevant errno before cleanup.
The file-security reference describes each library entry point. The kernel file-security guide owns the kernel's access checks and descriptor merge rules.
Hardening a Process
Peios / Developing for Peios / Access Control
Peios lets a process opt into hardening — exploit mitigations enforced by the
kernel on that process's security block. The SDK exposes this through a single
call,
peios_process_set_mitigations.
This short guide covers using it well; the full flag set and semantics are in
process.h and the operator
docs.
Harden yourself at startup #
The common case is a program hardening itself early in main, before it
processes any untrusted input:
int
pidfd == -1 targets the calling process. mitigations is a mask of
KACS_MIT_* bits (from <pkm/psb.h>); combine the ones you want and set them
together.
Three things to know #
It's one-way. Mitigation bits can only be set, never cleared — once on, they stay on for the life of the process. That's the point: a mitigation you could turn off is one an attacker could turn off. Treat each call as a permanent commitment.
It's all-or-nothing, and fails closed. If any requested protection can't
actually be activated, the call changes nothing and returns -1. You never
end up believing a mitigation is on when it isn't. So request the set you
require together and check the result once — success means the whole set is
active. (Bits from earlier successful calls stay on regardless.)
Targeting another process is privileged. To harden a process other than
your own, you need PROCESS_SET_INFORMATION on it and PIP dominance over it — you can't reach into a process you don't already dominate. For
self-hardening (-1), neither is needed.
Choosing what to enable #
The bit catalog and what each mitigation defends against is documented operator-side under process mitigations (and in the Peios Kernel TRM §3.3, the Process Security Block). A couple of notes for the SDK caller:
KACS_MIT_ALLis the mask of all valid bits — useful for validating input, not usually what you'd blanket-enable without thought.KACS_MIT_CFIis a legacy alias that expands toKACS_MIT_CFIF | KACS_MIT_CFIB.
Enable the specific protections your program can tolerate, verify the call succeeded, and prefer to do it before you touch untrusted data.
Activation and lifecycle #
A valid mask can still fail because a platform cannot activate the protection or existing mappings violate it. Late WXP, TLP, or LSV requests validate existing state; generating incompatible mappings first does not exempt them. TLP and LSV inspect file-backed executable mappings, while WXP also constrains anonymous executable memory. Plan JIT and library-loading behavior before choosing a policy.
Architecture support is part of activation. The maintained kernel refuses
live CFIF requests with ENODEV; CFIB activation is self-only. Having rights
to another process does not overcome either limitation. SML can be satisfied
by a platform reporting itself unconditionally unaffected. UI_ACCESS remains
reserved; do not use the valid-bit mask as a recommended hardening profile.
Fork inherits committed mitigations. Exec preserves them, while recomputing PIP from the executable. PIE governs subsequent exec and NO_CHILD governs subsequent process creation; neither retroactively changes the running image or removes existing children. NO_CHILD permits thread creation and exec.
Handle failures before accepting untrusted work. Read back the committed mask and correlate it with the process GUID; a requested mask or an earlier process's report is not evidence about a replacement process. Self-targeting removes the cross-process authority gates, not input and activation checks. A failed request leaves earlier successful commitments intact.
Do not assume a generic service launcher applies a mitigation mask. Verify the deployed launcher and the running process. The maintained Peinit launch path does not add a per-service mitigation request; inherited flags and application self-hardening remain separate.
Next #
process.hreference — the call in full.- Process mitigations — every mitigation and its threat model.
Authentication Conversations
Peios / Developing for Peios / Authentication Clients
The authentication client library, libauth.so.1, connects applications to
the Peios authentication authority. It carries credential conversations,
identity queries, self-account changes, and requests to end logon sessions.
The authority checks the connected caller and decides what it can do.
Authentication and logon #
Both operations use the same credential conversation. Authenticate returns an established identity and the requested groups and claims. It creates no OS token, session, home directory, or user registry. Logon additionally checks local logon policy and returns a token and session for the caller to install. An Authenticate result cannot be exchanged for a token later.
Use Authenticate for a service that needs to check identity before applying its own access policy. Authd does not need to understand a Wi-Fi network or the meaning of a department claim. The service interprets the identity data.
The shared authentication request supplies the identifier, supported credential types, an optional required type and any method binding. A password-based consumer sets Password as required: advertising support alone also permits an account whose source intentionally requires no credential.
Authenticate separately requests full source group membership and selects None, Named or AllPermitted claim disclosure. AuthenticationSecurity checks group and named-claim permissions before credential collection. Forbidden named disclosure fails the request. An authorized named claim absent from the source is listed explicitly; unrequested groups differ from an empty membership set. Group results exclude locally synthesized token groups.
Claim names use KACS's per-character Unicode lowercase mapping, without normalization or full case folding. Équipe and équipe name the same claim; ß and ss do not. This applies to lookup, duplicate detection, known absence, and claim-specific permission GUIDs. Results retain the source's spelling; claim-value matching is unchanged. A Named absence can therefore supply partial KACS claim knowledge using the same name rule. Other sources must establish matching semantics before their absence assertions are adapted.
This replaces the unpublished ASCII-only development rule. Before upgrading, regenerate affected non-ASCII claim permission GUIDs using auth-policy's claim_guid helper while preserving grants and denies. ASCII identifiers stay unchanged. Resolve source records containing newly equivalent duplicate names; authd refuses their assertions rather than choosing one. Rebuild named-disclosure clients with matching auth-core and libauth revisions. An older authority's ASCII-only absence result cannot be accepted safely. Use the current framing and ABI versions described below.
AllPermitted returns readable claims and a coverage marker. Complete means the result is the whole claim set and omitted names are absent. Filtered means some names might be restricted; omitted names remain unknown. Authd determines coverage from policy rather than the presence of hidden claims, and never reports restricted names or counts. A consumer must deny a policy decision that needs unknown information. Conditions using returned values or complete group membership can still be evaluated normally.
In C, begin with peios_auth_authenticate_begin, read AuthenticationView and the existing identity getters at record index zero, and enumerate absent claims with peios_auth_authentication_absent_claim. The operation owns the result until destroyed. The Rust Client::authenticate wrapper returns an owned Authenticated result through Operation::authenticated. No token accessor succeeds for this operation. AuthenticationView.claim_coverage preserves this knowledge through the C ABI; the owned Rust result exposes ClaimCoverage. The coordinated unpublished C ABI and public PGSS framing versions are 6. Rebuild clients with the matching library; the source protocol is version 4.
An MSCHAPv2 originator advertises Capabilities::MSCHAPV2 and requires
credential type 3. The source's single typed prompt supplies a 16-byte
authenticator challenge in parameters. The answer contains the peer
challenge (16 bytes) followed by the NT response (24 bytes). The source
owns challenge freshness, account eligibility, and credential-version checks.
The completed result includes a 20-byte authenticator response for this
exchange, exposed as mschapv2_authenticator_response through the C view
and owned Rust result. Other proof types carry no MSCHAPv2 output. This
uses the existing Authenticate and disclosure grants and creates no token.
An NTLMv2 originator, such as a file server, names nobody: it sends an
empty identifier, advertises only Capabilities::NTLMV2, and requires
credential type 4. The authority, not a source, sends the single prompt,
whose parameters are the 8-byte server challenge to put in the NTLM
CHALLENGE message. Answer with three length-prefixed spans copied from the
client's AUTHENTICATE message: UserName and DomainName as UTF-16LE,
then NtChallengeResponse. The authority routes on the user in the answer
and the owning source verifies it. A logon then returns a token with the
16-byte SessionBaseKey as ntlmv2_session_key in the grant; general
authentication returns it in the authenticated result instead. The key is
for NTLM key exchange and signing in this one protocol session, and cannot
be used to sign in again. Key exchange, the message integrity code and the
client's AvPairs remain the originator's to process.
Credential collection #
A logon begins with a proposed identity, logon type, and the credential types the application can collect. The authority can request several rounds of answers. Each round contains messages to display and prompts to answer. The application controls its interface; the library does not read a terminal or create a window.
stateDiagram-v2
[*] --> Waiting: Begin
Waiting --> Prompt: Credential request
Prompt --> Waiting: Answer round
Waiting --> Complete: Successful reply
Waiting --> Denied: Authority refusal
Waiting --> Failed: Transport or protocol error
Waiting --> Cancelled: Cancel
Prompt --> Cancelled: Cancel
Prompt labels are display text. Credential types and parameters determine how to collect an answer. Applications advertise supported types and reject requests they cannot handle. Passwords must not be echoed. Secure Shell (SSH) credentials retain the binding to the authorized originator's live transport.
The supported credential list describes what the client can collect. It does not force the source to request a password. An empty list permits only a conversation that needs no collection; it does not bypass account policy.
The authority reads the connected caller's token from the kernel. A proposed logon type is checked against that caller's originator policy. Fields such as the remote host remain claims supplied by the client, not independently verified identity.
Credential verification establishes identity. Token derivation combines that identity with this machine's grants. A source does not send a finished token or choose the machine's privilege set and integrity level.
An unknown account and an incorrect credential share the authentication failure response. The local source performs a decoy password verification for unknown accounts instead of taking a cheap early-return path. This does not make account existence secret: the separate identity interface can report that a principal does not exist. For diagnosis, compare the authority and source authentication events, without recording credential values.
Tokens and sessions #
Successful logon returns a token descriptor, session ID, and profile. The profile supplies a home directory, shell, and display name; these fields are session-start preferences, not proof of identity.
The operation owns the token until the caller takes it. Taking the token transfers responsibility for closing its descriptor. Installing it and starting a process are separate, explicit actions through the Peios software development kit (SDK). Destroying an operation closes any token it still owns.
The shared protocol transport accepts at most one descriptor per message. It rejects extra descriptors and truncated ancillary data, closing received descriptors if it cannot accept the complete message.
A service manager requests a service token through a distinct attestation operation. Self-service credential changes identify the caller from the connection; they do not accept a target username.
Completion and uncertainty #
An authority refusal differs from a lost connection. If a connection fails
after a change was submitted, the change could have taken effect. The error
reports this as outcome_unknown. Cancellation stops communication but cannot
roll back a submitted change. The library never retries a mutation on the
application's behalf.
Ending a session can terminate the program requesting the action. For that case, authd replies before termination and reports prospective process counts. A permission query is advisory: the later action is checked again.
Identity results #
Identity queries retain the difference between a missing identity, an unavailable source, and a refused request. A field can have an empty value or be withheld for a stated reason. These are different results.
Enumeration returns an opaque continuation cursor and a list of sources that did not contribute. A page with no records can still have a cursor. Continue until the cursor is empty, and preserve the incomplete-source information when presenting the result.
Read Using the Authentication Client for the operation loop and resource ownership.
Self-Service Operations
Peios / Developing for Peios / Authentication Clients
The authentication client library supports operations on the caller's own account without granting local account-administration rights. The daemon identifies the caller from the connected process's token.
Account details and display names #
Use Client::own_account() or the corresponding C operation to read the
caller's local account. The result includes its display name, credential
policy, whether a password exists, and enrolled public-key information. It
never contains a plaintext password or its verifier.
Use Client::set_display_name() to change the caller's presentation name. The
request does not accept a target account name, and a display name does not
change the account's security identifier (SID) or sign-in name.
These operations use lpsd's self-service socket. A caller whose account is not held by the local source cannot use that socket to administer a different source's account.
Credential changes need proof #
Password and key changes use credential conversations through authd. The local source asks the caller to prove an accepted current password. Opening the socket or possessing a session token alone is insufficient.
Follow the same prompt handling as a logon: display messages, collect only supported credential types, and answer the current round. An account without a usable password for this proof needs an administrator's help.
Self-service key removal selects a key by its SHA-256 fingerprint. The
administrative lps key remove command selects by key ID instead. Use the
identifier required by the interface you are calling.
Session actions are checked separately #
Client::may_end_session() queries whether the caller can request an action.
Client::end_session() requests the action and checks permission again. A
successful query does not guarantee a later request will succeed.
Warn the person before ending a session because running programs can lose unsaved work. The requesting program can be among the processes stopped. Read Sessions and Account Changes for the result's limitations.
Submitted changes can have uncertain outcomes #
A transport error after submission can leave a change's outcome unknown. The
public error exposes outcome_unknown; preserve that distinction in the user
interface and inspect state before offering a retry.
Canceling or destroying the operation releases client resources. It does not undo a request the daemon has already received. The library does not automatically retry mutations.
For full signatures and ownership rules, use <peios/auth.h>. Local
administrator operations are a separate interface; they are not part of the
public self-service library.
Using the Authentication Client
Peios / Developing for Peios / Authentication Clients
Use libauth to communicate with the authentication authority from your
application. C callers use <peios/auth.h>; Rust callers use peios-auth,
which wraps the same shared library.
Before you start #
Prepare the client dependencies:
- Install the
dev.peios.libauthruntime and thedev.peios.libauth-develsoftware development kit (SDK). - Use an account or service identity permitted to perform the operation.
- For Rust, add the
peios-authcrate from the matching authd source revision.
Link the application #
For a C application with a client.c source file:
-
Include the public header in C:
-
Obtain compiler and linker flags through
pkg-config:
For Rust applications built with Cargo, make auth.pc discoverable through
PKG_CONFIG_PATH. For an explicit development build, set PEIOS_AUTH_LIB_DIR
to the directory containing libauth.so. At runtime, the loader must also
find libauth.so.1. A development shell can set LD_LIBRARY_PATH to that
directory.
Drive an operation #
Use this sequence for each operation:
-
Create a client. Default options use the system sockets. Supply explicit socket paths only when selecting a trusted authority or a test server.
-
Begin the operation. Input strings and buffers are copied before the call returns. A null C handle means the arguments were invalid. A connection failure instead produces an operation with an error result.
-
Call
peios_auth_operation_step(). When it returnsPEIOS_AUTH_WAIT, obtain the descriptor, event mask, and maximum wait frompeios_auth_operation_poll_info(). Wait, then callstep()again, including after a timeout. Never read, write, or close that descriptor. -
At
PEIOS_AUTH_PROMPT, display the round's messages before collecting answers. Submit answers in prompt order, with their original references and the current round ID. Answer a message-only round with an empty answer array. Clear caller-owned secret buffers after submission. -
At a terminal state, inspect the typed result or error. If the operation granted a token, take it only when your program is ready to own the descriptor. Check
outcome_unknownbefore offering to repeat a change. -
Destroy the operation and client. Returned C views borrow the operation; copy any data needed after its next mutable call or destruction.
For blocking programs, peios_auth_operation_wait() performs the wait loop
until a prompt or terminal state. The Rust wrapper provides the same choice
through Operation::step() and Operation::wait(). Its result methods return
owned Rust data.
Check the result #
For Authenticate and Logon, peios_auth_operation_guid() returns a borrowed
authority operation identifier after a reply supplies it. The Rust accessor
is Operation::operation_guid(). An empty C span or Rust None means that
the identifier is unavailable. Copy the C span before mutating the operation.
The identifier links to object.authentication.operation.guid in authority
events. It is not proof of identity or permission. Older authorities can omit
the optional metadata. Malformed or inconsistent metadata removes the
correlation link without changing the credential or token result.
The getter is an additive symbol with unchanged ABI 6 layouts. A program using it needs a libauth build exporting the symbol. Existing clients remain compatible with that library, and the public framing remains PGSS version 6.
A completed permission query means that authd permitted the proposed action at the time of the query. A completed logon provides a token and session profile. Neither result changes the calling process's identity.
Use the public header for function signatures, constants, ownership rules, and the application binary interface (ABI) contract. Keep each operation under one caller's control; different operations can run concurrently.
Reading Identities
Peios / Developing for Peios / Authentication Clients
Use the identity operations in libauth when an application needs account or
group information. Native results retain details that a simple name string or
libc account record cannot express.
Before you start #
Prepare the client:
- Link the runtime and matching headers or Rust wrapper as described in Using the Authentication Client.
- Use the system authority or an explicitly trusted endpoint.
Look up an identity #
Follow these steps:
- Choose a name, binary security identifier (SID), or Unix identifier as the query key. Use the SID when your application already knows the identity and needs its display name.
- Request the identity kind and fields the application needs. Avoid requesting every field for a name-only display.
- Begin the lookup and drive its operation to completion using
stepand polling, or the blockingwaithelper. - Inspect the identity outcome as well as the operation state. A completed exchange can still report no matching identity or an unavailable source.
- Interpret each returned field's state. An empty value, a withheld value, and an absent field are not interchangeable.
In C, the begin function is peios_auth_identity_lookup_begin(). In Rust, use
Client::lookup() and read Operation::identity() after completion. The
public header documents the corresponding request and result types.
Enumerate a list #
Follow these steps:
- Start an enumeration for principals or groups with an empty cursor. Select a group only when requesting that group's members.
- Present or collect the returned records while preserving their SIDs.
- Retain the response's incomplete-source information. A partial list must not be presented as proof that omitted identities do not exist.
- If the next cursor is nonempty, pass its bytes back unchanged with the same query parameters. Continue even when a page contains no records.
- Stop only when the next cursor is empty or an error prevents progress.
Do not parse the cursor, derive one from the last name, or assume that every source supports complete enumeration.
Check the result #
Exercise the application's handling of an unknown identity, an unavailable authority, a withheld field, and an incomplete enumeration. The interface must preserve those differences instead of collapsing them into an empty list or an anonymous account.
C result views borrow the operation. Copy data needed after its next mutable call or destruction. The Rust wrapper returns owned result data.
Detect credential replacement #
CREDENTIAL_BINDINGS requests opaque reference and revision pairs owned by
the source. Disclosure requires the existing Authenticate right. A missing,
restricted, or unreported field means unknown; it does not establish deletion.
References are scoped to the authoritative principal SID. Neither part is a
credential, token, or proof of possession.
Local queries list eligible password bindings. Disabling the password credential policy omits that binding from a present list without destroying its stored revision. An explicitly empty list is authoritative; an unreported or restricted list is unknown. NT-storage policy alone does not remove the underlying password binding.
A successful Authenticate result can disclose the binding that actually verified. Retain it with the verified SID. Later SID lookups can detect a replacement; they cannot advance the revision that a session proved. Only fresh successful authentication can do that. Password, MSCHAPv2, and NTLMv2 refer to the same local password binding. Older sources can omit it.
C uses peios_auth_record_credential_binding_count() and
peios_auth_record_credential_binding() with reference or revision parts;
each borrowed part is 16 bytes. Rust exposes Field::CredentialBindings.
These additive exports require matching libauth headers and runtime. Existing
ABI 6 layouts are unchanged.
Registry Overview
Peios / Developing for Peios / The Registry
LCS — the Layered Configuration Subsystem — is Peios's registry: a
kernel-mediated, hierarchical, secured configuration store. If you have used
the Windows registry it will feel familiar — a tree of keys holding typed
values — but LCS adds one defining idea: layers. This section teaches
the client API;
registry.h is the
exhaustive reference.
Keys and values #
A key is a node in the tree. It has an immutable GUID identity, a KACS
security descriptor
that governs who can read or change it, and it holds values and child keys.
You address a key by path and open it for specific KEY_* rights, getting
back a key fd whose granted access is fixed for its lifetime.
A value is a named, typed piece of data on a key (REG_SZ, REG_DWORD,
REG_BINARY, and the rest). An empty name is the key's default value.
Layers and precedence — the LCS idea #
Here is what makes LCS more than a key/value store. Every value write is tagged with a layer, and each layer has a precedence. When you read a value, LCS resolves the effective entry — the one from the highest-precedence layer that has something to say, or, among layers of equal precedence, the most recent write — and that's what you get back.
This is what lets configuration compose cleanly:
- The base layer, at precedence 0, receives every write that names no layer.
- Role layers also sit at precedence 0 and carry what an installed role adds.
- Policy layers sit above precedence 0 and override both.
They all coexist on the same key. Reading gives you the winner; writing targets a specific layer (or the base layer by default). And because it's layers rather than destructive overwrites, removing a higher layer's entry lets the lower one re-emerge — you can override and then un-override without losing the original.
Tombstones are the tool for "hide, don't delete": a per-value tombstone masks lower layers for one value, and a blanket tombstone masks all lower values of a key on a layer at once. Keys have the same idea through hide.
Reads report where the answer came from #
Because a value can come from any layer, the read tells you which layer won and gives you a sequence number for the effective entry. That sequence number is the basis of safe updates: pass it back as a compare-and-swap guard on a write, and the write only lands if nothing changed underneath you.
Transactions #
Mutating operations can be grouped into a transaction and committed atomically: writing or deleting a value, setting or removing a blanket tombstone, creating, deleting, or hiding a key, and changing a security descriptor. A transaction covers one hive, so a multi-step configuration change either fully applies or not at all. Transactions are abort-by-default: close the transaction fd without committing and nothing happens. See watching and transactions.
Watches #
You can ask a key to notify you when it changes — values, subkeys, or its
security — optionally across its whole subtree. The elegant part: once armed,
the key fd itself becomes pollable, so a registry watch drops straight
into an epoll loop with no side channel.
The client, not the source #
This SDK is the registry client — it reads and writes the store. It does
not implement a registry source (a storage backend); that's a separate
library, librsi. As a client you speak
only the calls in
registry.h.
Where to go in this section #
- Reading and writing — open a key, read effective values, write to layers, do safe updates.
- Watching and transactions — react to changes and apply atomic multi-step edits.
registry.hreference — every call in full.
Reading and Writing
Peios / Developing for Peios / The Registry
This guide covers the bread-and-butter registry operations. The full call
signatures and error sets are in
registry.h; here you
string them together. Recall the registry's descriptor-struct buffer
convention: reads fill
*_cap/*_len fields and a zero-capacity buffer probes.
The code fragments elide some error checks for brevity — every call returns
-1 with errno on failure, and real code must check each one (see Library
conventions).
Opening a key #
Open a key for the rights you need:
int key = ;
if
parent_fd == -1 means path is absolute. To open relative to a key you
already hold, pass that key fd as the parent. Use
peios_reg_create_key
instead when the key might not exist yet — it opens-or-creates and reports
which happened.
Reading the effective value #
Reading resolves layer precedence for you and hands back the winning value, its type, and which layer it came from:
struct peios_reg_value v = ;
unsigned char data;
v.data = data; v.data_cap = sizeof data;
/* leave v.layer NULL if you don't care which layer won */
if else if else if
The name_len is explicit (value names are length-counted; 0 reads the
key's default value). Pass a transaction fd as the fourth argument to read
within a transaction, or -1 for none.
To read every value at once, use
peios_reg_query_values_batch — one call fills a buffer with all effective values in a packed record format.
To walk them one at a time, loop peios_reg_enum_value from index 0 until
ENOENT.
Writing a value #
Writes target a specific layer. Pass NULL/0 for the layer to write the
base layer:
uint32_t timeout = 30;
int rc = ; /* no CAS guard */
Writing to a higher-precedence layer overrides lower ones without destroying them; deleting that layer's entry later lets the lower value re-emerge.
Safe updates with compare-and-swap #
To read-modify-write without clobbering a concurrent change, feed the
sequence you read back as the expected_seq guard on the write. The write
only lands if nothing changed underneath you; otherwise it fails with EAGAIN
and you retry:
for
Passing expected_seq == 0 disables the guard (an unconditional write).
Cleaning up #
Close key fds with close() when done. Values you wrote with auto-commit
(txn_fd == -1) are already durable to the layer; to force the source to
persist a hive's pending writes at a known point, call
peios_reg_flush.
Next #
- Watching and transactions — react to changes and batch atomic edits.
registry.hreference — every call, field, and error.
Watching and Transactions
Peios / Developing for Peios / The Registry
Beyond simple reads and writes, LCS gives you two higher-order tools:
watches to react to change, and transactions to apply several edits
atomically. Both are in
registry.h; this
guide shows the shape of using them. To keep that shape visible, the fragments
elide most error checks — every call returns -1 with errno on failure, and
real code must check each one (see Library
conventions).
Watching for changes #
Ask a key to notify you when it changes, then poll its fd. Because the armed key fd is itself pollable, a watch integrates directly into whatever event loop you already run:
int key = ;
/* Watch values and subkeys, across the whole subtree. */
;
struct pollfd pfd = ;
for
filter is a mask of REG_NOTIFY_VALUE, REG_NOTIFY_SUBKEY, and
REG_NOTIFY_SD; REG_NOTIFY_ALL covers all three. The subtree flag extends
the watch to descendants. Arming needs KEY_NOTIFY on the key. Call
peios_reg_notify(key, 0, 0) to disarm.
Each read() drains as many complete change records as fit — every record
starts [total_len: u32][event_type: u16][name_len: u16][name], so you step
through the buffer by total_len. The full layout, the REG_WATCH_* event
types, and the extra path fields a subtree watch appends are in the
reference.
Two practical notes: a buffer too small for even one record fails EINVAL, so
size it generously rather than exactly; and a REG_WATCH_OVERFLOW record
means events were dropped — re-read the key's state instead of trusting the
stream.
This is how a service picks up configuration changes live — no polling loop
re-reading values on a timer, a blocking poll that wakes when something
actually changed.
Transactions #
When a configuration change spans several operations — create a key, set a few values, delete a stale one — you usually want it to be all-or-nothing. That's a transaction.
Begin one, pass its fd as the txn_fd argument to each operation you want
enlisted, then commit:
int txn = ;
int key = ;
uint32_t one = 1;
;
;
int rc = ;
if else if
;
;
Two things to keep in mind:
- Abort is the default. If you close the transaction fd without committing — including on any early-return error path — nothing is applied. So you don't need explicit rollback logic; don't commit.
- Commit can be retried.
EBUSY(write-lock contention) andEIO(source failure) leave the transaction active, so you can retrypeios_reg_commit. Only0(committed — the fd is now terminal) andEINVAL(already committed or never bound) are final. Check state at any point withpeios_reg_txn_status.
Consistent reads #
peios_reg_begin_read_transaction() creates a bounded read-only transaction.
Use its fd for every value read and enumeration, and use
peios_reg_open_key_transacted() for key resolution. The first read fixes
one hive's persistent and volatile data and its layer selection. A write
transaction that has not yet written does not provide this guarantee.
Metadata and descriptor reads have matching
peios_reg_query_key_info_transacted() and
peios_reg_get_security_transacted() calls. Their final argument is the
transaction fd, or -1 for a live read. Their buffer contracts match the
ordinary calls. Close the transaction as soon as the configuration has been
copied.
Mutations fail EROFS, another hive fails EXDEV, and lifetime expiry fails
ETIMEDOUT. Capture overlapping Registry publication can return EAGAIN;
discard the partial result and repeat the entire read with a fresh
transaction.
There is no fallback to ordinary reads.
Changing the caller's ordered private-layer or hive-scope attachments during
the transaction fails EACCES. Start a fresh transaction for a different
view.
Historical descriptors are data. A new transacted open checks the current descriptor of the resolved GUID against the actual caller. Existing handles keep their granted rights. Files named by Registry values are outside the snapshot: prepare immutable files first, switch their references atomically, and retain old files until readers have finished with them.
Backup and restore #
To snapshot a key and its whole subtree, or replace one from a snapshot, use
peios_reg_backup and
peios_reg_restore. They stream to and from an fd and are gated by
SeBackupPrivilege / SeRestorePrivilege; restore applies in a single
transaction.
Next #
registry.hreference — the notify filters, transaction states, and every error in full.- Reading and writing — the value operations you enlist in a transaction.
Registry Sources
Peios / Developing for Peios / Registry Sources
A registry source stores registry data and answers requests from the kernel. Use librsi when implementing that storage backend. Applications that only read or write registry keys use libpeios instead.
The Registry Source Interface (RSI) carries framed requests and responses on a source file descriptor. The libraries share a release and C calling conventions, but each exposes its own shared library.
Request flow #
A registry client reaches storage through the kernel:
flowchart LR
client[Registry client: libpeios] --> kernel[Kernel registry service]
kernel <-->|RSI requests and responses| source[Storage backend: librsi]
The source lifecycle has three stages:
- Register the hives that the source backs and receive a source descriptor.
- Read each request, decode it, perform the storage operation, and respond.
- Close the descriptor when the source stops serving requests.
Registration requires SeTcbPrivilege. The source supplies its highest
persisted sequence number so that the kernel can continue sequence
allocation without reusing older values.
Storage responsibilities #
The kernel mediates client access, checks security, resolves registry layers, and coordinates transactions. The source stores entries, key metadata, values, and transaction state.
A successful response means that the source performed the operation with the persistence semantics required by the registry protocol. librsi encodes and validates messages; it does not implement a database, transaction journal, or recovery policy for the backend.
Buffer lifetime #
Request decoders return pointers into the received frame. Process or copy those bytes before reusing the frame buffer. If storage work outlives the read loop iteration, keep the frame alive or make an owned copy first.
The source sends one response for each request. Preserve its request ID and operation code when constructing the response. Do not send a success status for an operation that the backend has not completed.
Start with registering a source, then serving requests and building responses.
Registering a Source
Peios / Developing for Peios / Registry Sources
Every source starts by registering. You tell the kernel which hives your
process backs, and it hands you a source fd to serve on. The full detail is in
rsi/source.h; this
guide walks the decisions.
Declare your hives #
A hive is a registry subtree with its own root key. Fill in one struct rsi_hive per hive your source backs:
struct rsi_hive hive = ;
The two decisions per hive:
- Global or private? A global hive (
flags = 0,scope_guidzero) is visible system-wide. A private hive (flags = RSI_HIVE_PRIVATE,scope_guidnon-zero) is scoped — only tokens carrying that scope GUID in their LCS credentials can resolve it. Use a private hive for per-application or per-tenant state that shouldn't be system-visible. - The root GUID. Every hive is anchored at a root key identified by
root_guid. This is the GUID paths in the hive resolve from, and it must match the root your storage actually holds.
Register #
Hand the kernel your hive array and the highest sequence number you've already persisted:
int src = ;
if
/* `src` is the source fd — serve the RSI protocol on it. */
Two things to get right:
SeTcbPrivilegeis required. Registration is a trusted operation; without the privilege you getEPERM. Sources run as trusted system components.max_sequenceis your durability contract. It is the highest sequence number this source has already persisted. The kernel resumes its global sequence counter past it, so it never hands out a number you've used. A brand-new source with no stored state passes0; a source restarting with durable data must scan that data for the highest sequence it ever wrote and pass that. Getting this wrong risks sequence reuse, so make it the first thing your restart path computes.
You can register several hives in one call by passing an array and a count
greater than one; the kernel enforces its configured MaxHivesPerSource limit
(ENOSPC if you exceed it).
Optional transaction lifetime control #
The kernel also supports lifetime extension version 1. A source using it opens
/dev/pkm_registry, calls REG_SRC_NEGOTIATE with version 1 and zero flags,
retains the returned session identifier, and then calls REG_SRC_REGISTER.
The current rsi_register convenience function uses the legacy registration
sequence; negotiate through the explicit device/ioctl sequence when adopting
this extension.
After reading each request, query REG_SRC_REQUEST_CONTEXT with its request
id and the negotiated session. It returns the original request deadline and
any transaction lifetime and cleanup-lease deadlines, all in CLOCK_MONOTONIC
nanoseconds. Renew live transactions using REG_SRC_RENEW, independently of
the normal request queue. Renewal cannot extend the transaction lifetime or
revive an expired lease. Both read-write transactions and read-only snapshots
use the same ownership rules. Serialize expiry cleanup with transaction
operations and wait for an admitted commit's actual result before reclaiming
its state.
The data-frame layout is unchanged. Sources without negotiation retain the legacy protocol. Current loregd requires the extension and must be deployed with a kernel that implements it. The PKM TRM, §5.8.3, specifies the control ioctls and their error and lifetime rules.
After registration #
The returned fd is your serve endpoint — you read(2) requests and
write(2) responses on it directly (through the
request and
response
helpers). Closing it deregisters the source and signals EOF to the kernel.
Keep it open for the life of the source, and move on to the serve
loop.
Next #
- Serving requests — the loop that runs on the source fd.
rsi/source.hreference — every field and error.
Serving Requests
Peios / Developing for Peios / Registry Sources
With a source fd in hand, a
source spends its life in one loop: read a request, decode it, do the work,
reply. This guide builds that loop. The exhaustive per-op detail is in
rsi/request.h and
rsi/response.h.
The loop skeleton #
unsigned char buf; /* size generously — a short buffer is EMSGSIZE */
for
Three details in that skeleton matter:
rsi_read_requestblocks until a request is queued, and returns0at EOF — that's your exit. Sizebufgenerously; a frame larger thanbufreturns-1/EMSGSIZE.rsi_parse_requestgives youreq.op_codeto dispatch on, plusreq.request_id(which every reply must echo — the helpers do this for you) andreq.txn_id(nonzero when the request is inside a transaction).- Always reply. Every request expects exactly one response. If you can't handle an op, reply with a non-OK status rather than dropping it.
Decoding a request #
Inside a handler, decode the payload with the matching rsi_request_* parser.
For a LOOKUP:
void
And for a SET_VALUE, a status-only op:
void
The borrow rule #
Every decoded name and data field — q.child_name, v.value_name, v.data,
and the rest — is a (ptr, len) pair that points into buf. Those
pointers are valid only until the next rsi_read_request reuses the buffer.
So:
- Consume them within the handler (store the bytes, resolve the name) before the loop comes around again, or
- Copy out anything you need to keep. Never stash a raw borrowed pointer across iterations.
GUIDs and scalars in the decoded struct are copied by value, so those are
always safe to keep — it's only the borrowed (ptr, len) fields that have the
lifetime.
Transactions #
When the kernel sends BEGIN_TRANSACTION, buffer subsequent writes tagged
with that transaction_id instead of applying them; req.txn_id on each
later request tells you which transaction it belongs to (0 = none). On
COMMIT_TRANSACTION apply the buffered set atomically; on ABORT_TRANSACTION
discard it. All three are status-only replies. The kernel coordinates
transaction boundaries — your job is to buffer, then commit or discard on
command.
Next #
- Building responses — choosing and filling the right reply.
rsi/request.hreference — every op's decoder and struct.
Building Responses
Peios / Developing for Peios / Registry Sources
Every request gets exactly one response. Choosing the right one is simple once
you know the rule; filling it in is a matter of handing librsi flat arrays and
letting it encode the frame. The full contract is in
rsi/response.h;
this guide is the working version.
The rule #
On failure, always
rsi_respond_status. On success,rsi_respond_statustoo — unless the op is one of the five that carry a payload.
Most operations (SET_VALUE, CREATE_KEY, the transaction ops, FLUSH, …)
are status-only in both cases. And any op reports a non-OK outcome with
rsi_respond_status, whatever it is:
/* Success for a status-only op: */
;
/* Any op reporting a problem: */
; /* for example a missing key */
; /* a failed CAS */
You never build the frame or echo the request id yourself — the helper reads
what it needs from req and writes the framed reply to fd.
The five payload-bearing ops #
Exactly five ops return data on success, each with its own helper:
| Op | Helper | You supply |
|---|---|---|
LOOKUP | rsi_respond_lookup | path entries + the referenced keys' metadata |
ENUM_CHILDREN | rsi_respond_enum_children | children (name + path entries) + metadata |
READ_KEY | rsi_respond_read_key | one key's non-layered metadata |
QUERY_VALUES | rsi_respond_query_values | value entries + blanket tombstones |
DELETE_LAYER | rsi_respond_delete_layer | the orphaned keys' GUIDs |
You pass the result as flat arrays; librsi validates and heap-encodes the wire
frame. A QUERY_VALUES reply, for example:
struct rsi_value_entry values = ;
;
You report what you store, per layer; the kernel resolves precedence across
the layers you return. (Note the (NULL, 0) for the empty blanket array — a
NULL pointer is allowed only when its count is zero.)
The validation contract #
The helpers check their inputs before encoding and return -1/EINVAL if you
break the contract — better a caught programming error than a malformed frame
on the wire. The rules that apply across all of them:
(ptr, len)pairs: a pointer can beNULLonly when its length/count is zero.- Booleans (
volatile_key,symlink, target types) are strictly0or1. - Hidden path targets (
RSI_PATH_TARGET_HIDDEN) carry an all-zerotarget_guid. LOOKUP/ENUM_CHILDRENmetadata must exactly cover the GUID targets in your path entries — every referenced key present, none missing, no duplicates, nothing unreferenced.DELETE_LAYERorphan GUIDs are nonzero and unique.
Beyond EINVAL, a helper can also fail with ENOMEM or EOVERFLOW (building
the frame), EIO (a short write), or the raw write(2) errno — treat those
as you would any I/O failure on the source fd.
Putting it together #
A source's handler for a payload-bearing op is: decode the request, gather the
result from storage into the flat arrays the helper wants, call the helper.
For a status-only op: decode, do the work, rsi_respond_status. On any error
along the way — a decode failure, a missing key, an I/O problem —
rsi_respond_status with the appropriate non-OK RSI_* code. That uniformity
is what keeps a source's dispatch table readable no matter how many ops it
supports.
Next #
rsi/response.hreference — every helper, struct, and error in full.- Serving requests — the loop these replies live in.
Events Overview
Peios / Developing for Peios / Events
KMES is Peios's event system, and it is the sole event path on the system.
Audit records, subsystem events, and your own application events all travel
the same way: the kernel stamps each event with trusted metadata and writes it
into a per-CPU, lock-free ring buffer, and consumers drain those rings. This
section teaches both sides — producing and consuming — through
event.h and
msgpack.h.
What an event is #
An event has two parts:
- Kernel-stamped metadata you cannot forge — a
CLOCK_REALTIMEtimestamp, a per-CPU monotonic sequence number, the CPU id, an origin class, and identity GUIDs (the effective token, the true token, and the process). This is the trustworthy skeleton: when you consume an event, you know who emitted it and when, because the kernel wrote that, not the emitter. - A payload — a single MessagePack value that you define. This is your event's actual content.
The event type names the kind of event. It's a dotted name made of your
package name, what the event is about, and what happened, such as
org.example.backup.snapshot.created. Its fields follow one vocabulary shared
by every emitter on the system.
Naming and Shaping Events
explains how to choose both.
Payloads are MessagePack, and you own them #
The kernel does not build or interpret payloads — it only structurally
validates them on emit (one well-formed MessagePack value, within size and
nesting limits). So userspace owns encoding and decoding, and the SDK ships a
MessagePack codec whose
validator's acceptance is matched to the kernel's check. Build a payload with
the writer, and a successful peios_mp_writer_bytes (or peios_mp_validate)
establishes structural validity. Emission still checks size limits,
permissions, rate limits, and the other requirements of the event interface.
Per-CPU rings and lost events #
Events live in per-CPU ring buffers — one ring per logical CPU, lock-free so producers never block on consumers. Two consequences shape how you consume:
- You drain per CPU. To see everything, run a reader per CPU (discover the count by attaching upward from CPU 0 until it fails).
- Rings can lap. If you don't drain fast enough, new events overwrite old
ones you haven't read. The per-CPU
sequencenumbers are contiguous, so a gap in the sequence means events were lost — and the reader tracks that count for you.
Privileges #
The two sides are gated separately:
- Emitting requires
SeAuditPrivilege. - Consuming (attaching to a ring) requires
SeSecurityPrivilege.
Two ways to consume #
The SDK offers a high-level reader that hides the entire lock-free drain —
barriers, lapping recovery, lost-event accounting, buffer-resize handling, and
the wait — behind a simple next/wait loop. That's what almost everyone
should use. There is also a low-level ring API for callers who need to
drive the drain inside their own event loop. Both are covered in consuming
events.
Where to go in this section #
- Naming and Shaping Events — design the type, fields, tier, and catalog entry before emitting it.
- Emitting events — build a payload and emit individual events or batches.
- Consuming events — drain the rings with the high-level reader (and, briefly, the low-level ring).
event.handmsgpack.h— the exhaustive reference.
Naming and Shaping Events
Peios / Developing for Peios / Events
Design an event around an occurrence an operator needs to identify, query, or investigate. A shared naming scheme and field vocabulary let the same filters and access policies work across components and language SDKs.
The example is a backup package named org.example.backup. It records each
attempt to create a snapshot archive. The
event specification owns the
rules; this guide applies them to an emitter's design.
Before you start #
- Identify the package that owns the event and the operation it describes.
- Inspect the installed event catalog with
evmanfrom Peiosutils. - Identify which facts your component observes and which it receives as claims.
Choose an event rather than a log or metric #
- Ask whether an operator would act on the information. Developer narrative belongs in a log.
- Ask whether one occurrence matters by itself. If only the trend matters, publish a metric instead.
A failed snapshot matters individually, so the backup attempt is an event. The daily amount of backed-up data is a metric. A trace of internal function calls is developer logging. See Event Classification and Tiers.
Name the operation #
-
Start with the owning package name.
-
Add nouns from general to specific where the grouping supports a useful filter or policy boundary.
-
End with a past-tense description of the operation:
org.example.backup.snapshot.created
Use one type for success and failure. A failed creation still uses this type,
with outcome.success = false; do not add a parallel snapshot.failed type.
Use lowercase kebab-case segments, such as copied-up. Short platform roots,
such as kacs, are reserved. Package-name roots and the remaining segments
have their own grammar in Event Types.
Reuse the field vocabulary #
-
Search existing definitions before adding fields:
-
Choose fields by their role:
subjectfor who acted,objectfor what was acted on,sourceanddestinationfor endpoints, andoutcomefor the result. -
If no existing field has the required meaning, define a field beneath the owning package name and its role.
The snapshot uses shared fields plus one package-owned identifier:
| Field | Meaning in the snapshot event |
|---|---|
object.kind | file |
object.file.path | Archive path |
object.file.size | Archive size in bytes, present on success |
object.org.example.backup.snapshot.id | Stable snapshot identifier |
operation.duration | Elapsed nanoseconds |
outcome.success | Whether creation succeeded |
outcome.reason | A declared reason when it failed |
outcome.errno | Negative error number when applicable |
The package owns object.org.example.backup.snapshot.id; it references the
other definitions rather than redefining them. If many components need the
same missing concept, propose a shared field instead of giving it several
incompatible names.
Do not duplicate the timestamp, sequence, or identity fields already stamped in the event header. Use binary security identifiers for principals rather than account names. Omit a field for which no value is available; do not substitute nil, an empty string, or zero. A real zero, such as an empty file's size, remains a meaningful value.
Match the declared wire types #
Choose the encoding from the catalog definition, not from how a value is displayed:
| Value | MessagePack encoding |
|---|---|
| Security identifier (SID) | Binary SID bytes |
| Globally unique identifier (GUID) | 16 raw bytes |
| Timestamp | Unsigned nanoseconds since the Unix epoch |
| Duration | Unsigned nanoseconds |
| Boolean | Boolean value |
| String enumeration | Declared kebab-case string |
| Numeric enumeration | Declared unsigned numeric value |
| Error number | Signed negative integer |
A numeric enumeration is not interchangeable with a string enumeration. Follow the declared field type and its list of values. See Values for the full encoding rules.
Represent dotted paths as nested maps. object.file.path means an object
map containing a file map containing a path key. A literal key named
object.file.path is not that hierarchy. The package-owned identifier has
its own nested object → org → example → backup → snapshot → id
path.
Record the outcome #
- Set
outcome.successto the result of the operation. - On failure, supply a declared
outcome.reason, such asdisk-full. - Include
outcome.errnoonly when an error number applies. Record its negative form, such as-ENOSPC.
The reason is a stable filtering value. Free-form explanation belongs in
outcome.detail when the catalog allows it; consumers should not parse that
text as a replacement for the reason. Describe required and conditional
fields in the fragment so both successful and failed attempts remain valid.
See Outcomes.
Choose the tier and apply policy #
Use standard for ordinary operational records, including this snapshot.
Use verbose for investigation detail and debug for developer detail;
those tiers are off by default. Reserve essential for rare, critical
occurrences or events already governed by their own configuration, such as
access auditing. Essential does not mean that every program's diagnostics
are unconditionally important.
Emission policy is rooted at Machine\Generic\Events, with one key per
segment. This package's subtree is
Machine\Generic\Events\org\example\backup. Check policy before building
and emitting a nonessential record. Consumer-side filtering does not replace
that decision. Read Emission Policy
for inheritance, failure handling, and interactions with other audit controls.
Publish the definition and check the result #
- Describe the event and package-owned field in an
.evmanfragment. - Specify the tier and each field's required, optional, or conditional presence.
- Lint it with the intended catalog and test actual encoded events against it.
- Include the fragment in the package alongside the emitter.
Writing evman Pages contains the matching snapshot fragment and the validation workflow. Keep it as the format example rather than maintaining a second copy here. Emitting Events builds the corresponding payload with the C SDK and explains individual and batch submission.
A well-formed MessagePack value is not necessarily a catalog-conforming event. Check that successful and failed fixtures contain every required field with the declared type, that absent values are omitted, and that queries can reach the nested paths. A successful encoding or emission call does not prove those semantic properties.
If your daemon guards access to its own objects, pass an audit context to the kernel access check instead of inventing a competing access-denial event. Access Decisions explains how the descriptor and audit policy control those records.
Emitting Events
Peios / Developing for Peios / Events
Use the C SDK to encode an event payload and submit it to the kernel. Choose the type and its catalog definition first; the example follows Naming and Shaping Events. The event and MessagePack headers define the complete API.
Before you start #
- Install matching Peios SDK headers and libraries.
- Run emission calls on a Peios kernel with
SeAuditPrivilegeavailable as required by the access policy. - Install the matching
.evmanfragment and select the declared tier. - Include
<peios.h>,<errno.h>,<stdint.h>, and<string.h>in the example's translation unit.
Check emission policy #
- Open a
peios_event_policyhandle at startup and handle allocation failure. - Before constructing a payload, call
peios_event_policy_enabledwith its type name and declared tier. - If the result is
0, skip the event. If it is-1, handle the failure according to the policy interface rather than treating it as permission. - Close the handle when the emitter shuts down.
The handle caches decisions and watches registry changes. Its check does not make a later emit operation atomic with a policy update. Essential types are always on at this layer; their own audit or reporting controls still apply. See Emission Policy.
Build a complete payload #
The following helper builds a successful snapshot event matching the fragment in Writing evman Pages. Supply a valid UTF-8 archive path, a 16-byte snapshot identifier, the archive size, and the elapsed nanoseconds. The helper returns an owned writer that the caller must free.
static peios_mp_writer *
A map count is the number of key/value pairs. A dotted catalog path becomes
a chain of nested maps, including each segment of the package-owned field.
Writer errors are sticky: check peios_mp_writer_bytes before using its
result.
Structural validation does not check catalog meaning or guarantee emission.
For a failed snapshot, keep the same type and identifier. Omit the unknown
archive size, write outcome.success = false, and include a declared reason.
Add a negative outcome.errno when one applies. Adjust the file and
outcome map counts to match the fields actually written. Do not append a
second outcome map or another top-level value to an already completed payload.
Submit and release the payload #
After a successful policy check, call the helper and submit its bytes:
static int
The bytes are borrowed from the writer until it is changed or freed. The submission copies them before returning. The length-counted UTF-8 type is nonempty; the terminating NUL is not part of the name on the wire.
Handle emission errors, including invalid input, insufficient privilege, oversized payloads, and rate limiting. A successful encoding does not bypass those checks. On success, the kernel supplies trusted header metadata and marks the origin as userspace. Your payload remains the emitter's assertion.
Batch high-rate events #
peios_event_emit_batch accepts an array of peios_event_entry values and
reports the accepted prefix through its emitted output. Count is bounded by
KMES_BATCH_MAX_ENTRIES and cannot be zero.
If an entry fails, earlier entries can already have been emitted. Do not
replay that prefix as though the batch were a transaction. Rate-limit refusal
is the special all-or-nothing case: EAGAIN accepts no entries in that batch.
Keep all names and payload buffers valid until the call returns.
See Batch Emit for the complete signature and error contract. Shared timestamp capture and wakeup work make batching useful when the application naturally has multiple events ready; avoid delaying important events merely to fill a batch.
Check the result #
- Decode a portable fixture and verify its field paths and wire types against the catalog, including the required snapshot identifier.
- Test successful and failed operation payloads separately.
- In a permitted Peios test environment, confirm policy-controlled omission, emission results, and the record observed by a consumer.
Consuming Events explains the read side. A codec test on another kernel verifies encoding only, not Peios emission or identity stamping.
Consuming Events
Peios / Developing for Peios / Events
Consuming events means draining the per-CPU ring buffers. The SDK's high-level
reader hides all the hard parts, so most consumers are a short loop. This
guide shows that loop and how to parse what you read;
event.h has the full API.
Consuming requires SeSecurityPrivilege.
The reader loop #
Open a reader for a CPU, then loop next/wait:
peios_event_reader *r = ;
if
for
;
peios_event_reader_next returns 1 (event filled), 0 (nothing available —
call wait), or -1 (error). peios_event_reader_wait blocks until events
arrive or the timeout elapses (negative = forever). The reader handles the
memory barriers, lapping recovery, buffer-resize handling, and futex wait
internally — you alternate the two calls.
Parsing an event #
Each struct peios_event gives you the trusted metadata by value and the
payload as a MessagePack value. Parse it with a
reader:
void
The lifetime rule #
In libpeios 0.5.12 and later, ev->event_type and ev->payload point
into a private reader snapshot. Kernel overwrites cannot change those
bytes. The pointers remain valid until the next read or reader closure.
Copy anything you need to retain beyond that lifetime.
Draining every CPU #
Rings are per-CPU, so one reader sees only one CPU's events. To consume the whole machine, run a reader per CPU — typically one thread each. Discover the CPU count by attaching upward until it fails:
uint32_t ncpu = 0;
for
/* now spawn one peios_event_reader per cpu in [0, ncpu) */
Watching for loss #
If a consumer falls behind, the producer laps it and events are lost. Poll
peios_event_reader_lost
to see the cumulative count of lost events (derived from sequence gaps). A
rising number means you aren't draining fast enough — process events more
cheaply, hand off to a worker, or accept the loss deliberately.
The low-level ring #
If the reader's loop doesn't fit your event model — you want the ring
integrated into an existing epoll/state-machine loop, driving the read
position yourself — the low-level ring
API exposes the
mapping directly: peios_event_ring_map, the position accessors
(write_pos/tail_pos/generation), peios_event_ring_event_at to parse a
slot, and peios_event_ring_wait to sleep. It's more bookkeeping (you own the
read position and the empty/lapping/generation checks) for more control. Reach
for it only when you need to; the high-level reader is the right default.
Next #
event.hreference — the full reader and ring APIs, and everystruct peios_eventfield.- Auditing — the operator-side view of the event and audit stream.
Rust Query Clients
Peios / Developing for Peios / Events
The eventd-client Rust crate provides query framing and client lifecycle
handling. It shares access-right constants with the daemon so that clients
can describe policy without implementing the authorization decision.
The default access feature includes the local access-policy helpers.
Query-only consumers can turn off default features without changing the
server's authorization of their queries.
Finite queries #
query returns the complete result after the server's terminal response.
A server error discards the accumulated initial records. The call blocks,
so a graphical client must keep it off its interface thread.
The result is a vector in client memory. Server resource limits do not make that client allocation a fixed-size buffer. Choose bounded queries or use the wire interface when an application needs a different storage strategy.
wire::Connection::bounded(stream, max_frame_bytes) rejects an oversized
response-frame length before reserving its body. A rejected frame ends the
connection. Reconnect instead of trying to skip the body. The bound applies
to encoded frame bytes; decoded values and retained result collections need
separate memory bounds. Connection::new retains its protocol-sized bound.
Streaming queries #
Tail reads a STREAM query on a worker thread. It reports the complete
initial result, live batches, and the reason the stream ended. Dropping the
handle shuts down the connection and releases the receiving channel.
The channel capacity bounds queued reports, not their total bytes. A client that stops consuming reports eventually stops reading the socket, and the server can disconnect it. A client must handle that end state; reconnecting does not provide a resume cursor.
Query text and policy #
Use the crate's text helpers to quote values when constructing queries.
Do not concatenate untrusted strings as query syntax.
The access module can describe relevant registry policy to a person.
Only eventd, using kernel access checks and the socket peer token,
authorizes a query. A client's policy preview cannot replace that check.
See the manual's client library reference for lifecycle and wire details.
System Service Libraries
Peios / Developing for Peios / System Service Libraries
Peios system services publish C libraries so that your application can ask them for their state, or ask them to act, without starting a command and reading its output. Each library has a Rust crate that wraps the same shared library. For access control, the registry, and events, use the Peios SDK instead. For sign-in and account operations, use the authentication client.
Choosing a library #
Choose the library for the service or format you need:
| Library | Use it to | Rust crate | Guide |
|---|---|---|---|
libresolvd | Look up names and addresses, read resolver status, and flush the cache | resolvd-client | Using libresolvd |
libtimed | Read clock status and sources, follow clock changes, and request time changes | timed-client | Using libtimed |
libtrust | Read and follow the trusted root certificates, and add or distrust certificates | trust-client | Using libtrust |
libreg, libregman, libevman | Parse registry documents, registry manuals, and event catalogs | peios-reg, peios-regman, peios-evman | Utility Libraries |
libresolvd, libtimed, and libtrust talk to a running service. The
utility libraries work on documents and need no service.
What the service decides #
The service, not the library, decides what each call can do. It checks the caller's permissions for the operation, so a call can be refused even when the library loads and connects. A management call, such as adding a trusted certificate or flushing the resolver cache, uses your own rights; the library never raises them.
Each library's major version is part of its shared-library name, such as
libresolvd.so.1. A new major version means an incompatible C interface, so
link against the major version your code was written for.
Utility Libraries
Peios / Developing for Peios / System Service Libraries
The Peios utility libraries let your application work with the same document formats as the command-line tools. You can import a registry document, show configuration help, or look up an event description without starting another process or interpreting terminal output.
Choosing a library #
| Library | Purpose | Reference |
|---|---|---|
libreg | Parse, export, and apply registry batch documents | libreg(3) |
libregman | Parse and search registry manuals | libregman(3) |
libevman | Parse, check, and search event catalogs | libevman(3) |
Each library has a C interface and a safe Rust wrapper. The runtime package provides a shared library; its matching development package provides headers and linking information. The libraries share Peiosutils release versions, while their ABI major identifies the compatible C interface.
Parsing a registry document doesn't change the registry. Applying it is a separate operation that uses the caller's access token. A document that parses successfully can still fail validation or access checks when applied.
Manual and event parsers can return usable records alongside diagnostics. Check both: a successful library operation doesn't mean every source record is valid. This lets an editor display the valid content and explain problems in the same view.
Ownership across language boundaries #
A C operation returns a handle that owns its result or its error. Check the error accessor, then read the result. Free the handle on either path. Views returned by the library borrow that handle, so copy anything you need to retain before freeing it.
The Rust wrappers manage these handles automatically. Registry-manual records and event-query matches are owned Rust values. A registry document keeps its library handle alive while you borrow its JSON representation.
The C interfaces accept pointer-and-length spans rather than terminated strings. This preserves the difference between an absent optional value and an explicitly empty one. Text is UTF-8; filesystem paths in the manual and event libraries retain their original Unix bytes.
Moving from the earlier Rust crates #
Use peios-reg, peios-regman, and peios-evman for application code. They
call the corresponding shared library. The earlier Rust-only crates exposed
implementation types directly; changing only a dependency name doesn't adapt
those types to the new ownership model.
The implementation crates registry-docs, registry-manual, and
event-catalogue are internal to Peiosutils. Keep application integrations on
the public wrappers or C interfaces so an implementation change doesn't
require a matching change in every consumer.
Using libresolvd
Peios / Developing for Peios / System Service Libraries
libresolvd.so.1 provides the public C interface for resolvd. The
resolvd-client crate wraps the same shared library and returns owned Rust
values. Internal implementation crates do not replace this public boundary.
Operations #
The library reads resolver status, looks up addresses, resolves DNS record types, performs reverse lookups, and flushes the cache. Replies retain their source, interface, and server information. A successful library exchange can still contain a DNS failure outcome; check the typed answer before using its records. Flushing requires the caller's existing control permission.
The shared library is libresolvd.so.1. It is separate from the platform's
libresolv library and from libnss_peios_net.so.2, which provides the glibc
name-service interface. Applications do not link the NSS module directly.
Linking and ownership #
Include <peios/resolvd.h> and use the resolvd pkg-config module. The
installed header and libresolvd(3) describe individual functions and data
layouts. peios_resolvd_abi_version() returns the ABI major version, 1.
Each operation returns an owned result, including failures. Check
peios_resolvd_result_error() before reading a view, and release the result
exactly once with peios_resolvd_result_free(). Error codes are POSIX
numbers;
human-readable diagnostic wording is not a stable identifier. Reading the
stored error does not set thread-local errno.
Strings are UTF-8 spans with explicit byte lengths, without terminating NUL bytes. Input spans are borrowed for the call and must remain live, aligned, and initialized. A null pointer with zero length represents absent optional text; a non-null pointer with zero length represents present empty text. Returned strings, arrays, and nested views belong to the result. Copy what you need before freeing it. Handles from another library are not valid here.
Connections and failure #
Each ordinary daemon operation opens its own filesystem Unix socket. The
system default is /run/resolvd/resolv.sock; clients can select another
socket for a
private service instance or a test.
A positive timeout in milliseconds bounds connection, sending, and receiving together. A full connection queue can fail immediately. A transport error does not establish whether a requested change was applied. The library does not automatically replay operations after an uncertain failure.
Rust access #
Use Client::system(Duration) for the installed daemon or
Client::new(path, Duration) for an explicit socket. The wrapper copies
result views into Rust values and releases C results through Drop.
Select a matching source revision of resolvd-client and link the installed
shared library; the crate is not a precompiled Rust ABI package.
Using libtimed
Peios / Developing for Peios / System Service Libraries
libtimed.so.1 provides the public C interface for timed. The
timed-client crate wraps the same shared library and returns owned Rust
values. Internal implementation crates do not replace this public boundary.
Operations #
The library reads status and sources, subscribes to clock snapshots, requests configuration reloads, and requests manual time changes. The daemon checks permissions and whether its operating mode allows a manual change.
Configuration helpers parse a server entry, check zone-name syntax, verify an installed zone, and read zone and country lists. Zone-name syntax alone does not establish that the zone is installed. Zone files and metadata must be regular files of at most 16 MiB; aliases to regular files are supported. Missing or unreadable metadata produces an empty list. These helpers do not change the registry or the system clock.
Linking and ownership #
Include <peios/timed.h> and use the timed pkg-config module. The
installed header and libtimed(3) describe individual functions and data
layouts. peios_timed_abi_version() returns the ABI major version, 1.
Each operation returns an owned result, including failures. Check
peios_timed_result_error() before reading a view, and release the result
exactly once with peios_timed_result_free(). Error codes are POSIX numbers;
human-readable diagnostic wording is not a stable identifier. Reading the
stored error does not set thread-local errno.
Strings are UTF-8 spans with explicit byte lengths, without terminating NUL bytes. Input spans are borrowed for the call and must remain live, aligned, and initialized. A null pointer with zero length represents absent optional text; a non-null pointer with zero length represents present empty text. Returned strings, arrays, and nested views belong to the result. Copy what you need before freeing it. Handles from another library are not valid here.
Connections and failure #
Each ordinary daemon operation opens its own filesystem Unix socket. The
system default is /run/timed/time.sock; clients can select another socket
for a
private service instance or a test.
A positive timeout in milliseconds bounds connection, sending, and receiving together. A full connection queue can fail immediately. A transport error does not establish whether a requested change was applied. The library does not automatically replay operations after an uncertain failure.
Rust access #
Use Client::system(Duration) for the installed daemon or
Client::new(path, Duration) for an explicit socket. The wrapper copies
result views into Rust values and releases C results through Drop.
Select a matching source revision of timed-client and link the installed
shared library; the crate is not a precompiled Rust ABI package.
Subscriptions #
A subscription is owned separately from each returned snapshot. Calls and freeing on one subscription must not overlap. A receive timeout retains partial framing so a later call can continue. Other transport or protocol errors close the stream; create a new subscription explicitly if needed. The Rust wrapper requires mutable access to receive the next snapshot.
Using libtrust
Peios / Developing for Peios / System Service Libraries
libtrust.so.1 provides the public C interface for trustd. The
trust-client crate wraps the same shared library and returns owned Rust
values. Internal implementation crates do not replace this public boundary.
Operations #
The library reads status and complete root snapshots, subscribes to changes, and requests recomposition. Snapshot chunks must belong to one generation; the library rejects incomplete or mixed-generation results.
Certificate helpers decode, inspect, and vet candidate roots. Decoding or
inspecting a certificate does not make it trusted. Other helpers need no
daemon: they compute a certificate's SHA-256 fingerprint, convert between
DER and PEM, normalize a fingerprint as typed, and resolve a whole
fingerprint or an unambiguous prefix of at least eight digits against a
list of fingerprints. peios_trust_default_control_security() returns the
descriptor trustd checks against when the ControlSecurity value is
absent. Management operations add
or remove registry entries, record or remove distrust, and configure
compatibility output using the caller's own rights. An access probe is not
an authority token: the actual operation can still fail.
Registry writes and daemon recomposition are separate operations. Request a reload after management changes when immediate recomposition is required, and handle either operation's error. A failed reload does not roll back a completed registry write.
Linking and ownership #
Include <peios/trust.h> and use the trust pkg-config module. The
installed header and libtrust(3) describe individual functions and data
layouts. peios_trust_abi_version() returns the ABI major version, 1.
Each operation returns an owned result, including failures. Check
peios_trust_result_error() before reading a view, and release the result
exactly once with peios_trust_result_free(). Error codes are POSIX numbers;
human-readable diagnostic wording is not a stable identifier. Reading the
stored error does not set thread-local errno.
peios_trust_result_failure() gives the kind of failure, which is also
stable:
| Constant | Failure |
|---|---|
PEIOS_TRUST_FAILURE_NONE | The operation succeeded |
PEIOS_TRUST_FAILURE_OTHER | Any other failure, such as an unreachable daemon or an ambiguous prefix |
PEIOS_TRUST_FAILURE_DENIED | The caller's rights refused the change |
PEIOS_TRUST_FAILURE_NOT_FOUND | No such root, addition, distrust entry, or matching fingerprint |
PEIOS_TRUST_FAILURE_MALFORMED | The bytes are not a certificate |
PEIOS_TRUST_FAILURE_NOT_A_CA | The certificate is not a certificate authority's |
PEIOS_TRUST_FAILURE_EXPIRED | The certificate has expired |
PEIOS_TRUST_FAILURE_NO_CERTIFICATE | PEM text holds no certificate block |
Strings are UTF-8 spans with explicit byte lengths, without terminating NUL bytes. Input spans are borrowed for the call and must remain live, aligned, and initialized. A null pointer with zero length represents absent optional text; a non-null pointer with zero length represents present empty text. Returned strings, arrays, and nested views belong to the result. Copy what you need before freeing it. Handles from another library are not valid here.
Connections and failure #
Each ordinary daemon operation opens its own filesystem Unix socket. The
system default is /run/trustd/trust.sock; clients can select another socket
for a
private service instance or a test.
A positive timeout in milliseconds bounds connection, sending, and receiving together. A full connection queue can fail immediately. A transport error does not establish whether a requested change was applied. The library does not automatically replay operations after an uncertain failure.
Rust access #
Use Client::system(Duration) for the installed daemon or
Client::new(path, Duration) for an explicit socket. The wrapper copies
result views into Rust values and releases C results through Drop. Its
Error carries the POSIX code, the failure's kind as an ErrorKind,
and the diagnostic message. The crate also exports the registry key and
value names trustd reads, and the certificate Details and Parsed types.
Select a matching source revision of trust-client and link the installed
shared library; the crate is not a precompiled Rust ABI package.
Subscriptions #
A subscription is owned separately from each returned snapshot. Calls and freeing on one subscription must not overlap. A receive timeout retains partial framing so a later call can continue. Other transport or protocol errors close the stream; create a new subscription explicitly if needed. The Rust wrapper requires mutable access to receive the next snapshot.
Reading Registry Documents
Peios / Developing for Peios / System Service Libraries
Use libreg to read a registry batch document without applying it. This is
useful for an importer that shows a document before asking the user to apply
its changes.
Before you start #
- Install matching
libregandlibreg-develpackages. - Install a C compiler and
pkg-config. - Supply a UTF-8 JSON document in the registry batch format.
Parse the document #
-
Include
peios/reg.hand create a span containing the JSON bytes. This example uses an empty batch, so it needs no live registry access:int -
Save the example as
read-document.c, then compile it against the installed library:
Check the result #
Run ./read-document. It prints the empty batch and exits successfully:
The handle owns the returned JSON bytes. The example writes them before freeing the handle. For an application that retains the document in another format, copy those bytes while the handle is still alive.
See libreg(3) for export, apply, errors, and lifetime requirements. Parsing
alone doesn't check whether you have permission to apply a document.
Using Cryptography from Rust
Peios / Developing for Peios / Cryptography
Use the peios-crypto crate whenever Peios-authored Rust code needs
cryptography. It offers keys, signatures, passphrase sealing for keys at
rest, and the building blocks of random bytes, SHA-2 digests and HMAC.
The crate's choices are deliberately limited. You pick from a short list of
key types and signature schemes rather than supplying parameters, so a
weak or mismatched combination can't be expressed. Secret bytes are wiped
from memory when dropped and never appear in Debug output.
Before you start #
- Add
peios-cryptofrom the peios-rs repository to yourCargo.toml. - Handle
Error::PolicyRejected. Peios crypto policy can refuse an algorithm on a particular machine. peios-crypto 0.1 doesn't enforce the policy and never returns this error; versions that enforce it keep the same API.
Generate a key and sign #
-
Generate a key with one of the
KeyAlgorithmchoices:use ; let key = generate?; -
Sign with the key's default scheme. Each key type has one that suits it, so you don't need to choose a hash or padding:
let scheme = key.algorithm.default_signature_scheme; let signature = key.sign?; -
Give the public key to whoever verifies, as a DER
SubjectPublicKeyInfo:let spki = key.public_key.spki;
Write code that signs against the Signer trait rather than PrivateKey.
A key held in hardware implements the same trait, so the code works
unchanged when the key moves out of process memory.
Verify a signature #
Load the public key and verify with the scheme the signer used:
use ;
let public = from_spki?;
public.verify?;
PublicKey::from_spki accepts only the canonical DER encoding of a key
type Peios offers. A bare RSA key, a raw EC point or a compressed point is
refused with Error::InvalidKey.
Verify a signature made by other software #
Signatures from other software, such as the signature on a certificate
request, come in more combinations than Peios makes itself. OpenSSL, for
example, signs with SHA-256 whatever the curve. Use VerifyingKey for
these:
use Algorithm as Hash;
use ;
let key = from_spki?;
key.verify?;
VerifyingKey accepts ECDSA P-256 and P-384 keys, with compressed points,
and RSA keys from 2048 to 8192 bits. Any SHA-2 hash can be used with
either curve. RSA-PSS signatures verify only when their salt is as long as
their hash. SHA-1 isn't offered.
A VerifyingKey can only verify. To sign, use a PrivateKey.
Protect a private key at rest #
Seal the key's PKCS #8 encoding under a passphrase, and store the result:
use ;
let pkcs8 = key.to_pkcs8?;
let sealed = seal_with_passphrase?;
To use the key again, open the blob and load it:
let pkcs8 = open_with_passphrase?;
let key = from_pkcs8?;
Sealing derives a key from the passphrase with Argon2id, using 64 MiB of memory, and encrypts with AES-256-GCM. The work makes each guess of the passphrase expensive, but it can't make a weak passphrase strong. The crate sets no minimum, so check the passphrase's strength in your program before sealing anything valuable, such as a certificate authority's key.
Keep passphrases in a Secret too, as these examples do, so that they're
wiped from memory when you're finished with them.
Export a key with its certificates #
To hand a key and its certificate chain to other software, such as a phone or a Windows machine, write them as a PKCS #12 file:
use pkcs12;
let p12 = write?;
The file uses the format OpenSSL 3 writes by default: AES-256 encryption under keys derived with PBKDF2-HMAC-SHA256, and an HMAC-SHA256 check over the whole file. Current OpenSSL, Windows 10 version 1709 and later, Firefox, iOS 18 and later, and macOS 15 and later can import it. Older Apple systems need a weaker legacy format, which peios-crypto doesn't write.
The certificate has to be the key's own, and the passphrase can't be
empty; otherwise pkcs12::write returns Error::InvalidInput.
Check the result #
Opening a sealed blob with the wrong passphrase fails with
Error::WrongPassphraseOrDamaged. That error also covers a blob that was
altered or damaged, deliberately: distinguishing the two would help someone
guessing passphrases more than it helps you.
See also #
Using the OpenSSL-Compatible Libraries
Peios / Developing for Peios / Cryptography
Peios provides cryptography and TLS through two libraries with OpenSSL's API: libpcrypto, for cryptography, and libpssl, for TLS. Software written for OpenSSL builds against them with its source unchanged, and Rust crates built on aws-lc-rs, such as rustls, can use them in place of a copy of their own.
Both libraries are built from AWS-LC, Amazon's cryptography library, and provide the API AWS-LC does. They link AWS-LC in and export each function under its OpenSSL name, so that every call a program makes passes through one place where Peios can apply its crypto policy.
For new Rust code written for Peios, use the peios-crypto crate instead;
see Using Cryptography from Rust.
Before you start #
- Build libpcrypto and libpssl from the peios-crypto repository with
pekit build pcrypto, and install the tree it gives under/usr. Peios doesn't ship them as a package yet. - Install libpeios, which libpcrypto loads to read the machine's crypto
policy. A static link needs
-lpeios, which pkg-config's--staticgives. A cross linker needs-Wl,-rpath-linkto the directory holdinglibpeios.so.0. - Install a C compiler and pkg-config.
- Expect Peios crypto policy to apply to these libraries' callers. The
current libraries apply it when a program computes a digest or a MAC
(HMAC, CMAC, Poly1305, or SipHash), starts or keys a cipher or an AEAD,
derives a key, encrypts or decrypts a private key, PEM file, PKCS #12
file or PKCS #7 message, generates or uses a public key, verifies a
signature in a certificate, OCSP response or PKCS #7 message, or
finishes a TLS handshake. Data that names its own algorithm, such as an
encrypted PKCS #12 file, is checked as it's read, before it's
decrypted. Each process applies the machine's crypto policy, which it
reads once, at its first call: its floor, which no machine can loosen,
its thresholds, and the exceptions granted to the program. See
How Crypto Policy Works.
Two calls still go straight to AWS-LC:
EVP_CIPHER_CTX_set_key_lengthandEVP_CIPHER_CTX_ctrl, which can change a cipher's key length or parameters after the cipher was checked. - Expect TLS to be checked once each handshake has negotiated, before any
data is sent or received on it: its version, cipher suite, key-exchange
group, keys, signatures, and the peer's certificate chain. If policy
refuses any of them, the connection fails with an
insufficient_securityalert, as if the handshake itself had failed, and every later call on it fails too. A call such asSSL_writethat runs the handshake itself checks it before sending anything. TLS 1.3's early data isn't checked: a client sends it before the handshake negotiates anything, using a session that an earlier handshake negotiated.
Build a C program #
-
Include OpenSSL's headers as usual. This program prints the library's version and the SHA-256 digest of
abc:int -
Save it as
digest.c, and compile it with the flags pkg-config gives forlibcrypto:For a program that uses TLS, ask for
opensslinstead, which gives both libraries.
A build that links -lssl -lcrypto without asking pkg-config works too:
libssl.so and libcrypto.so lead to libpssl and libpcrypto.
Check the result #
Run the program:
It prints AWS-LC's version and the digest:
AWS-LC 5.15.0
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
Build a Rust crate that uses aws-lc-rs #
aws-lc-rs normally compiles its own copy of AWS-LC. Set
AWS_LC_SYS_SYSTEM_DIR when you build, and it uses libpcrypto instead:
AWS_LC_SYS_SYSTEM_DIR=/usr
aws-lc-rs reads the Rust bindings that libpcrypto installs at
/usr/share/rust/aws_lc_bindings.rs, and links libcrypto.so. The program
it builds loads libpcrypto when it runs, and contains no AWS-LC of its own.
Differences from OpenSSL #
AWS-LC provides OpenSSL 1.1.1's API, with some of OpenSSL 3's functions, not all of OpenSSL 3. Expect to change a program that needs:
- OpenSSL 3's providers, or engines loaded by name. AWS-LC has no
providers, and its algorithms are built in. Its
ENGINEcan only stand in for RSA and EC key operations, with methods the program supplies. - A newer OpenSSL version. libpcrypto reports version 1.1.1 to
pkg-config and in
OPENSSL_VERSION_NUMBER, so a build that insists on OpenSSL 3 refuses it. - Elliptic curves of your own. A key on a curve given by its parameters is accepted only if the curve is one of the named curves AWS-LC provides, such as P-256; any other curve is refused.
PKCS12_create's defaults. AWS-LC encrypts a PKCS #12 file's certificates with 40-bit RC2 unless told otherwise, and Peios crypto policy refuses it. Pass -1 ascert_nidto leave the certificates, which are public, unencrypted. Files that other software encrypted this way still read.
AWS-LC's porting documents, in its repository's docs/porting directory,
list the functions it leaves out and those that behave differently.
A call that Peios crypto policy refuses fails as any failed OpenSSL call
does, and leaves an error on the thread's error queue whose library is
ERR_LIB_USER and whose reason is 1000. Reading the policy and reporting
to cryptod leave errno as they found it.
A few functions can't report failure, or have callers that never check:
the low-level digest functions, such as SHA256 and MD5_Init, the
low-level cipher keying functions, such as AES_set_encrypt_key, and
Poly1305's and SipHash's. When policy refuses one of those, the program
ends with a message naming the function, rather than carry on with a
digest or key that was never computed. Use the EVP_ functions where a
refusal should be handled.
The libraries export only the API AWS-LC's headers declare. Functions
AWS-LC exports only for its own tests, such as its ML-KEM internals, aren't
available. Use only OpenSSL's names: libpcrypto also exports names
beginning peios_awslc_, which libpssl uses internally. They aren't part
of the API, and a program that calls them won't pass Peios crypto policy.
The GXWI Application Model
Peios / Developing for Peios / GXWI Applications
A GXWI application runs on the Peios machine and presents surfaces through
the desktop. It connects to the display named by GXWI_DISPLAY; it does
not expose an independent public listening port.
Three layers #
The SDK has distinct responsibilities:
| Layer | Responsibility |
|---|---|
libgxwi.so | C interface for desktop connections and surface requests |
Rust gxwi crate | Application HTTP service, rendering, and settings helpers |
| Compositor | Desktop layout, browser presentation, and shell authorization |
Use the C interface when integrating another language or a custom runtime. Use the Rust rendering layer for process-owned HTML surfaces. The shared library does not implement the Rust rendering helpers.
State belongs to the application #
A live surface owns its application state and named input fields in the process. Browsers receive renderings of that state. Multiple browsers can interact with the same surface, and reconnecting browsers receive its latest state.
This is not automatic persistence across application failure or session shutdown. Save durable data explicitly. Keep focus, viewport geometry, and other device-specific presentation out of shared application state.
Surfaces and requests #
An application can present windows and dialogs. Shell programs can also use panels, backgrounds, and overlay surfaces where the compositor permits those roles. Merely requesting a role or obtaining an SDK shell handle does not grant shell authority.
Closing a live surface is a request to the application. The application can ask about unsaved work before allowing the close. Closing the last surface ends the application's desktop loop.
Trust the operation, not the markup #
Treat events and field values as untrusted input. Validate actions in the
process and rely on the backend's authorization checks. Escape untrusted
text before placing it in HTML. The Rust escape helper handles text
escaping; it does not validate URLs or authorize operations.
Launching files #
Application::command returns a result when adding a file argument. The
desktop startup protocol carries UTF-8 text, so a native filename that is
not valid UTF-8 cannot be represented in that request. The SDK returns an
error instead of replacing bytes and opening a different path. Show the
error and keep the original native path intact.
Application declarations #
The application catalog accepts regular declaration files up to 64 KiB. It checks the opened descriptor and bounds the actual read, so a file that grows beyond the limit is rejected. A declaration at the exact limit is accepted if its content is valid. Special files are not declarations.
Executable icon probes also require an opened regular file. These checks prevent catalog discovery from treating a pipe or device as a normal file. They do not replace validation of the declaration's fields.
Live Surfaces and Input
Peios / Developing for Peios / GXWI Applications
Implement the Rust Live trait to draw a surface from application state.
render returns HTML. event handles named actions, input responds to
field changes, and closing decides whether a close request can proceed.
Rendering and actions #
App::live creates a window and returns a Surface handle. Use
Surface::update to change state from a worker and request another render.
Use Surface::look to inspect the application, fields, and surface facts
under their shared state lock.
An element's fx-click attribute names an action. Attributes beginning
with fx-value- provide action data. A form with fx-submit names its
submission action. The browser protocol is implemented by the compositor;
adding arbitrary HTML event attributes does not create a Rust callback.
Keep rendering free of irreversible effects. A browser reconnect or field change can cause another render. Put effects in explicit action handlers and background operations.
Named fields #
Fields stores values for named inputs. Fields::get returns an empty
string for an absent field. Fields::set changes a field from the process
and updates connected views, including a view editing that field.
The browser input path accepts at most 256 fields. Each value is limited to 1 MiB, their total to 4 MiB, and each name to 256 bytes. These are transport limits, not application-specific validation rules. Validate lengths and formats required by the operation itself.
Do not use the field transport for files larger than its limits. A custom bounded HTTP route can serve a different data-transfer requirement.
Shared edits #
Multiple views share field values. They do not form an independent draft per browser. Design conflict-sensitive operations around explicit state, revisions, or confirmation rather than assuming only one viewer edits a surface.
The surface state lock serializes its callbacks. Avoid blocking operations inside rendering or a callback that must keep the interface responsive. Move long work to a worker and publish progress through the surface handle.
Closing #
Return false from closing to keep a surface while asking about unsaved
work. Once the user confirms, use the surface or closer handle to close it.
A process failure or ended desktop session is not an interactive close
request, so save durable data independently of this callback.
Building a Settings Application
Peios / Developing for Peios / GXWI Applications
The Rust gxwi::settings module builds settings interfaces from HTML
helpers. It supplies layout and controls; your application owns state,
validation, backend calls, and authorization.
Before you start #
Create an application using App and implement Live for its page state.
Choose the backend operation and permissions each control needs. Use the
SDK's checked example and Rust API documentation for complete signatures.
Build the page #
- Register
settings::stylesheetwith the application before adding your own stylesheet. - Choose
settings::windowfor a page with navigation orsettings::singlefor one section without navigation. - Build navigation with stable section identifiers. Handle the
sectionevent by validating the requested identifier and selecting its page. - Assemble controls with settings helpers and named fields. Escape text that comes from users, files, or services before embedding it in HTML.
- Show the effective backend state and an actionable error when an operation fails.
The kit adapts navigation to narrow views. It does not require the process to track a browser's viewport.
Apply changes deliberately #
Use immediate application for controls such as a switch when the operation is reversible and failure can be shown clearly. Restore the displayed field if the backend refuses the change.
Use an explicit Apply action for a group of typed values that must be validated together. Validate the complete proposed state before submitting it. Rendering a success message before the backend accepts the operation misrepresents the effective configuration.
For a destructive operation, ask for confirmation and focus the safe choice. A confirmation is not authorization: the backend still checks the caller's rights.
Verify the result #
Exercise successful changes, refused access, invalid values, and backend failure. Open the same surface in two browser views and check that both reflect accepted state. Verify keyboard operation and a narrow viewport.
Custom HTTP Pages
Peios / Developing for Peios / GXWI Applications
Use a custom HTTP page when a live surface cannot represent the interface, such as a terminal renderer. The application still serves through the desktop's connection; it does not need its own public network listener.
Routes and resources #
App::routes adds application HTTP routes. App::file serves a resource,
and App::stylesheet registers a stylesheet for live surfaces. Paths are
relative to the application's routing space. Do not assume that the
application owns the browser's root path.
App::raw_page presents a scripted page. The compositor keeps that page
apart from other applications. Its browser-owned state does not
automatically reach another device or survive a tab being closed.
Isolation and keyboard access #
A raw page has no ordinary access to the desktop's cookies or browser storage. Worker code uses a blob where required by the isolated page's origin. Do not use the absence of storage as a substitute for validating requests in the application.
Include the compositor's key-forwarding module from .fx/keys.js within
the application's path space. Without it, desktop keyboard shortcuts can
be unavailable while focus is inside the page. The SDK's hello raw-page
example demonstrates the expected resource layout.
Lifecycle #
Closing a raw window allows it to close without the live surface's
closing decision. Keep important state in the process and implement an
explicit save or stop flow where the interface requires it.
Limit request bodies, pending work, and output queues according to the application's needs. The shared transport cannot choose an appropriate memory or cancellation policy for every application protocol.
The C Client Lifecycle
Peios / Developing for Peios / GXWI Applications
libgxwi.so.1 exposes the desktop control interface to C and other
languages with a C foreign-function interface. Include peios/gxwi.h
and link with libgxwi. The header and libgxwi(3) define exact types,
function signatures, errors, and concurrency requirements.
Connect and serve #
peios_gxwi_connect uses GXWI_DISPLAY and returns an owned opaque display
handle. The library sets Identification before connecting. It does not
adopt arbitrary caller-supplied display descriptors.
peios_gxwi_serve transfers one end of a socket to the desktop and returns
the other as a close-on-exec descriptor. Your application owns that
descriptor and serves HTTP/2 on it. Start serving before asking the desktop
to present routes from that connection.
Create live or raw surfaces with application-chosen identifiers. The C
library sends the surface description; it does not implement rendering,
HTTP handling, or the live-surface WebSocket protocol for you. The Rust
gxwi framework supplies those higher layers.
Receive and release events #
peios_gxwi_receive blocks and returns one of three results:
| Result | Meaning |
|---|---|
1 | An independently owned event is available |
0 | End of file, with a null event output |
-1 | Failure reported through errno |
Inspect an event's kind before using its typed getters. A close event
identifies an application surface. A surface-list event describes the
desktop surfaces visible to an authorized shell connection. Unknown or
malformed messages become PEIOS_GXWI_EVENT_OTHER. Truncated packet data
or descriptor control data also produces that event rather than a parsed
partial message.
Destroy each event after use. Text returned by an event getter borrows storage from that event and becomes invalid when the event is destroyed. An event remains valid after its display handle is destroyed.
Text and output ownership #
Text is UTF-8 with explicit byte lengths. No NUL terminator is required, and embedded NUL bytes are supported. A null pointer is valid for an empty span or array, not a nonempty one.
Input storage is borrowed only for the duration of the call. Output parameters remain unchanged on failure. Supply writable outputs that do not alias inputs. The library cannot make an invalid non-null pointer safe.
Shutdown and concurrent calls #
Display operations can run concurrently. Concurrent receivers consume different packets without a promised completion order. Use one receiver when your application requires a single ordered event-processing loop.
peios_gxwi_stop_listening wakes receivers with end of file and leaves
sending available. Wait until all calls using a display finish before
destroying it. Events can be read concurrently, but destruction cannot
race a reader.
Shell authority #
Program startup, desktop-surface close, and sign-out calls send requests. Successful transmission does not acknowledge that the desktop accepted or completed the action. The compositor decides whether the connection has shell authority. Observe subsequent desktop state rather than inventing a completion guarantee.
Interaction Markup
Peios / Developing for Peios / GXWI Applications
Live-surface HTML describes actions for the compositor to dispatch.
Attributes do not replace validation in the application. The Rust Live
API documentation gives the complete markup contract.
Actions and forms #
The common action attributes serve these purposes:
| Attribute | Purpose |
|---|---|
fx-click | Named activation action |
fx-dblclick | Named repeated activation action |
fx-value-* | Values associated with an action |
fx-submit | Named form submission action |
fx-autofocus | Focus target when a control appears |
fx-key | Surface-local keyboard activation |
Named input fields belong to the surface. Validate form and action values in the process before calling a backend. Escape text when generating HTML attributes as well as element content.
Keyboard and menus #
A keyboard chord uses modifiers such as Ctrl, Alt, Shift, and Meta
with a key name. Field-editing shortcuts remain field operations where
appropriate. The desktop reserves its own chords, so an application cannot
assume every chord reaches its handler.
fx-menu identifies a hidden menu element. Its action items provide
labels and values; the compositor presents the menu. A disabled item
cannot be selected through the normal interface, but its handler must
still enforce operation validity and access.
Device-local presentation #
fx-copy copies the named value to the activating device's clipboard.
This is distinct from an application-owned clipboard shared through a
session file or service.
fx-columns lets a view resize columns. fx-reorder reports a requested
reordering with a destination position. The next process rendering remains
the authority for the accepted application order.
Shell presentation #
Authorized shell surfaces can describe desktop focus, workspace, and
overlay actions. fx-focus, fx-workspace, and fx-overlay affect the
presenting device where the compositor implements them. They do not make
focus into shared process state.
fx-global-key names a desktop-wide chord for a shell control. Requesting
that attribute does not make an ordinary application a shell. The
compositor determines which program connections have that authority.
GXWI Process Boundaries
Peios / Developing for Peios / GXWI Architecture
GXWI separates privileged machine operations from network parsing.
gxwid owns the listener, certificate state, authentication connections,
and session jobs. gxwi-server handles browser traffic with a restricted
token and descriptors supplied by the daemon.
Browser to desktop #
The network worker accepts TLS and HTTP requests. It communicates with the daemon over private channels for authentication and overlay state. The daemon starts session jobs with the access token returned by authd.
A compositor receives a session socket and serves HTTP/2 over it. The network worker forwards requests for the authenticated browser session to that connection. The compositor then routes desktop and application requests inside the session.
The externally served protocol and internal transport differ. Browser connections use HTTP/1.1 over TLS. The worker-to-session connection uses HTTP/2 over a local socket.
Session credentials #
The network worker owns its session cookies. It strips GXWI authentication cookies before forwarding requests to a session and prevents application responses from replacing them. A compositor or application does not need the browser's session cookie to serve its connection.
The worker also keeps application-origin routing separate from ordinary session paths. Application-provided labels do not establish another application's authority.
Failure boundaries #
The daemon restarts a failed network worker with a bounded retry delay. Keeping the listener and desktop jobs outside that worker allows them to outlive its failure. This does not make in-flight browser requests transactional or preserve the worker's in-memory cookie table.
Session startup waits for the compositor to accept its connection within 10 seconds. A program that cannot become ready fails startup rather than leaving authentication waiting indefinitely.
Restricted and development execution #
Normal execution relies on Peios access tokens, registry access control, authd, peinit jobs, and local token transfer. A host-only unrestricted run omits those security mechanisms. It can exercise HTTP and browser code, but it cannot qualify native authentication or sandbox behavior.
The Session Environment
Peios / Developing for Peios / GXWI Architecture
GXWI starts a compositor with environment values chosen for the authenticated principal. Those values describe the session, not the browser device that happens to display it.
Identity and runtime #
The session receives these values:
| Value | Purpose |
|---|---|
HOME | Home directory from the account profile |
SHELL | Account shell |
PATH | Program search path for the session |
GXWI_RUNTIME_DIR | Session runtime directory |
GXWI_DISPLAY_NAME | Display label from the first logon profile |
The compositor exposes GXWI_DISPLAY to applications it starts. An
application should connect to that display rather than guessing a socket
path. The session runtime directory and socket are not public network
addresses.
Locale #
GXWI reads machine locale settings and the authenticated user's locale
preferences before starting the session. It clears inherited locale
overrides and falls back to C.UTF-8 where needed.
Rejoining an existing session does not restart its processes or replace their environment. Changes to locale, home, display label, or shell apply when another session is created, according to the relevant service policy.
Separate overlay runtime #
A machine overlay receives its own runtime and job. It is not the overlay account's ordinary desktop session. Its lifecycle follows the configured overlay rather than a browser visitor's sign-in.
Fenesh Implementation Boundaries
Peios / Developing for Peios / GXWI Architecture
Fenesh is a Rust application built on the gxwi crate. It renders shell
surfaces and companion windows, while the desktop service and compositor
provide session transport, authorization, and window management.
Source layout #
The implementation separates shell state from companion applications:
| Source | Responsibility |
|---|---|
src/main.rs | Connect the shell, register surfaces, and wire shared state |
src/dock.rs and src/launcher.rs | Application selection, window actions, and pins |
src/settings.rs, src/looks.rs, and src/pinned.rs | Read settings, resolve defaults, and maintain shell state |
src/watch.rs | Follow registry notifications and refresh settings |
src/wallpaper.rs | Validate image paths and bound reads shared by the shell and Settings |
src/topbar.rs, src/person.rs, and src/power.rs | Clock, display identity, and session or power controls |
src/welcome.rs | First-session welcome attempt and marker |
src/bin/fenesh-welcome.rs | Get started application |
src/bin/fenesh-settings/ | Settings controls, validation, and registry writes |
The source repository contains these files
and the manual pages under docs/man. docs/fenesh.regman owns the Fenesh
registry reference. Build and contributor instructions live in
docs/building.md, outside the published Learn tree.
Authority and untrusted input #
Fenesh runs with the desktop account's identity. Its shell role comes from Fenestra's configuration, not from a user-interface claim. Launcher and dock events resolve application IDs against the catalog before asking the desktop to start a program. Display names provide presentation only; they are not an authorization decision.
The shared wallpaper loader opens paths without waiting on named pipes and accepts only regular files, including symlinks to regular files. It checks the opened object before reading, then bounds the read to 16 MiB plus one byte for detecting overflow. It rejects oversized content, including growth after the metadata check. File extensions select the content type; this is not image decoding or sanitization.
Gallery image URLs encode each filename as one path segment before HTML
attribute escaping. Spaces, non-ASCII text, and characters such as #,
?, and % remain part of the filename instead of changing the URL.
Desktop Settings tests registry access through the registry API. It does not infer write access from group names. Writes for a single key use a transaction. Advanced changes across GXWI and Fenestra keys use separate transactions, so a later failure can leave an earlier key changed.
The power menu asks the session service to end the session and asks peinit to restart or power off the machine. Those services retain the authority to accept or refuse the request. The shell shows a refusal rather than presenting the action as completed.
Updates and defaults #
Personal settings take precedence over machine defaults where the setting supports them. Registry watchers follow the nearest existing ancestor so a missing settings key can be created later. A failed watch stops that watcher and reports the failure; it does not silently poll as a fallback. Desktop Settings separately polls every four seconds to refresh controls.
Wallpaper refresh compares the selected path, file size, and modification time after a registry notification. It does not monitor the image file. Clock and pin updates share state across shell surfaces. Focus and overlay visibility belong to each connected display, so one display's focus does not need to match another's.
The first-session marker records that the automatic welcome launch was attempted. It does not prove that the user saw or completed the window.
Fenestra Implementation Boundaries
Peios / Developing for Peios / GXWI Architecture
Fenestra separates session state from browser layout. The Rust process owns application connections and surfaces. Each desktop page receives that state and applies its window manager locally.
Source layout #
The implementation assigns these responsibilities:
| Source | Responsibility |
|---|---|
src/main.rs | Inherited listener, session startup, and compositor routes |
src/apps.rs and src/apps/shell_child.rs | Application transport, shell supervision, and peer checks |
src/surface.rs | Surface ownership, workspace assignments, and changes |
src/desktop.rs | Browser snapshots, requests, and session termination |
src/forward.rs | Forward application HTTP and WebSocket traffic |
src/live.rs | Serve the shared live-page runtime and icons |
src/settings.rs | Read and validate the shell selection |
page/fenestra.js and page/wm/tiling.js | Browser composition and local window layout |
page/sdk.js and page/keys.js | Live application interaction and raw-page keyboard forwarding |
src/bin/ | Companion taskbar and launcher |
The source repository contains the
implementation and its tests. Contributor instructions belong in
docs/building.md; installed references belong in docs/man and
docs/fenestra.regman.
Session and application boundaries #
GXWI passes a listening descriptor to Fenestra and controls access to it. Fenestra restamps the listener to the session identity. The compositor assumes that incoming session traffic has passed GXWI's authentication and routing boundary; it is not a standalone public web server.
Application connections use a Unix sequenced-packet socket in the session runtime directory. Fenestra compares the connecting account's security identifier with its own and obtains the process identity from the kernel. Shell authority is assigned only to a tracked configured child connection. Requesting a panel, background, or dialog role does not itself confer shell authority. Reaping a shell child and revoking its tracked process ID share the same admission lock, so a recycled ID cannot retain that authority.
The application supplies an HTTP/2 connection for its content. Fenestra
associates it with that application connection and a generated origin
label. GXWI's origin routing keeps pages separated. Fenestra strips
cookies from forwarded requests and Set-Cookie from application responses.
Application-origin requests cannot fall through to compositor routes.
These rules rely on the kernel, GXWI, and browser protections as well as Fenestra. Host unit tests do not establish that those boundaries work in an installed Peios session.
Live and raw pages #
A live surface uses Fenestra's page runtime to display content from the application process and return user actions. Its content security policy permits the runtime script through a response-specific nonce. The application's own scripts are not part of that live-page execution model.
A raw surface serves the application's page and scripts. Its state can be local to one browser page. The shared keyboard-forwarding helper allows that page to participate in desktop shortcuts. Fenestra treats messages from a frame according to the surface and its shell authority.
Resource bounds and failure handling #
An application connection can create at most 64 simultaneous surfaces. Application messages are limited to 64 KiB, and titles are retained up to 128 characters. A truncated application message closes the connection and removes its surfaces.
Surface resource paths start with a single /, exclude the reserved
/.fx/ prefix, and fit a total limit of 1024 UTF-8 bytes. Fenestra rejects
ASCII control characters anywhere in the supplied path. In the pathname
before the first ? or #, it also rejects literal backslashes and
segments that browsers interpret as . or ... This includes
case-insensitive %2e dots and combinations of literal and encoded dots.
Unicode names, ordinary spaces, query strings, and fragments are retained. Dots or backslashes in a query or fragment do not count as pathname traversal. The check does not recursively decode percent escapes or reject dots within longer names. A rejected resource path prevents the surface from being created and is reported without closing the app connection.
Workspace selection, renumbering, moves, and initial surface placement share one session-state lock. Concurrent browser pages cannot split those updates across inconsistent workspace states.
The desktop has up to 16 workspaces. Its change channel retains 256 messages; a lagging browser reconnects for a snapshot. A shell is sent a complete surface list on each change, so a later successful update repairs a missed list. A failed send is reported rather than treated as delivery.
Closing a surface requests cooperation from the application. Fenestra does not claim that a close request has saved work or forced a process to exit. Disconnecting the application removes its surfaces and releases their compositor state.
Animation lifetime #
The arrival animation releases its resize listener when it finishes. A canceled departure animation stops its frame loop, cancels pending timers, aborts its availability request, and releases its resize listener. Each attempt has a generation marker, so callbacks from an earlier attempt cannot update a later attempt's state or redirect its page.
A shell announcement can arrive while the compositor page is checking an address after its socket closes. The page rechecks departure ownership when that probe completes, so the active departure receives the closure instead of starting a competing reconnect path.
Writing regman Pages
Peios / Developing for Peios / Documenting Configuration
Ship a .regman fragment with your component so an operator can look up
its registry keys and values with regman. Keep the fragment beside the
code that reads those values, and update both together.
Before you start #
- Install
regmanfrom Peiosutils. - Identify the keys your component owns and the values it reads.
- Follow regman and evman prose style.
Document another component's key by referring to its full path in your record's body. Do not publish a second definition of that key.
Write a fragment #
- Create a file named for your component, such as
exampled.regman. - Add a key record explaining the subtree, then a record for each value.
- Write a standalone summary as the first nonempty body line. Explain the effect, trade-offs, dependencies, and unusual cases in the remaining body.
This example describes an illustrative spooler and its queue limit:
--- machine\system\exampled
canonical: Machine\System\Exampled
Tuning parameters for the Exampled spooler.
--- machine\system\exampled maxqueuedepth
canonical: Machine\System\Exampled MaxQueueDepth
type: REG_DWORD
default: 1024
valid: 16–65536
applies: restart
Maximum number of jobs held in the spool queue before submissions are rejected.
Increase the limit to absorb longer bursts. Each queued job consumes memory.
The spooler reads this value when it starts.
The fence starts a record. Header lines continue until the first blank
line, and the body continues until the next fence. canonical supplies the
human-readable registry path and, for a value, its name after a space.
regman fmt derives the anchor from this header through Unicode simple
case folding. Do not maintain the folded anchor by hand.
A record with any type, default, valid, or applies header is a value
record. Supply all four for a useful value description. A record without
those headers describes a key. deprecated adds a deprecation notice;
explain the replacement and its limitations in the body.
Header names are case-insensitive, and surrounding whitespace is trimmed.
Unknown headers are ignored, so a typo can silently remove information.
A record without canonical is invalid and cannot provide a lookup result.
Check the rendered record as well as the lint result.
Format and check #
-
Format and lint the fragment:
-
Preview it from the directory containing only the fragments under review:
REGMAN_DIR="" REGMAN_DIR="" -
Compare every header with the implementation. Confirm the allowed type, bounds, behavior when absent, and point at which a changed value takes effect.
Formatting updates anchors without rewriting the body, preamble, or line endings. Running it twice should produce the same file. Lint checks record structure and anchors; it cannot prove that the program implements the prose.
default describes the component's behavior, not the value on the machine
running regman. Use live, restart, or reboot for applies, with a
short parenthetical qualification when needed.
Package the fragment #
- Include
exampled.regmanin the package payload asusr/share/regman/exampled.regman. - Install it with the component that owns the documented keys.
- Check the installed lookup before releasing the package.
The filename stem identifies the provider in lookup results. Installation requires no registration hook. An absent documentation directory means no fragments, not a broken registry. If an installation mechanism replaces files in place, use atomic replacement so readers do not see a partial fragment.
An index is an optional lookup optimization. The reader can scan fragments when the index is absent, stale, or invalid. Do not make correctness depend on generating an index during installation.
Check the result #
The key lookup shows the subtree summary and its values. The value lookup shows its headers and body under the expected provider. A second provider for the same record indicates overlapping ownership; resolve that overlap before shipping.
For dynamic names, use Registry Documentation Patterns.
Registry Documentation Patterns
Peios / Developing for Peios / Documenting Configuration
Registry documentation patterns describe families of keys without publishing one record for every instance. Use a pattern only where the implementation accepts dynamic names; a literal record makes a fixed name easier to verify.
Match dynamic names #
In a canonical path, <name> matches one path component. <name...> matches
one or more components separated by backslashes. The label inside the brackets
explains the role to a reader; it does not constrain the matched text.
Neither pattern matches a space. The format has no escape for a literal name
that itself has this placeholder shape.
For example, Machine\Software\Example\Profiles\<profile> describes one
profile key. A pattern ending in <path...> also reaches its descendants.
Use the narrower form when the documented behavior applies to one level.
Literal matches take precedence over patterns. Among patterns, more specific matches take precedence over broader ones. Key and value lookup remain separate: a matching key record does not define all its values.
Dots do not split registry components. A value pattern such as Local.<op>
can match Local.User.Equal as well as Local.Equal. If those names have
different meanings, document the operators explicitly instead of relying on
placeholder labels to separate them.
Overlapping records from different providers remain visible. Provider order is not a mechanism for overriding another package's documentation.
Write terminal prose #
Use paragraphs, headings, bullet lists, bold, and code spans. The renderer rewraps paragraphs to terminal width. Follow the shared prose style and avoid relying on emphasis styling that a plain-text terminal cannot represent. Unmatched markup remains literal; whitespace inside an emphasis marker can prevent it from being recognized.
A line beginning with --- starts another record, even in body text. Use
*** or ___ for a horizontal separator if one is needed. Keep examples of
record fences out of a fragment's prose.
Piped output and NO_COLOR suppress terminal styling. Review both styled and
plain output when presentation carries meaning. State a warning in words;
color alone cannot communicate it.
Keep format and meaning separate #
Headers such as access or since do not extend the parser's schema. Put
required access and relevant constraints in the body, and omit historical
narrative. Unknown headers being ignored does not make them supported.
Regman does not read the live registry to validate a documented default or range. Review those claims against the consuming code, including how that code handles a missing or malformed value.
Writing evman Pages
Peios / Developing for Peios / Documenting Events
Ship an .evman fragment with each component that emits events. The fragment
defines its event types and fields so operators and consumers can interpret
the stream. The event catalog specification
owns the format and its requirements.
Before you start #
- Install
evmanfrom Peiosutils. - Identify the event types, tiers, and fields your component emits.
- Obtain the catalog fragments that define the fields your events reference.
- Follow regman and evman prose style.
Choose field definitions #
-
Search the existing vocabulary before defining a field:
-
Reuse a field when its meaning fits. Define a package-owned field under its role and package name only when the shared vocabulary lacks that meaning.
-
Keep each definition in its owning component's fragment. Other fragments carry the field by reference rather than defining it again.
A --- field record defines a field. A field: line in an event describes
its presence in that event. Two definitions of one field are an error.
Related fields can be collected in a group record with include: lines;
an event can then include the group.
Describe an event #
Create org.example.backup.evman for this illustrative backup component:
--- field object.org.example.backup.snapshot.id
type: bin.guid
The snapshot an event concerns, by the GUID the backup tool assigned it.
Stable for the life of the snapshot, including verification and deletion.
--- event org.example.backup.snapshot.created
tier: standard
A snapshot was written, or an attempt to write one failed.
field: object.kind required
Always `file`.
field: object.file.path required
The snapshot archive.
field: object.file.size when outcome.success == true
field: object.org.example.backup.snapshot.id required
field: operation.duration required
field: outcome.success required
field: outcome.reason when outcome.success == false
values: disk-full | source-unreadable | cancelled
closed: false
Why the snapshot was not written.
field: outcome.errno optional
The first sentence of each body is its summary. Explain when an event is
emitted, when it is not, and how to interpret its fields. Use **bold** and
code spans for emphasis and literal names.
Presence is required, optional, or when followed by a condition. An
indented paragraph after a field is its event-specific explanation. That
explanation can narrow the general definition but cannot contradict it.
Use gating to describe selection of occurrences and cardinality when one
occurrence produces multiple records; follow the specification for the full
header set, including asserted and carried.
Enumeration definitions declare values and closed. String enumeration
values use kebab case. Integer enumerations pair each number with its display
name, such as 0 None | 512 Protected. Event-specific enumerations, including
outcome.reason, declare their values on the event's field entry.
Set closed: true only when consumers can rely on the set being complete.
Check the emitted values against the declaration; a parser cannot establish
that runtime behavior matches the catalog.
Validate and preview #
-
Create a disposable directory and copy the candidate fragment plus the fragments it references into it. Include
kernel.evmanfor the shared fields in this example. Do not also copy an installed version of your candidate fragment.preview_dir= -
Check the combined definitions and inspect the event:
EVMAN_DIR="" -
Repeat lint against the full intended package set before release, replacing the installed version of your fragment with the candidate. This catches duplicate definitions and incompatible names across components.
A successful lint run prints no findings. Findings identify the file, line, and catalog rule. Lint checks the declared catalog; separately test actual events for presence conditions, value ranges, tiers, and emission behavior.
Package the fragment #
Include the fragment at usr/share/evman/org.example.backup.evman in the
component's package payload. No central registration or installation hook is
needed. Removing the package removes its fragment.
The package owns the definitions throughout their lifetime. Renaming or changing their meaning can affect filters and consumers; review such changes against the event specification before publishing them.
Writing a Feature
Peios / Developing for Peios / Writing Features
A feature gives feat a repeatable way to configure installed software.
Its package supplies scripts and metadata; the operator decides when to
install, turn on, turn off, or uninstall that configuration.
Before you start #
- Install
featand the tools your scripts call. - Identify the state each phase changes and how to recover from a partial run.
- Arrange a disposable Peios test environment with the required permissions.
Define the feature #
-
Choose a name containing only ASCII letters, digits, dots, underscores, and hyphens. It must be one path component and cannot be
.or... -
Stage a directory at
usr/libexec/features/<name>in the package. The runtime view is/libexec/features/<name>. -
Add the applicable scripts and make them executable:
Script Purpose install.shPrepare the feature's persistent configuration enable.shMake the prepared feature active disable.shStop using the feature while retaining prepared state uninstall.shRemove the feature's configuration
A missing phase script is a successful no-op. Do not omit a script if that would leave state that the reverse phase needs to remove. Each script needs a shebang naming an interpreter available in its execution environment.
Make phases repeatable #
feat executes each script directly, with its working directory set to the
feature directory. FEAT_NAME, FEAT_DIR, and FEAT_PHASE identify the
invocation. Scripts run with the caller's authority; feat does not grant
them extra privileges.
A failed phase can leave some of its changes applied. A retry starts the
script again, and feat does not roll back those earlier changes. Check the
existing state before each operation and tolerate already completed work.
Reverse phases also need to handle partially completed forward phases.
Keep output brief and identify the operation that is progressing. Write errors to standard error and return a nonzero status on failure. A failed or interrupted phase is not a completed transition.
In driven operation, standard input is closed and output is forwarded from both streams. Do not require interactive prompts. In ordinary operation, scripts inherit the terminal streams, but the same noninteractive contract keeps the feature usable through graphical clients.
Add descriptive metadata #
Create an optional feature.toml beside the scripts:
= "Example Service"
= """
Prepares the Example service and makes it available at boot.
Turning the feature off retains its configuration.
"""
The title falls back to the directory name. The description can contain paragraphs. Unknown keys do not run code or add lifecycle behavior. Invalid metadata produces a warning without making the feature disappear from the list, so check its presentation before shipping.
Package and check #
- Include the directory, metadata, and executable scripts in the package.
A
feat-<name>package name is a convention, not the runtime lookup key. - Declare dependencies on
feat, the script interpreters, and invoked tools. - In the disposable environment, exercise the lifecycle and repeat each applicable phase. Inject failures between operations and verify recovery.
- Check that turning the feature off and uninstalling it also work after a partial attempt.
Installing the package makes the feature available; it does not activate the feature. For operator commands and state handling, see Managing Features.
Identity and Service Adapters
Peios / Developing for Peios / Porting Software
A familiar library interface does not imply the same configuration source as another Linux distribution. Peios connects account lookup, hostname lookup, and certificate trust to their owning services.
Account lookup and authentication #
The authd NSS adapter translates
POSIX account queries into the authority's identity protocol. Peios' libc
package fixes the account providers; it does not use an /etc/passwd
fallback or an independently configured source order. Shadow queries do not
expose credential verifiers.
UID 0 is the numeric projection of SYSTEM, not an account named root that
must be looked up before boot can proceed. Native authorization uses tokens
and security identifiers. A numeric name-service record is a compatibility
view rather than the complete security state.
Authentication uses authd conversations. Applications integrate with that interface instead of configuring a PAM stack. Account lookup and credential verification remain separate operations.
Hostname lookup #
The network name-service provider sends hostname queries to
resolvd. Static names and resolver policy
belong to that service's configuration. Editing a separate /etc/hosts file
or a files dns provider chain does not configure Peios' fixed host lookup
path.
This does not make every libc database fixed. Consult the libc package for databases outside the account and hostname integration before assuming the same behavior.
Certificate trust #
trustd combines supplied certificate roots with machine trust decisions and produces the compatibility files consumed by TLS libraries. Those files are generated output, even where their paths match another distribution.
Use the trust service's supported configuration for an enduring change. Adding a certificate directly to a generated file can be undone by the next refresh. Permission to modify trust policy is separate from permission to read the resulting certificate bundle.
Porting Identity and IPC
Peios / Developing for Peios / Porting Software
Review authority decisions separately from compatibility display. Peios exposes Linux UIDs, GIDs, mode bits, and capability interfaces so programs can operate, but those values do not describe the full security token or descriptor.
Replace credential assumptions #
Do not authorize a request solely because geteuid() or SO_PEERCRED reports
zero. A numeric projection omits claims, groups, privileges, restrictions,
impersonation level, and process trust. Cosmetic credentials can also differ
from the token. Name-service lookup helps display identities; it does not
create or authenticate them.
Do not treat successful setuid() as a privilege drop. Without the relevant
Peios privilege it is a silent no-op; the privileged identity-swap path is
unimplemented and fails. Setuid-bit exec has different cosmetic behavior.
Use a correctly scoped service token or the supported token API, and verify
the effective identity. The setuid
reference
also covers setfsuid, access, exec, and the absence of a general uid0
helper.
The kernel neutralizes conflicting Linux DAC decisions through its capability switchboard. Some capabilities are allowed for compatibility, some map to Peios privileges, and some are denied. The displayed capability mask is not an independent source of authority. Removing Linux capabilities or assigning file capability xattrs is not a substitute for controlling Peios token privileges.
Filesystem-facing projected identity also matters to quotas, remote servers, and stacking filesystems. Preserve that distinction when diagnosing a local success followed by a remote refusal. Peios does not make a remote server understand a local descriptor automatically.
Choose a channel with the required identity #
| Channel | Identity and authority boundary |
|---|---|
| Unix stream or seqpacket socket | Native peer-token transport can bind local identity to the connection and conveyed requests. |
| Unix datagram | Identity is conveyed per message; do not use a connection register as its substitute. |
| TCP, UDP, or VSOCK | No local kernel attestation of the remote principal, including loopback IP traffic. Use an explicit authentication protocol. |
| Pipe or FIFO | Bytes and descriptor/file authority; no per-request token identity. |
| System V or POSIX queue | Object permissions protect use; payload and projected notification identity do not authenticate a principal. |
| Shared memory | Mapping and handle permissions; no identity attached to each memory write. |
| Netlink | Kernel-bound operations use the kernel's sender/opener checks; this is not a generic peer-token channel. |
A FIFO cannot replace an identity-carrying request/response named-pipe API.
Use a Unix socket with the native token protocol. SCM_RIGHTS delegates a
handle; token attestation is a different contract. Bind a received request to
its received token before concurrent work changes the socket's latest peer
state. The SDK token guide
and socket identity reference
define capture, impersonation, and transport limits.
Protect objects and their names #
System V objects carry descriptors, and mode changes do not replace those descriptors. Their numeric keys, abstract socket names, and shared-memory names remain claim-on-create namespaces. Create exclusively where appropriate and treat a pre-existing name as a condition to investigate, not proof of the expected server. Prefer service-owned directories and authenticate the peer.
The System V reference defines creation policy and descriptor operations by object kind and ID. A restricted caller is not categorically refused every object created by its parent: the complete descriptor and restricting identity determine the result.
Existing descriptors and mappings can retain authority after a policy change. Replacing a name or tightening a descriptor does not remove another process's old mapping. Design revocation and shutdown explicitly rather than promising that a permissions edit retracts already-delivered data.
Keep diagnostic provenance #
Linux process accounting remains a compatibility facility, gated through its capability-to-privilege mapping. Native KMES/eventd records carry Peios identity and process correlation, subject to each producer's schema and delivery limits. Do not promise that every Linux accounting field has a native event counterpart. Audit metadata and signal sender crumbs are observations, not credentials to reuse for authorization.
The MSIP Rust Library
Peios / Developing for Peios / Installer and Setup Conversations
The multi-surface interaction protocol (MSIP) lets one daemon drive terminal,
graphical, and automated interfaces. The msip Rust crate provides wire
framing, message structures, answer checks, and page state. It doesn't open
listeners or run an operation for you.
Use the protocol specification for the complete contract. The library is a set of helpers, not a conformance claim for an application that embeds it.
Library boundaries #
The modules divide responsibilities as follows:
| Module | Responsibility |
|---|---|
frame | Version-one framing, a 1 MiB total limit, and JSON object bodies |
msg | Typed message bodies and protocol enum encodings |
element | Common element fields and open type-specific state |
daemon | Turn sequencing, atomic updates, and structural answer checks |
surface | The outstanding page after accepted updates |
Your application owns socket permissions, peer verification, authorization, HELLO negotiation, binding order, listings, and conversation lifetime. It also owns timeouts, write serialization, bounded queues, and broadcast to attached peers. A frame's direction bit doesn't establish a valid connection state.
Daemon state #
Create a Conversation for an application-defined kind. Creation reads
128 random bits from /dev/urandom; failure returns an I/O error. The
identifier names the conversation and does not authorize attachment.
Supply a TurnSpec to issue. It assigns the next sequence number and
replaces the outstanding turn. Provide unique refs, valid state and defaults,
and only element types supported by every attached surface.
Call handle_answer for a decoded Answer. It returns stale, protocol-error,
missing-required-value, or valid results. It checks built-in value encodings
and select/table choices. Your application validates domain rules, including
string length, patterns, and whether referenced resources still exist.
Negotiated extension types also need application-specific checks.
A valid result doesn't consume the answer. Serialize checking, domain
validation, and acceptance across attached surfaces. Accept by issuing the
next turn or ending the conversation before processing another competing
answer. Reject domain validation with reject, then broadcast its Update.
Updates and attachment #
update stages an entire sparse batch before changing the stored turn.
Unknown refs or malformed fields reject the batch without partial changes.
Repeated refs fold in order, and log append entries accumulate in lines.
If a log patch also supplies lines, that explicit value replaces the
accumulated lines. Prefer one operation per patch.
update_full replaces the element list. Neither operation changes the turn
sequence. Send current_turn after a successful attachment so the surface
receives folded state without replaying earlier updates.
end marks the conversation ended and returns End for broadcast. The
embedding daemon removes it from listings and handles connection cleanup.
The library retains its final turn until the conversation is dropped.
Surface state #
Pass decoded daemon messages to Session::handle. Turn replaces the page;
Update changes it atomically. Updates for other sequence numbers are ignored.
Malformed updates and End bodies preserve the page. A valid End clears it.
The last Bound identifier remains available for displaying the result.
The session doesn't enforce greeting or binding order. Apply those checks in your connection handler before calling it. Treat names, help, and messages as text; don't execute instructions inferred from display content.
Secrets and failure handling #
Mark secret inputs, collect them without echo, and avoid retaining their
values after submission. Never put collected secrets in turn state, updates,
errors, or logs. Message and element Debug implementations do not redact
values. The library does not wipe caller-owned buffers.
A framing error can leave the stream between messages. Close the connection instead of attempting to resume decoding. A failed write can have sent a partial frame; don't retry that frame on the same stream. Configure read and write deadlines in the transport layer.
Presentation across surfaces #
Turn and element classes are optional presentation hints. The protocol carries typed content and state; it does not prescribe a daemon-controlled layout. Keep actions, required values, and validation correct when a surface ignores every class.
The installer owns its terminal renderer's
presentation behavior.
Those conventions describe msip-tui, not guarantees made by the Rust
library or by all MSIP surfaces.
Conversation Lifetime
Peios / Developing for Peios / Installer and Setup Conversations
An installer daemon keeps one live conversation in memory. A frontend connects to that conversation to show its current questions and progress. The conversation belongs to the daemon rather than to a browser tab.
flowchart LR
T[Terminal] --> D[Installer daemon]
B[Browser frontend] --> D
A[Scripted driver] --> D
D --> J[Installation or setup job]
A second client can attach to the same live conversation. Its answers affect the same state, so multiple clients are collaborators rather than isolated sessions. Starting a client is not proof that it created a fresh operation.
Disconnects and restarts #
Closing a frontend does not stop an active job. A reconnect can show the current turn while the daemon remains alive. Restarting the daemon loses the conversation; the protocol does not make an interrupted disk operation transactional or provide durable recovery.
Completed and failed conversations are cleared so a later start can create another conversation. Read and preserve a failure result before retrying. Starting again is an additional operation, not an automatic rollback.
Progress and completion #
A successful installation job reaches a result page that offers restart. The restart request and the actual disk boot are separate events. A daemon can accept a restart request without proving the firmware booted the target.
The graphical frontend retains a failed job's result until you request a
new conversation. Its log download records the job's output. msip-drive
prints a trace, but its abbreviated log display is not a complete audit
journal. See msip-drive(1) for automation constraints.
Slow clients and completion #
Each daemon connection has one writer, so complete messages remain in order. The daemon disconnects a client if queued output, including the frame being written, exceeds 4 MiB or writes make no progress for 10 seconds. A client that stops reading does not hold the conversation lock indefinitely.
At conversation completion, final messages drain outside that lock with a shared 10-second deadline. A start request during retirement receives an unavailable result. After retirement finishes, a fresh start can create the next conversation. A disconnected client must not assume that its last action failed or replay it without checking the daemon's state.
Browser input and reconnection #
The graphical frontend limits each incoming browser message and the input it admits to its shared queue. When the queue is full, submission waits for space while the browser continues receiving state updates. An oversized submission is refused with a message on the supplied page.
A stalled write to the daemon ends that connection. The page shows the lost connection while the frontend tries again. Actions queued for the old daemon connection are discarded, and browsers reconnect to fresh state. They are not automatically replayed against another conversation.
An action sent before disconnection can already have taken effect. Check the recovered page and any job result before submitting it again. Closing a tab also does not guarantee that an earlier submission was canceled. If a form is refused for exceeding the message limit, shorten its input before retrying.
The queue limit is not a limit on total process memory or the number of
connected browsers. installer-gxwi(1) and oobe-gxwi(1) specify the message
limits, queue accounting, and connection timeout.
Service Lifecycle
Peios / Developing for Peios / Installer and Setup Conversations
Installer packages carry registry seeds that define service startup. A seed is inert until an image or administrator applies it. Installing a package alone does not select the machine's setup lifecycle.
The installerd-service seed starts installerd as SYSTEM and restarts it
after failure. A restart restores a listening service, but does not recover
its previous in-memory conversation.
The oobe-service seed is intended for the installed system. It starts
oobed after the local account service and waits for its readiness signal
before starting the terminal frontend. oobed sends readiness after its
socket is bound and its browser setup has been prepared.
The terminal frontend takes /dev/console ahead of the normal sign-in
prompt. It also runs as SYSTEM in the supplied seed because the first
administrator has not yet been created. Splitting the frontend from the
engine separates responsibilities; the seed still determines authority.
On successful setup, oobed removes its service definition and the terminal
setup definition. On failure, it keeps them so another boot can retry.
Releasing the console lets the normal prompt appear even if setup failed.
Socket access #
The intended installation socket descriptor admits SYSTEM and Administrators. Setup additionally admits its temporary browser account when browser setup is offered.
Applying the descriptor is best effort: if sd is unavailable or fails,
the daemon warns and retains inherited access. A listening message does
not prove that the intended descriptor was applied. Verify the service's
runtime environment and socket protection before granting access.
Console output #
While a conversation is active, the privileged service suppresses routine kernel console messages and restores the prior setting afterward. Emergency kernel messages remain visible. Other services can still write to the console; Ctrl+L asks the terminal frontend to repaint if those messages disturb the form.
Terminal geometry #
The terminal frontend discovers its size at startup. A render area with zero width or height draws no content and leaves the conversation intact. This does not add size reporting to a serial connection: a terminal that does not report later size changes still needs its size set explicitly.
Use the nonzero dimensions accepted by the frontend's --size option when
starting with known geometry. See install-tui(1) or oobe-tui(1) for the
size-discovery fallback and repaint controls.
Rehearsing Installer Conversations
Peios / Developing for Peios / Installer and Setup Conversations
Dry-run mode exercises the installation or setup conversation without performing its disk or account operations. It helps check frontend behavior and error handling, but it does not qualify a boot medium or installed operating system.
Use a private directory reserved for the rehearsal and an explicit socket path. Daemon startup removes the existing entry at that path, binds its socket, and attempts to apply its access descriptor even in dry-run mode. Do not point a rehearsal at a production service socket.
For installation, supply a synthetic inventory as well as --dry-run.
Without an inventory, the daemon still probes the host's disk inventory.
The checked-in frontend fixtures describe invented machines; the developer
harness selects them explicitly.
A simulated phase failure can exercise an error page without damaging a filesystem. A simulated restart acknowledges the request without restarting the machine. Neither checks the real executor's cleanup, disk state, or boot behavior.
msip-drive can answer named inputs and queue actions, but it does not guard
against joining an existing conversation. It waits on progress and consumes
actions on new turns. It has no built-in deadline, and a rejected answer or
same-turn update can leave it waiting. Stopping the driver does not stop
the daemon's job.
Keep synthetic inputs and captured output in the disposable fixture.
Credentials passed through --set are exposed in process arguments; the
--set-file option avoids that exposure but still requires a protected
input file. Do not use real credentials in a rehearsal.
The repository's build guide describes its host and VM harnesses. For the
complete command interfaces, read installerd(8), oobed(8), and
msip-drive(1).
Terminal Presentation
Peios / Developing for Peios / Installer and Setup Conversations
The installer's msip-tui renderer draws pages for install-tui and
oobe-tui. Daemons supply typed elements through the multi-surface
interaction
protocol (MSIP); the renderer chooses their arrangement and appearance.
A page still needs to work when another surface ignores its presentation
hints.
Page arrangement #
Without a recognized turn class, the renderer places the heading and elements
in a column, with actions together below them. The menu class moves actions
into the body as a list. The confirm class marks the heading as a
confirmation.
Neither class changes the daemon's validation or makes an action safe to run.
The renderer checks these classes independently. Prefer one clear purpose for a turn rather than assuming that combinations define another layout. Unknown classes do not acquire behavior merely by being sent.
Progress elements render as a phase list. The first unfinished progress
element is active, and a log can use the remaining height. This follows the
element types and state; it does not require a progress turn class.
Element presentation #
| Element information | Terminal behavior |
|---|---|
An action's primary state | Accent color and bold text |
An action's destructive state | Destructive coloring, including focus |
A string's secret flag | Masked entered text |
A string's placeholder state | Dim text while the empty field is unfocused |
A table column's align: right | Right-aligned cells |
A table row's enabled: false | Dimmed row, skipped during selection |
A table row's note | A remark after its cells |
A table's empty state | Text shown when it has no rows |
An element's help | Context explaining the element or why it is unavailable |
An element's error | An error below the element until cleared |
Masking is a display property. It does not make logging, debug formatting, or retaining a submitted secret safe. Follow the MSIP library's secret handling guidance and keep secrets out of turn updates and diagnostics.
A primary action's appearance does not authorize unattended execution. Choose explicit actions in automation. A destructive action is not given extra validation by its color; the daemon owns confirmation and authorization.
Focus and narrow terminals #
Unavailable input elements can take focus, allowing a person to discover
why they cannot answer them. Supply useful help, such as the missing
prerequisite. Initial focus favors the first answerable element, with the
primary action used where appropriate.
Fields reserve space for their note so moving focus does not shift the page. Errors remain visible. Help appears when the element is focused or unavailable. Table selection skips unavailable rows, and the answer validator also rejects them; dimming alone is not the enforcement mechanism.
Tables drop columns from the right when space is limited. Put the column needed to identify a row first, and test narrow terminal widths.
Leaving and automation #
Esc opens the surface's leave question. Its wording depends on the frontend: leaving an ongoing installation differs from leaving initial account setup. A daemon page cannot override that lifecycle meaning with a presentation class.
msip-drive does not draw the terminal layout. Its scripted answers rely on
refs, values, and actions rather than color or class hints. Use
Installer Conversation Rehearsals
to check that the same conversation remains usable through automation.
Packages
Peios / Developing for Peios / Packaging Software
A package is how software is shipped on Peios: a set of files, symbolic
links, and directories with a name, a version, and an architecture. ppk
stores a package as a list of its paths and the content of each file, and
names every piece by a hash of its content. That design explains why a
packed version can never change and why files shared between packages take
no extra space.
Manifests and blobs #
A package has two kinds of part:
- Blobs. A blob is the content of one file, named by its SHA-256 hash. It doesn't record the file's path or name.
- The manifest. A manifest names the package and lists every path in it. Each path is a file, given by its blob and whether it is executable; a symbolic link, given by its target; or an empty directory.
A directory that contains anything is implied by its contents, so the manifest lists only empty ones, and those with security metadata of their own. Of a file's permissions, the manifest keeps only whether it is executable.
The manifest for a package holding one program and one document looks like this:
= "dev.peios.hello"
= "1.0-1"
= "noarch"
[]
= { = "sha256:de7a5d81f4ab0680f55966b56e7bebfd5da26f4f45d8cd6e2e22c6a0e523c37f", = true }
= { = "sha256:c90139667a35e240080ae250c1f99a5df3a6d509b0aa65b3d5550f87e20cb3a4" }
Paths are relative to /usr, where everything Peios ships lives, including
the configuration it ships in /usr/etc. This package's bin/hello is
/usr/bin/hello. A package can't ship anything outside /usr: a machine's
own configuration and state live outside it, and stay the machine's. An
absolute symbolic link target is read from the root of the system, so a
link to /usr/lib/libz.so.1 names a file in the same or another package.
A package's identity #
A package's identity is the SHA-256 hash of its manifest, written as
sha256: followed by the hash in hexadecimal. The manifest names every
blob by its hash, so the identity covers the content of every file as well
as the paths, names, and versions.
ppk writes a manifest in exactly one way: entries in a fixed order, with
fixed spacing and quoting. The same directory therefore always produces the
same manifest and the same identity. You can rebuild a package and compare
identities to check that the result is identical.
Package identifiers #
You name a package with an identifier of this form:
<name>@<version>[?arch=<arch>]
<name> and <version> are the package's name and version. <arch> is
the processor architecture its content is built for, such as x86_64 or
aarch64. Use noarch for a package whose content runs anywhere, such as
documentation or scripts.
If you leave out ?arch=, the architecture is the one ppk itself was
built for. Give it explicitly for any package built for another machine,
and always for noarch packages. The characters an architecture can
contain are listed in ppk(1).
Package names #
A package's name is reverse-DNS: the domain of whoever owns the software,
backwards, then the product. ppk refuses any other name, wherever one
reaches it, including in a fetched manifest.
| Software | Name | Example |
|---|---|---|
| Peios's own | dev.peios.<product> | dev.peios.hello |
| A testing-only Peios product | dev.peios.testing.<product> | dev.peios.testing.fixture |
| Anyone else's | The upstream project's domain | org.gnu.bash, io.github.eudev-project.eudev |
| Part of a split package | The complete name of the base, with a suffix | org.gnu.glibc-devel |
Use the upstream project's own domain for software that Peios only packages. A name doesn't rename anything: a program keeps its own executable, service, and other externally defined names.
A name has at least three labels, separated by dots, and at most 64
characters. Each label holds lowercase ASCII letters, digits, +, and -,
starts with a letter or digit, ends with a letter, digit, or +, and has no
--. The first label holds only letters, as a top-level domain does, and
neither of the first two holds a +.
ppk can only check a name's form. It can't tell whether a domain is the
right one for the software, or whether a split keeps its base's name, so
those are for whoever writes the package.
Package versions #
A version has three parts, written [<epoch>:]<upstream>-<revision>:
- Upstream version. The version the software's own project gave it,
such as
2.44or1.0-rc.1. It holds ASCII letters, digits,.,+,-, and~, and starts with a letter or digit. - Revision. Which packaging of that upstream version this is, starting
at
1. Pack a new revision when the package changes but the software doesn't. Every version has one:2.44-1, never2.44. - Epoch. An optional number before a colon, as in
1:0.5-1, that's raised only when an upstream project's versions go backwards, so that the new ones sort after the old.
Versions sort by epoch, then upstream version, then revision. Upstream
versions compare a run of digits or letters at a time, with digits as
numbers, so 2.10 comes after 2.9. A pre-release sorts before its
release: anything after a ~, and dev, alpha or a, beta or b,
pre, and rc, in that order, so 1.0~rc1-1 and 1.0-rc.1-1 both come
before 1.0-1. This is the order of PSPU 5.6, the same as the earlier
Peios package tools used.
What else a manifest says #
Besides its files, a manifest can record what the package needs and offers, and describe it:
| Part | What it records |
|---|---|
[dependencies] | Other packages this one needs, each with the versions it can use |
[requires] | Capabilities this one needs, such as the library libc.so.6 or a shell, sh |
[provides] | Capabilities this one offers, each at a version or none |
[claims] | Links this package provides besides its files, such as /usr/bin/sh |
description, homepage, license, license_class, source_license | What the package is and its terms |
source | The package holding the source it was built from |
They're part of the manifest, so they're part of the package's identity, and like the files they have one spelling each. A package that records none of them has the same manifest it would have had without them. To record them, see Recording Dependencies and Metadata.
Security metadata #
A file or directory can carry security metadata in its manifest entry:
- A security descriptor, which replaces the one it would otherwise get, so that, for example, only one service can run a program or write a directory.
- A signature, for a file. The kernel reads it from the file's
security.peios.sigattribute and checks it before it gives the file to a device as firmware. The signature is stored as a blob, and the entry names it by its hash.
These entries, with the descriptor shortened, are from a package that gives one content both ways:
= { = "sha256:07f7ab476bc3a83fad639d34a012cb4a5f859441f0d24c11627ca96696839012", = "0100048014000000…" }
= { = "sha256:07f7ab476bc3a83fad639d34a012cb4a5f859441f0d24c11627ca96696839012", = "sha256:ec87928fa1c24dacf5ebe2eaf8f7adf473de9ef65f8b7648ead92e9f7672155b" }
The metadata is part of the entry, so it's part of the package's identity. A file with security metadata is stored as a file of its own that carries it, and every hard link to that file carries it too. Two files with the same content and different metadata are two stored files, and two packages can't give one path different metadata. A package with no security metadata has the manifest it would have had without it.
On Peios, ppk gives each file and directory its metadata as it creates
it. On another system, such as a Linux host that builds packages, it writes
the attributes only where that system lets it, which usually needs
privilege, and otherwise warns that it couldn't. The manifest records the
metadata either way. To give files security metadata, see
Giving Files Security Metadata.
The artifact directory #
ppk stores packages in an artifact directory, which is
/system/artifacts unless you name another. It holds these kinds of file:
| Path | Contents |
|---|---|
blobs/sha256/<hash> | The content of one file that isn't executable |
blobs/sha256/<hash>.exec | The content of one executable file |
blobs/sha256/<hash>.<entry> | The content of one file with security metadata, which it carries |
manifests/sha256/<hash> | One manifest, named by its hash |
refs/<name>/<version>/<arch> | The identity of the package with that name, version, and architecture |
A blob is stored in the form its manifest entries need: plain, executable, or both if the same content is shipped both ways. A file with security metadata has a form of its own, named by the SHA-256 hash of its entry as the manifest writes it. The form is part of the stored file, not of the blob's name, so a package's identity doesn't depend on it.
A ref is an index. It lets you find a package by name, but every manifest records its own name, version, and architecture, so the manifests remain the authority.
Because a blob is named by its content, a file that appears in several packages, or in several versions of one package, is stored once. Packing a new version adds blobs only for the files that changed.
An artifact directory is also where other machines get packages from. ppk fetch copies a package out of one artifact directory into another, checking
every hash on the way; see
Fetching a Package.
Packed versions never change #
Once a package is packed, its name, version, and architecture always mean the same content. Packing the same version again with identical content succeeds and changes nothing. Packing it with any change to its files is refused, so that a version means one thing everywhere it is used. To ship a change, give it a new version.
Every file in the artifact directory is read-only for the same reason: a blob, manifest, or ref that changed after it was written would stop matching what refers to it.
Who can read a package #
Everyone on a machine can read and run what's in its artifact directory.
ppk gives every file it stores a security descriptor that grants Everyone
read and execute, and SYSTEM and Administrators full control. The
directories it creates there grant the same, so any user can reach the
packages. A file or directory that a package gives a descriptor of its own
has that one instead, wherever it's placed.
A package is the same on every machine it's installed on, because its content is named by hash. It can't hold anything that belongs to one machine or one user, and anything in it is readable by every user of every machine that stores it.
Closures
Peios / Developing for Peios / Packaging Software
A closure is a set of packages composed into one directory tree: the
contents of a /usr. Mounted at /usr, each package's files are at their
ordinary paths, such as /usr/bin/hello, so software runs from a closure
without any changes to where it looks for its files. Different closures
can hold different versions of the same package side by side.
A tree of hardlinks #
Unless you ask for copies, every package file in a closure is a hardlink to its blob in the artifact directory: the same file on disk, not a copy. Building a closure therefore copies no file content, and a file that several closures share is stored once.
A hardlink shares everything about the file except its name, including whether it is executable. That's why the artifact directory stores an executable form of each executable blob, as described in Packages. For the same reason, everything in the artifact directory is read-only: a change made through one closure would change the file in every closure that links it.
Symbolic links and directories aren't shared. ppk closure creates them
afresh in each tree. The root of the tree grants everyone read and execute,
and the directories and links inside it inherit that, so any user can reach
and run what a closure holds. Its files have the access their blobs grant,
described in Packages.
Why each package is there #
Each closure records why it holds each package, in its inventory: a file at
the top of its tree, visible as /usr/inventory when it's mounted.
ppk compose-env writes the same file in the root's usr. It's a line
format:
closure sha256:9c41…
org.openssl.libssl@3.5.8-1?arch=x86_64 sha256:… [se.curl.curl libssl.so.3]
se.curl.curl@8.22.0-1?arch=x86_64 sha256:… [* >=8.22]
The first line names the closure. Each other line is a package: its full ID, its identity, and a bracket for each thing that wants it.
- Who wants it:
*for a request made of the closure itself, such as a package named afterppk run -por in a profile, or the name of another package in the closure. - What it asked for: a capability, such as a library's soname, if the package wasn't asked for by name.
- Where from:
#and an index or channel, such as#stable, for a request that named one. - Which versions would do: one token per expression of the constraint,
such as
>=8.22, or none for any version.
A package is wanted by every request, dependency or requirement it
satisfies. Every package in a closure must be wanted by something, and
every request satisfied. Lines are sorted by package ID, and brackets by who
wants the package, * first.
This generated file has mode 0444 and inherits the tree's security
descriptor, like directories without manifest metadata.
Naming a closure #
A closure's identity is the SHA-256 hash of its inventory without the first
line. So the same packages, asked for the same way, always make the same
closure, whatever order you name them in. The same packages asked for
differently, such as * asking for curl exactly in one and only through
another package in the other, are two closures.
Closures are kept in the closures directory of the artifact directory
unless you name another. The tree is closures/<hash>/, and its manifest,
the same lines as the inventory without the first, is
closures/<hash>.manifest.
Because the name is known before anything is built, ppk closure reuses
a closure that already exists. It builds a new tree in a temporary
directory and moves it into place only when it's complete, so a closure
that exists is never half-built.
A closure can also be given a name of your own with ppk name:
A name is a symbolic link beside the closures, replaced by renaming, so it
always names one closure or another. An installed system names the closure
that is its /usr SYSTEM, and the one its initramfs is built from
INITRAMFS.
Identifying the mounted closure #
ppk list checks that the inventory's identity is the hash of its other
lines before printing the packages. This checks the recorded packages and
requests; it doesn't authenticate the package IDs or verify the files in the
tree.
Run ppk list to print the current closure's full package IDs in byte
order, one per line. No artifact directory is needed. Run ppk list --all
to list every package indexed by the store's refs, also sorted by full ID.
A package whose ID and identity are both in the current closure has *
before its ID; other packages have a space there, so every ID starts in the
same column.
A missing inventory makes ppk list fail with an explanation. With
--all, a missing inventory leaves every package unmarked. A malformed
inventory or mismatched closure identity makes either command fail.
An existing closure without an inventory is reused unchanged as a closure built by an older ppk. To obtain an inventory, compose a fresh root or use a separate closure directory. Reusing a closure keeps requiring only read access to its tree.
Conflicts #
Packages in a closure share one tree, so they have to agree about every path in it. Building a closure fails, before anything is written, when:
- Two packages give one path different contents. Two packages can ship the same file only if it is identical, such as a shared license text.
- A path lies beneath another package's file or symbolic link. One package can't put files inside something another package ships as a file. This also means a closure is never written through a symbolic link to somewhere outside it.
A package can put files in an empty directory that another package ships.
The same mount #
A hardlink can't cross from one mount to another, even between two mounts of
one filesystem, as the bind mounts of a build sandbox often are. So the
closure directory must be on the same mount as the artifact directory, and
ppk closure fails with nothing left behind if it isn't.
Copied files #
To build a closure on another mount, ask for copies with --copy-files. The
tree then has the same paths, content, and permissions, and the same
identity, but each file is a file of its own. ppk copies a file only when
you ask, rather than whenever a link fails, because a copy differs from a
hardlink in ways you should choose:
- It takes space. A copy is stored once per closure, not once per store.
- It has a security descriptor of its own. A hardlink has its blob's one descriptor, so the store controls access to every closure that links it. A copy gets the store's descriptor when it's made, so it grants what a hardlink would, but a later change to the store's descriptors doesn't reach it.
- It is checked. A copy has to read the blob, so
ppkhashes it asppk fetchdoes, and a blob that doesn't match its hash stops the build. Hardlinking reads no content, and checks none.
A closure is named by its packages, not by how its files got there, so
ppk closure reuses an existing closure whichever way it was built.
Environments
Peios / Developing for Peios / Packaging Software
An environment is a view of the filesystem in which a closure is /usr.
Everything Peios ships lives under /usr, so a program in an environment
finds the exact set of packages the closure holds, while everything else,
such as the machine's own configuration, its state, and your home
directory, stays where it was. Different programs can run side by side with
different closures as their /usr.
What changes and what doesn't #
An environment starts from the filesystem as the process that creates it
sees it, and replaces only /usr with the closure. Directories such as
/lcl, /var, /home, and /run are the same ones, so a program in an
environment reads the machine's configuration and shares /run with the
rest of the machine.
Packages are laid out relative to /usr for this reason: a package's
bin/hello is /usr/bin/hello in any environment that includes it, and a
package can't place anything outside /usr.
Kept to its own processes #
An environment is a mount namespace: a private copy of the table that says
which filesystem is mounted where. ppk run creates one, mounts the
closure at /usr in it, and starts the command there. The command and
every process it starts see the closure; nothing outside sees any change,
and when the last of them ends, the environment ends with it.
Each ppk run creates a new environment, even for the same closure. The
closure itself is built once and reused.
Laid out as files #
An environment can also be laid out as a directory, as the whole root of a
filesystem, for a tool such as an image builder to take. ppk compose-env
does this. There is no running system around such a root to borrow the rest
of the filesystem from, so what lies outside /usr, such as links and
mount points, is given when the root is composed. It belongs to the
environment, not to any package.
Described by a profile #
An environment profile is a TOML file that describes an environment, so that it can be named and reused rather than spelt out on the command line each time:
= ["proc", "sys", "tmp"]
[]
= "1.37.0-1"
= ">= 0.0.7"
[]
= ":sbin/prelude"
packages maps each package the environment asks for to the versions that
will do, as a constraint. A bare version asks for exactly that version, and
"" for any. "#stable" asks for the version a repository's stable
channel holds, and "#stable >= 1.36" for that version if it satisfies the
constraint; see
Publishing a Repository. A
profile holds the requests, not their answer: composing it resolves them,
choosing a version of each package they need, and the closure's
inventory records what was chosen.
The same requests against the same packages always resolve the same way. A
profile that asks for exact versions of everything, as
ppk resolve
writes one, always describes the same environment. symlinks and dirs
are what the root holds outside /usr, besides any links its packages
claim there, and a leading : in a link's target
stands for usr. include_artifacts = true gives a composed root its
packages in an artifact directory of its own. Every key is optional.
arch sets the architecture of every package, the one ppk was built for
by default.
A profile can include other profiles, called fragments, so that what
several environments share, such as the layout of a root, is written once:
= ["root-layout.toml"]
[]
= "1.37.0-1"
Each path is relative to the file that names it, and a fragment can include others. The profile holds everything its fragments hold. Where two of them hold the same thing, it's held once, and where they disagree, as with two versions of one package or two targets for one link, it's an error naming both files. Nothing decides which one wins: you change one of them.
ppk compose-env and ppk run both take profiles, and several given
together merge as fragments do. A run keeps the rest of the filesystem as
it is, so it uses only the profiles' packages.
Who can create one #
Any process can create a mount namespace of its own and mount a closure in
it, so ppk run needs no privilege. Building a closure needs write access
to the closure directory, but running one that already exists only reads
the store, so an ordinary user can run any closure an administrator has
built.
The closure is mounted as it is, not read-only: making a mount read-only needs a privilege that ordinary users don't hold. Its files are protected by their security descriptors instead, which grant everyone read and execute and nothing more.
Creating a Package
Peios / Developing for Peios / Packaging Software
Packing turns a directory of files into a package in an artifact directory. Do this when you have built software and want to ship it as a named, versioned package. For what a package contains, see Packages.
Before you start #
The top-level name inventory is reserved for ppk's closure inventory.
Do not include a file, directory, or symbolic link with that name in the
package's input tree, or claim /usr/inventory or a path beneath it.
ppk pack refuses these paths before writing to the store.
- Install
ppk. - Choose the package's version, the architecture its content is built for, and its name, which must follow the rules for package names.
- Have write access to the artifact directory. The default is
/system/artifacts; to use a directory of your own, pass--artifact-dir.
Pack a directory #
-
Stage the package's files in a directory, laid out as they will appear under
/usr. For example, a program installed as/usr/bin/hellogoes athello/bin/hello. -
Make sure each program in the directory is marked executable. The package records which files are executable and nothing else about their permissions.
-
Run
ppk packwith the package's identifier and the directory:Quote the identifier, because some shells treat
?as a wildcard.ppkprints the package's identity:sha256:73a137f612f39b8ee1ffcbb7f51b7b9dc370b8662323d72b9e6b73b9d54413f8
Check the result #
Read the package's ref, which is named by its name, version, and architecture:
It holds the identity that ppk pack printed:
sha256:73a137f612f39b8ee1ffcbb7f51b7b9dc370b8662323d72b9e6b73b9d54413f8
The manifest is artifacts/manifests/sha256/ followed by the same hash.
It lists every path in the package.
Packing for another architecture #
If the content is built for a particular processor, name its architecture in the identifier:
Without ?arch=, ppk uses the architecture it was built for itself. The
same name and version can be packed once for each architecture.
Shipping a change #
A packed version never changes. If you pack the same version again with
different files, ppk refuses and exits with status 1:
ppk: dev.peios.hello@1.0-1?arch=noarch: already packed as sha256:73a137f612f39b8ee1ffcbb7f51b7b9dc370b8662323d72b9e6b73b9d54413f8; a packed version cannot be replaced
Pack the changed files as a new version instead, such as
dev.peios.hello@1.1-1?arch=noarch. Only the files that changed are stored
again. Packing a version again with identical files succeeds and prints the
same identity.
Recording Dependencies and Metadata
Peios / Developing for Peios / Packaging Software
A package's manifest can say what the package needs, what it offers, and what it is, as well as listing its files. Record these when you pack it, so that whatever builds an environment from packages can choose the ones that work together. For what a manifest holds, see Packages.
Before you start #
- Be able to pack the package, as Creating a Package describes.
- Know what the package needs at run time that isn't in its own files and
that its programs don't link: the packages and commands it runs by name or
loads itself.
ppk packfinds the libraries its programs link, as What ppk pack finds in the files describes.
Record what the package needs and offers #
Give ppk pack an option for each thing to record. The options that take
two values take them as two separate arguments, so neither value needs a
separator. An empty value means "any version" for a dependency or
requirement, and "no particular version" for something provided:
--depends <name> <constraint>records a dependency on another package, by its name.--requires <name> <constraint>records a need for a capability rather than a particular package: a name such as the shellsh, orpkgconfig(zlib), which any package can provide. A library that a program links is found for you.--provides <name> <version>records a capability this package offers.--claims <path> <target>records a link at an absolute path that the package provides besides its files, with the link's target. Use it for a name that one of several packages answers, such as/usr/bin/sh.
Give each option once for each package, capability or path. A name given twice is an error.
What ppk pack finds in the files #
ppk pack reads each ELF program and library in the files, and adds what
they need and offer to what the options give:
- Each library a program or library links (its
DT_NEEDED) becomes a requirement, such aslibtinfo.so.6. A library the package itself provides isn't required. - Each library's own name (its
DT_SONAME) becomes a capability the package provides. - For glibc's libraries and
libgcc_s.so.1, the requirement has a floor: the newest symbol version the programs use. A program usingGLIBC_2.38requireslibc.so.6 >= 2.38. The package providing the library provides it at its own version, such as2.44-1. - For
libstdc++.so.6, each symbol version is a capability of its own, such aselfver(libstdc++.so.6:GLIBCXX_3.4.21).
Files under src/ and symbolic links aren't read, nor is anything that
isn't ELF.
Where an option names a capability that the files also give, the option's
entry is kept. The floors are the exception: they come only from the files,
so don't write them yourself. A floor written by hand tends to record what
the package was built against, not what it needs, and it would keep the
package off a system with an older glibc that would run it. To require a
newer glibc for a reason the symbols don't show, depend on the glibc package
with --depends and say why in the recipe.
The rules in full are under DERIVATION in ppk(1).
Write a constraint #
A constraint is one or more expressions, separated by commas, that a version must all satisfy:
| Constraint | Satisfied by |
|---|---|
>= 2.44 | 2.44 and later, whatever the revision: 2.44-1, 2.44-3, 2.45-1 |
>= 2.44-3 | 2.44-3 and later, but not 2.44-2 |
>= 1.0, < 2.0 | 1.0 and later, before 2.0 |
= 2.44-1 or 2.44-1 | Exactly 2.44-1 |
!= 2.43 | Anything but upstream version 2.43 |
| Empty | Any version |
The operators are =, >, >=, <, <=, and !=, and a version
without one means =. A version in a constraint can leave out its
revision, and the revision then isn't compared. That's usually what you
want: repackaging the same upstream version shouldn't change whether a
dependency is met. Versions compare as
Package Versions describes.
Describe the package #
Add the descriptive options to the same command:
--descriptionis one line of printable ASCII.--homepageis anhttporhttpsURL.--licenseis the package's license, conventionally an SPDX expression, and--source-licensethe license of the source it was built from, where that differs.--license-classisfree,firmware,proprietary, orunknown, the default.--sourcenames the package holding the corresponding source the package was built from, as a package ID with its architecture, such asorg.git.kernel.dash-source@0.5.13.5-1?arch=noarch. A package built from no source of its own, such as device firmware, leaves it out.
Check the result #
ppk pack prints the package's identity. Its manifest, in
artifacts/manifests/sha256/ followed by that hash, records everything you
gave and everything found in the files, in one fixed order:
= "org.git.kernel.dash"
= "0.5.13.5-1"
= "x86_64"
= "POSIX-compliant shell"
= "https://git.kernel.org/pub/scm/utils/dash/dash.git"
= "BSD-3-Clause"
= "free"
[]
= "dash"
[]
= ">= 2.44"
[]
= ""
[]
= ">= 2.38"
[]
= { = "sha256:e4a76dc6517a94c9f1abde8582aa3909a1315e28a66a5c9f304c5a697b74c638", = true }
The requirement on libc.so.6 comes from bin/dash, which uses symbols as
new as GLIBC_2.38. Each constraint is written in one form, whatever
spacing you gave it, and anything that wasn't given or found is left out.
When an option is refused #
ppk pack checks everything before it writes anything. Anything that breaks
a rule is a usage error, with exit status 2, and nothing is packed. A
dependency must name a package, so a capability given to --depends is
refused:
ppk: dependencies: invalid package name 'sh': use a reverse-DNS name such as dev.peios.hello, of at most 64 characters, with at least 3 dot-separated labels of lowercase ASCII letters, digits, - and +
Use --requires for it instead. A constraint that doesn't parse names its
option:
ppk: --depends org.gnu.glibc: constraint '>=2.44,' has an empty expression
A floor on one of glibc's libraries or libgcc_s.so.1 fails, with exit
status 1, because only the files can say what it is. The message names what
you wrote and what the files need:
ppk: requires libc.so.6: the written floor '>= 2.44' is refused, and the payload needs '>= 2.38' (bin/dash); a floor on libc.so.6 comes only from the payload's symbol versions
An ELF file that ppk pack can't read fails in the same way, naming the
file.
The full rules for each value are in ppk(1).
What ppk does with them #
The dependencies, requirements, capabilities and claims you record are part
of the package and its identity, and ppk checks them when it reads a
manifest.
ppk resolvefollows dependencies and requirements to choose the packages an environment needs, as Choosing Packages for an Environment describes. A requirement is met by a package of that name or one that provides the capability; a dependency only by a package of that name.- Composing creates each claimed link: under
/usrin the closure, and elsewhere, such as/init, in a composed root. Two packages in one environment can't claim the same path. A closure is only/usr, soppk runcreates only the links claimed there.
Changing any of them changes the package, so it needs a new version, as a change to its files does.
Giving Files Security Metadata
Peios / Developing for Peios / Packaging Software
Most files in a package get the security descriptor that ppk gives
everything it stores. Some need one of their own: a program that only one
service can run, or a directory that only one service can write. Firmware
needs a signature, which the kernel checks before it gives the firmware to
a device. Record both when you pack the package, and ppk gives each file
and directory its metadata wherever it places it. For what a manifest holds,
see Security metadata.
Before you start #
- Be able to pack the package, as Creating a Package describes.
- Have each descriptor as a self-relative security descriptor in
hexadecimal, with an owner, a group, and a DACL.
ppktakes the descriptor's bytes, not SDDL. - Have each firmware file's signature: the 3310-byte file that a signer
writes beside the file, named with
.peios.sigadded.
Give a file or directory a descriptor #
Give ppk pack the --descriptor option with the path, as the manifest
lists it, and the descriptor. The two values are separate arguments:
The descriptor is shortened here. Give the option once for each path. The
path is relative to /usr, so bin/gxwi-server is /usr/bin/gxwi-server.
- A file keeps its descriptor in every closure and environment, because each placed file is a hard link to a stored file that has it, or a copy given it.
- A directory with a descriptor is listed in the manifest even if it has contents. It's created with its descriptor before anything inside it, so what's created in it inherits from that descriptor.
- A symbolic link can't have a descriptor of its own.
Sign a file #
Put each signature in the directory you pack, beside the file it signs,
with .peios.sig added to the file's name:
gxwi/lib/firmware/acme/fw.bin
gxwi/lib/firmware/acme/fw.bin.peios.sig
ppk pack doesn't pack the signature as a file. It records it in the
signed file's entry, and the file gets it as its security.peios.sig
attribute wherever it's placed. A signature must be exactly 3310 bytes and
start with the version byte, 1. The file it signs must be a regular file in
the same package, and not an ELF file: an ELF file carries its signature in
its own .peios.sig section. No other path can end in .peios.sig.
ppk doesn't check what a signature signs. That's the kernel's job, when it
loads the file.
Check the result #
ppk pack prints the package's identity. In its manifest, in
artifacts/manifests/sha256/ followed by that hash, each file and directory
with security metadata has it in its entry, after its blob or dir:
= { = "sha256:07f7ab476bc3a83fad639d34a012cb4a5f859441f0d24c11627ca96696839012", = true, = "010004801400000020000000000000002c000000..." }
= { = "sha256:07f7ab476bc3a83fad639d34a012cb4a5f859441f0d24c11627ca96696839012", = "sha256:ec87928fa1c24dacf5ebe2eaf8f7adf473de9ef65f8b7648ead92e9f7672155b" }
The descriptor is written in lowercase, whatever case you gave it, and is shortened here. The signature is named by its hash, and stored as a blob.
Packing on a system other than Peios #
On Peios, ppk gives each stored file, copy, and directory its metadata as
it creates it, and fails if it can't. On another system, such as the Linux
host that builds packages, it writes the security.peios.sd and
security.peios.sig attributes only where that system lets it, which
usually needs privilege. Where it can't, it packs the files without them
and warns:
ppk: warning: 2 files and directories lack security metadata this system would not let ppk give; their manifests record it
The package is still complete: its manifest records the metadata, and
ppk fetch on Peios gives each stored file what its entry records. ppk closure, ppk compose-env, and ppk run warn in the same way when they
place files that lack it.
When something is refused #
ppk pack checks everything before it writes anything. A descriptor that
isn't hexadecimal, or isn't a whole self-relative descriptor, is a usage
error, with exit status 2:
ppk: --descriptor bin/gxwi-server: security descriptor has no owner or no group
These fail with exit status 1, and nothing is packed:
-
A descriptor for a path that isn't a file or directory of the package, or for a symbolic link.
-
A signature that isn't 3310 bytes, or doesn't start with version 1.
-
A signature beside nothing, or beside a symbolic link, or an ELF file:
ppk: "bin/tool.peios.sig": signs "bin/tool", an ELF file, which carries its signature in its .peios.sig section -
Anything else whose name ends in
.peios.sig.
ppk closure and ppk compose-env refuse two packages that give one path
entries that differ only in their security metadata, as they refuse any
other two different entries. A stored file whose signature attribute isn't
the one its entry names is an error, because it isn't the file its name
says. The full rules are under SECURITY METADATA in ppk(1).
Fetching a Package
Peios / Developing for Peios / Packaging Software
Fetching resolves a package and everything it needs from another artifact directory, or from a repository served over HTTP, then copies the chosen packages into yours and checks them on the way. Do this to use a package that was packed somewhere else, such as on a build machine whose artifact directory you can read, or one a repository publishes.
Before you start #
- Install
ppk. - Have read access to the source: an artifact directory, as a local path, or a repository's URL.
- Have write access to your artifact directory. The default is
/system/artifacts; to use a directory of your own, pass--artifact-dir. - Know the package's name, such as
org.figlet.figlet.
Fetch the package #
Run ppk fetch with the name and the source:
ppk chooses the newest version that satisfies the request, follows its
dependencies and requirements, and fetches every chosen package. It prints
one identity per package fetched, in package-name order:
sha256:73a137f612f39b8ee1ffcbb7f51b7b9dc370b8662323d72b9e6b73b9d54413f8
To constrain the version, quote the name and constraint, for example
'org.figlet.figlet >= 2.2'. A full ID such as
'org.figlet.figlet@2.2.5-1?arch=x86_64' pins that exact package, including
the version's spelling. Its dependencies are still resolved. Unqualified
requests choose for ppk's own architecture; --arch selects another. All
packages in one resolution must be for the same architecture. A full ID
with an explicit architecture can select that architecture on its own.
Resolution is greedy, as ppk resolve is. Missing dependencies, missing
capability providers and conflicting constraints fail with an error naming
what is needed, before copying starts.
To copy exactly one package without resolving anything it needs, pass
--no-deps and a full ID. This mode accepts IDs, with an optional
?arch=…, rather than bare names or constraints:
--from also takes the URL of a repository served over HTTP, such as
https://pkgs.peios.org/. --from takes no identity, so ppk checks every
file against its hash but can't check who signed the repository. To check
that too, add the repository with its identity, using ppk repo add.
Check the result #
Compare the identity with the one ppk pack printed where the package was
made. Because the identity is the hash of the manifest, and the manifest
names every file by its hash, the same identity means the same package,
byte for byte.
Fetch from configured repositories #
A machine keeps a list of the repositories it fetches from, each a file in
/conf/ppk/repositories/. Add one with ppk repo add, giving the identity
its pointer file must be signed under, and the channel it follows:
ppk accepts the signature only if a root it was built with vouches for
the chain that made it. A repository whose publisher has no such chain signs
under a top-level certificate of its own, which you enable on the machine
first. Add that repository with --unrooted, and optionally with
--anchor and the top-level's hash, to accept that top-level and no
other:
That writes /lcl/conf/ppk/repositories/peios.toml, which /conf/ppk merges
with whatever the system ships. Then fetch without --from:
A repository served over HTTP is added by its URL instead of a path. Give more than one URL to try them in order, such as a cache on your network first and the repository's own server after it:
If a URL can't be reached or doesn't have a file, ppk tries the next one.
ppk keeps the tree nodes and manifests it reads from a repository served
over HTTP in /var/cache/ppk, so it reads each of them only once. Pass
--cache-dir to keep them somewhere else.
A request for a bare name, or a name with a constraint, follows the channel
its repository tracks, so this fetches the version stable holds, and what
it needs from stable too. Naming an index, as in se.curl.curl#leading, or
an exact version, takes that instead.
Each package name belongs to one repository. If two of them publish one, for
something you asked for or something it needs, ppk refuses rather than
choose. A repository's pointer file goes up in sequence each time it's
published, and ppk keeps the highest it has seen of each in
/var/state/ppk, refusing a repository that offers an older one. A mirror
might still be behind; ppk repo list shows when each was signed:
peios /mnt/peios-repo #stable (sequence 42, signed 2026-11-13T13:11:46Z, signature checked)
What fetch checks #
ppk fetch trusts nothing it reads from the source:
- The manifest must hash to the identity in the source's ref.
- Its form must be exactly what
ppk packwrites, naming the package you asked for, with every path relative and inside the package's root. - Each file's content must hash to the name the manifest gives it.
If a check fails, ppk fetch stops with an error and doesn't record the
package. Only the files missing from your artifact directory are copied, so
fetching a new version transfers only what changed.
These checks prove that the package is the one the source's ref names. They don't prove who published it, so fetch only from sources you trust. A configured repository with an identity proves that too: a package must be in the catalog its signed pointer file leads to, at the identity the catalog gives, so a package it didn't publish, or a ref changed since, is refused.
A repository served over HTTP has no refs that ppk can list, so its
catalog says which packages it has. To choose packages, ppk reads only the
catalog's entries for the names it needs and each version's summary: the
start of its manifest, which says what the package needs and provides but
not what files it holds. A catalog also lists what provides each
capability, so finding a library by its soname reads no more than that.
ppk reads a manifest only when it fetches the package, and refuses one
that doesn't begin with the summary it chose the package by.
ppk checks every file it reads from
the repository against its hash before using it, and checks the pointer
file's signature. A file that fails its check is an error: ppk doesn't try
the next URL, because a server that sends the wrong file is broken or
hostile. A file that fails its check is never stored.
A repository can keep its blobs compressed, as an export does, and its
pointer file says so. ppk decompresses each blob as it fetches it and
checks what it decompresses to, so your artifact directory always holds the
files uncompressed.
When the package is already present #
By default, a chosen package already present with the same identity is
skipped without writes or output. Its dependencies are still resolved and
fetched if missing. With --no-deps, fetching it checks the package, copies
any missing files, and prints its identity as before. If your artifact
directory has a different package under the same name, version, and
architecture, ppk fetch refuses to replace it:
ppk: dev.peios.hello@1.0-1?arch=noarch: already present as sha256:73a137f612f39b8ee1ffcbb7f51b7b9dc370b8662323d72b9e6b73b9d54413f8, but other has sha256:453a10dad4cb1902912919527452fa61c6420ae9152c1f02b57c1421a6d9d57b
A packed version never changes, so two different packages under one version mean the two artifact directories disagree. Find out which one is right before you use the package.
Replace a package in a bootstrap's directory #
A bootstrap builds its first packages with another system's tools, then
rebuilds them with its own at the same versions. Its artifact directory isn't
published until every package has been rebuilt, so nothing relies on the
first builds yet. To replace one, pass --replace --no-deps with its ID:
The ref then names the fetched package. The replaced manifest and its files
stay in the directory. Replacement requires --no-deps so that it affects
only the named package. Every check above still applies. Don't use
--replace on an artifact directory anything has fetched from: that breaks
the rule that a version never changes.
Building a Closure
Peios / Developing for Peios / Packaging Software
Building a closure composes packages into one directory tree, the contents
of a /usr. Do this when you want a set of packages together in
one place, for example to check that they fit together without conflicts.
For how closures work, see Closures.
Before you start #
- Install
ppk. - Have every package in your artifact directory, by packing it with
ppk packor fetching it withppk fetch. - Have write access to the artifact directory. The default is
/system/artifacts; to use a directory of your own, pass--artifact-dir.
Build the closure #
Run ppk closure with the identifier of each package:
ppk prints the closure's identity:
sha256:fe5cf307f0b70379e1ec36b0d8dca659782446b0d13e7140c1257cd855ba61c4
Check the result #
The closure's tree is in the closures directory of the artifact
directory, named by the hash in the identity:
The tree holds the files of every package, laid out as they appear under
/usr:
hello
The closure's manifest, which lists its packages and what wants each, is
beside the tree with the same name and a .manifest suffix. Running the
same command again reuses the closure and prints the same identity.
ppk closure asks for each package you name exactly.
The tree also holds inventory, the same lines with the closure's identity
first. When mounted at /usr, this file lets ppk list identify the
closure without an artifact directory. For its format, see
Why each package is there.
Resolving a conflict #
If two packages give the same path different contents, ppk closure
refuses and names both packages:
ppk: "bin/hello": dev.peios.hello@1.0-1?arch=noarch and dev.peios.clash@1.0-1?arch=noarch provide different entries
Nothing is written. Decide which package should provide the path, and build the closure without the other one, or change one of the packages so that the two don't overlap and pack it as a new version.
Using another closure directory #
To keep closures somewhere other than the artifact directory, pass
--closure-dir. The directory must be on the same mount as the artifact
directory, because the closure's files are hardlinks to its blobs. If it
isn't, ppk closure refuses and leaves nothing behind:
ppk: closures: not on the same mount as the artifact directory artifacts; use --copy-files
To build the closure there anyway, such as in a sandboxed build step that has the artifact directory as a read-only input, copy its files:
ppk checks each blob against its hash as it copies. To see what a copy
changes, including for security descriptors, see
Copied files.
Running a Command in an Environment
Peios / Developing for Peios / Packaging Software
ppk run runs a command in an environment whose /usr is the closure of
the packages you request and everything they need. Do this to use a set of
packages without changing
/usr for anything else on the machine. For how environments work, see
Environments.
Before you start #
- Install
ppk. - Have every package in the artifact directory. If their closure doesn't exist yet, you also need write access to the closure directory; to run an existing closure you need only read access.
Run the command #
Run ppk run with the packages after -p, then --, then the command
and its arguments:
One -p takes every request after it, up to the next option. Requests accept
bare names, quoted names with constraints such as
'org.figlet.figlet >= 2.2', and exact IDs such as
'org.figlet.figlet@2.2.5-1?arch=x86_64'. ppk resolves them against the
artifact directory, including dependencies and capability
requirements. It does not fetch missing packages: use ppk fetch first.
Unqualified requests use ppk's own architecture, or --arch if given.
An explicit architecture in a full ID selects that architecture when all
requests are qualified. One resolution holds one architecture.
To use the packages of an environment profile, give the profile first. Its
requests are resolved together with any after -p, with what they need, and
a request the others can't satisfy fails before composition. The closure's
inventory records every request, so ppk list and /usr/inventory show
what was asked for as well as what was chosen.
A run keeps the rest of the filesystem as it is, so a
profile's links and directories don't apply:
The command runs with the chosen packages at /usr.
To compose exactly the IDs you name, pass --no-deps. This mode accepts
full IDs with an optional architecture, as before; names and constraints
are not accepted. A profile used with it must ask for one exact version of
each package:
If the named packages omit the program's loader or libraries, execution can
fail with No such file or directory even when the program itself exists.
The default resolution includes providers for the package's requirements.
Everything after -- is the command, so its own options aren't read as
ppk's. A command without a / is looked up through PATH inside the
environment.
Start a shell instead #
Leave out -- and the command, and ppk run starts /usr/bin/sh in the
environment:
The shell is the closure's own, not yours, so one of the packages must
provide bin/sh. Commands you run from it share its environment.
Check the result #
ppk run exits with the command's own exit status. If the command can't be
started, the status is 127 when it isn't found and 126 when it isn't
executable, and ppk says why:
ppk: /usr/bin/nothing: No such file or directory
Outside the command, /usr hasn't changed.
The mounted closure includes its own /usr/inventory, so ppk list
inside the command reports that closure's packages. Include ppk and its
runtime packages if you want to run it there. ppk list --all reads the
store in the caller's root and marks membership in the mounted closure.
A closure is named by its requests as well as its packages, so a closure
built by an older ppk, named by its packages alone, is never mistaken for a
new one.
Choosing Packages for an Environment
Peios / Developing for Peios / Packaging Software
ppk resolve chooses an exact version of every package an environment
needs, from what you ask for and the packages in one or more artifact
directories, and writes them as a profile. It follows each package's
dependencies and requirements, as
Recording Dependencies and Metadata
records them. Composing a profile resolves its requests anyway, so use
ppk resolve when you want the answer fixed: a profile of exact versions
always composes the same environment, whatever else the artifact
directories come to hold. Compose it as
Composing an Environment
describes.
Before you start #
- Install
ppk. - Have every package the environment could need in one or more artifact
directories.
ppk resolveonly reads them.
Write the profile #
Name the packages you need after -p, and the capabilities after -c.
Each request is one argument: a name, then optionally a constraint. Quote
a request with a constraint, so that the shell passes it whole. Give the
artifact directories after --from:
root.toml then holds one version of each package chosen:
= "x86_64"
[]
= "0.5.13.5-1"
= "16.1.0-1"
= "2.44-1"
= "4.4.1-1"
Without --out, the profile goes to standard output. Like -p, -c and
--from take every argument after them, up to the next option. The
packages are for the architecture ppk was built for unless you give
--arch.
The profile holds only packages. To give it a root layout, include a
fragment that has one, or give both to ppk compose-env, as
Share a layout between profiles
shows:
How it chooses #
- A package you name, or that a chosen package depends on, is chosen by its name, at the newest version that satisfies the constraint.
- A capability, requested or required, is met by a package of that name, at its own version, or by one that provides it, at the version it provides. A capability provided without a version meets any constraint.
- Packages are settled before capabilities, at every step. So if you name a package that provides a capability, it's the one that meets it, wherever the request appears.
- Once chosen, a package is never reconsidered. Everything later that needs it must accept the version chosen.
Because nothing is reconsidered, the order matters when two things need different versions of one package. A constraint you give on the command line is settled before what the packages need, so naming the package with a tighter constraint is how you steer the choice.
If ppk refuses #
ppk resolve writes nothing when it refuses. When something needs a
version of a package other than the one already chosen, it names both,
and says whether another version would have satisfied both:
ppk: org.example.b@1.0-1 depends on org.example.c < 2, but org.example.c@2.0-1 was chosen for org.example.a@1.0-1 depends on org.example.c >= 1; org.example.c@1.5-1 would satisfy both, but finding it needs backtracking, which ppk doesn't do
Request the version that would satisfy both, here
-p 'org.example.c < 2', or change a constraint.
When packages of several names provide a capability, ppk doesn't pick
one for you. Request the one you want by name:
ppk: org.gnu.make@4.4.1-1 requires sh, but net.busybox.busybox, org.git.kernel.dash all provide it; request one of them by name
It also refuses when no version satisfies a request, when no package
provides a capability, and when one package is different in two of the
directories. A version can be spelt two ways, such as 1.0~a-1 and
1.0~alpha-1. No constraint can tell those apart, so if the version it
would choose has both, it refuses and asks you to remove one.
Composing an Environment
Peios / Developing for Peios / Packaging Software
ppk compose-env lays out an environment's whole root in a new directory:
the closure of the packages you name as its usr, and whatever else you
give it outside usr. Do this when a tool needs the environment as files,
such as an image builder making an initramfs from it. For how environments
work, see Environments.
Before you start #
- Install
ppk. - Have every package in your artifact directory.
- Choose a directory for the root that doesn't exist yet. Every file in the root is a hard link to its blob, so the directory must be on the same mount as the artifact directory, unless you compose on another mount.
Compose the root #
-
Describe the environment in a profile, such as
env.toml. For the format, see Environments:= "noarch" [] = "1.0-1" = "2.0-1" -
Run
ppk compose-envwith the profile and--out:
ppk resolves the profile's requests against the artifact directory, with
the packages they depend on or require, and prints the identity of the
closure of the packages chosen:
sha256:fe5cf307f0b70379e1ec36b0d8dca659782446b0d13e7140c1257cd855ba61c4
root/usr holds the packages' files, and the links they
claim
under /usr, such as dash's /usr/bin/sh. Nothing is written to the
artifact directory.
root/usr/inventory records the closure identity, and each package's full
ID and identity and what wants it. List them without a store:
To list a store and mark the packages in this root, run:
Each line has * for a package whose ID and identity are in this root, or a
space otherwise, then a space and the full ID. Both commands sort by full
ID. For validation
and missing-inventory behavior, see
Identifying the mounted closure.
To add packages to the profile's, or to compose without a profile, name
them after -p. One -p takes every package after it, up to the next
option, so the profile must come first:
These packages are all for the architecture ppk was built for. To name
another, give it in the package, as dev.peios.hello@1.0-1?arch=noarch, or
give arch in the profile.
Add what lies outside usr #
A package can only place files under /usr. The one exception is a link
it claims elsewhere, such as /init, which the root holds because the
package is in it. Anything else the root needs comes from the profile or
the command line:
- A link, from the profile's
symlinksor--symlink <path>:<target>. The target is written as given, unless it starts with a colon in the profile, or a second colon on the command line, which stands for/usr:"bin" = ":bin"andbin::binboth linkbintousr/bin. - An empty directory, such as a mount point, from the profile's
dirsor--dir <path>. - The packages themselves, from the profile's
include_artifacts = trueor--include-artifacts, in the root's own artifact directory,system/artifacts, as hard links, so thatppkinside the environment finds them. --copy-artifactsdoes the same with copies, checking every manifest and blob asppk fetchdoes, and wins over hard links.
Paths are relative to the root. The options add to what the profile gives:
The root then holds bin, a link to usr/bin, an empty tmp, the
packages' artifacts in system/artifacts, and usr.
For a live image, ppk-live-root composes the root from the medium's
profile and store, then runs skeleton apply on it. That applies the root
skeleton file in the root's own /usr/share/skeleton, which
dev.peios.fsbase ships, so the root gets its directories outside /usr
and the /lib64 link. Without the file the hook warns and continues. It
then copies the medium's /lcl tree into the root if present.
The copy preserves modes and a copy failure fails the boot. This carries
image policy, including registry seed queues and executable autorun
scripts, outside /usr. peinit applies the common and live seed queues
after registryd starts; an installer owns promotion of the install queue.
Share a layout between profiles #
When several environments need the same root layout, write it once as a
fragment, such as layout.toml:
= ["proc", "sys", "dev", "tmp"]
[]
= ":bin"
= ":lib"
Then include it from each profile. The path is relative to the profile's own directory:
= ["layout.toml"]
[]
= "1.0-1"
You can also give several profiles to ppk compose-env, which merges them
in the same way, so a profile that names only packages can be composed with
a layout:
If two of them disagree, ppk names both files and composes nothing:
ppk: other.toml links "bin" to "usr/sbin", but layout.toml links it to "usr/bin"
Compose on another mount #
A hard link can't cross a mount, even between two mounts of one filesystem. To compose a root on another mount than the artifact directory, such as a fresh tmpfs, or in a sandboxed build step that has the artifact directory as a read-only input, copy what would be linked:
-
If the root has no artifact directory of its own, pass
--copy-files.root/usrthen holds a copy of each file, checked against its hash, and the root holds nothing else from the store: -
If it needs one, pass
--copy-artifacts, which copies the packages into the root'ssystem/artifacts.usrthen hard links to that.
To see what a copy changes, including for security descriptors, see Copied files.
If ppk refuses #
ppk compose-env leaves nothing behind when it refuses. It checks all but
the hard links before it writes anything. It refuses a root that already
exists:
ppk: root: already exists
It refuses a path under a link you also gave, because creating it would follow the link out of the root:
ppk: "bin/extra": under "bin", which is a symlink
It refuses another version of a package the profile holds, since an environment holds one version of each:
ppk: dev.peios.hello@2.0-1?arch=x86_64: the environment holds dev.peios.hello@1.0-1?arch=x86_64 already
It refuses two packages that claim one path, even as links to one target, since a claim says which package provides the name. Choose one of them:
ppk: "/usr/bin/sh": claimed by both org.git.kernel.dash@0.5.13.5-1?arch=x86_64 and net.busybox.busybox@1.37.0-1?arch=x86_64
It refuses a claimed link outside usr that the profile or the options
also give as a link or a directory, or that a path given lies under:
ppk: "init": claimed by org.git.kernel.dash@0.5.13.5-1?arch=x86_64, but the environment links it
It also refuses packages that conflict, in the same way as
ppk closure, including a claimed
link that is a path in a package's files, and any path that is usr or
lies under it.
Publishing a Repository
Peios / Developing for Peios / Packaging Software
A repository is an artifact directory that says what it publishes. Its
catalog lists every version it holds. Its indexes each hold one
version of each package for each architecture: leading always holds the
newest, and a snapshot holds a release, unchanged for ever. Its
channels, such as stable, each follow an index or another channel.
One file, the pointer file, says what the catalog, each index and each channel are, and it is the only file that is signed. Everything else is named by its hash, from there.
Before you start #
-
Have the packages in an artifact directory, as Creating a Package and Fetching a Package describe.
-
Have a signing certificate that holds the
Repositorywarrant, and its secret key. Thepsocommand issues both. The certificate'sNamewarrant has to cover the name your repository signs as, its identity, such aspkgs.example.com. -
Write a signer file that names them:
= "pkgs.example.com" = "signer.cert" = "signer.key" = ["intermediate.cert"]A path that isn't absolute is beside the signer file.
carrylists the certificates above the signing certificate, in order upward, so that a machine reading your repository for the first time has the whole chain. Leave it out if the signing certificate was issued by a top-level.If the key is sealed under a passphrase, as
psomakes keys unless told otherwise, addpassphrase-file, a file whose first line is the passphrase. Without it,ppkasks for the passphrase on the terminal, and fails if there isn't one. Keep the passphrase file with the same care as the key: together they sign.Keep the key out of the repository and out of version control. Every
ppk repocommand that publishes reads the signer file from--signer, or from$PPK_REPO_SIGNER.
Publish #
Run ppk repo update:
It writes the catalog and leading, signs the pointer file, and prints it:
sequence 1
signed 2026-11-13T13:11:46Z
catalog sha256:09cc9d05541917d9894cb2fc71a05373509789c0218b9ca5b7284ed6cca28619
provides sha256:f6ca384d90eb3223b077a93785c13ea3a9fb5ee53957f489e93cbd3b959e8015
index leading sha256:f5e090f9de6441810fab9e15909770d071687375e9f35c35d73244302c877ab6
The sequence goes up by one each time you publish. Run ppk repo update
again after adding packages.
Besides the catalog, ppk repo update writes each version's summary, the
part of its manifest that says what it needs and provides, and the
catalog's provides tree, which lists what provides each capability. A
machine choosing packages from the repository over HTTP reads those for
the names it needs, not every manifest the repository holds. A repository
published by an earlier ppk gets them the next
time you run ppk repo update, with the same packages.
leading holds only what can be installed from it. A package whose
dependencies or requirements leading can't satisfy is left out, with a
warning naming what it lacks, and so is anything that then lacks it. To make
that an error instead, pass --strict.
Make a release #
Take a snapshot of leading as the release's index, then point channels at
it:
A snapshot never changes, so its name must be new. To fix a release, take a
new snapshot, 2026.10.1, and move the release's channel to it. When a
release gets no more fixes, mark its channel ended, so that a machine
following it can tell:
Take a version back #
To stop new resolutions choosing a version, yank it. Anything that asks for exactly that version still gets it:
--undo restores it. To remove a version altogether, delete it, giving a
reason:
That removes its ref, its manifest, and every file of it that no other package shares. The catalog keeps a tombstone with the reason, so that anything still asking for it can say why it's gone. Snapshots that hold it aren't changed; publish a new one without it to keep a release installable.
Install from a repository #
Anything that resolves packages from a repository can ask for what an index
or channel holds, with # after the name:
The version the index holds is chosen, and so is everything it depends on or
requires: a request for a release takes the release's versions of what it
needs too. A constraint after the index, as in 'se.curl.curl#stable >= 8',
must also hold. A closure records the index of each request that named one,
so its inventory shows what it was asked for from where.
A yanked version is chosen only by a request for exactly it, such as
'org.example.tool = 1.2-1'. A request that only a deleted version would
satisfy fails, giving the reason it was deleted.
Export a compressed copy #
Most of a repository is its blobs, the content of its packages' files. The repository itself keeps them uncompressed, because machines and builds that read it directly link them into closures. To serve it, export a copy whose blobs are compressed:
ppk repo export writes export as the repository as it was last
published, with each blob compressed with zstd under its own name, and
prints the pointer file it signed, which says blobs zstd. Nothing else is
compressed, and every package keeps its identity. ppk decompresses each
blob as it fetches it and checks it against its hash before storing it.
Run ppk repo export again after each ppk repo update. It compresses only
the blobs the export doesn't hold yet, and removes anything you deleted from
the repository. Compression uses zstd level 12 unless you pass --level,
from 1, the fastest, to 22, the smallest.
Serve the repository over HTTP #
Every file of a repository but repository and repository.pso is named by
its hash and never changes. A static web server can serve the repository's
directory, or its export, as it is, with no other software. Machines then
fetch from it by its URL, the URL of that directory:
ppk reads each file at the URL followed by the file's path in the
directory, such as https://pkgs.peios.org/repository for the pointer file.
It doesn't need the server to list directories or answer range requests.
A copy of the repository on another server, such as a cache on your own
network, serves machines the same way. A cache can keep every file but
repository and repository.pso for ever. A machine given the cache's URL
before the repository's own tries the cache first and falls back to the
repository for anything the cache can't serve. Because every file is checked
against its signature or its hash, a cache never has to be trusted for what it
sends.
Check what a repository publishes #
ppk repo show prints the pointer file. Give the repository's identity to
check its signature too:
The check succeeds only if a root this build of ppk holds vouches for the
chain that signed the repository. For a repository whose top-level you
enabled yourself, add --unrooted.
--artifact-dir also takes the URL of a repository served over HTTP, to
check what a server is publishing.
For the files a repository holds, see ppk(1).
Peios ISOs
Peios / Developing for Peios / Building ISOs
A Peios ISO is a disc image that boots a live Peios system under UEFI, on
a virtual machine or on a computer it is written to as a USB stick.
peiso builds one from Peios packages, as a spec describes. For what a
package is, see Packages.
What an ISO holds #
An ISO holds six things:
- A unified kernel image (UKI). One EFI program holding the kernel, its command line, and the initramfs, the small filesystem the kernel starts from. It sits in an EFI system partition image, where UEFI firmware looks for the loader of a removable medium, so the firmware starts it directly.
- A package store, at
/artifacts. It holds every package the spec names and every package those depend on or require, laid out asppkstores them. - The live system's image, at
/live.sqfs. It is the live system's/usras a read-only squashfs image: the packages the spec places in the live system and everything they need, with the inventory a composed/usrhas. Each file and directory carries its security descriptor, and each signed file its signature, which the store's plain files on the medium can't, because ISO9660 holds no extended attributes. - The live system's profile and layout.
/live.tomlis the environment profile the image is the closure of: it asks for the packages the spec places in the live system, each at exactly the versionpeisochose.peisochecks, when it builds the ISO, that resolving it from the store gives exactly those packages./live.layoutlists the links and empty directories the spec gives the live system's root outside/usr. For profiles, see Environments. - What an installer composes an installed system from, if the spec can
be installed:
/install/system.tomland/install/initramfs.toml, the requests of its/usrand its initramfs, each pinned to the versionpeisochose, and checked as/live.tomlis. - The medium's identifier, at
/peios-medium. It is the SHA-256 hash of the packages, the profiles and the image, so the same spec and packages always make the same medium.
Where each package goes #
A spec places each package in one or more of these places:
- The live system, whose
/usris the medium's image. - The initramfs, which prelude, Peios's early-boot init, runs from. Anything that runs before the live system exists belongs here: prelude itself, the live-boot hook that mounts the live system, and what the hook runs, such as a shell. The initramfs is held in memory, so it holds only what boot needs.
- The installed system, which an installer composes from the medium, and its initramfs, which mounts the installed system's disk. A spec that places nothing there can't be installed.
- The medium only, carried in the store and nowhere else. Such a package can be fetched from the medium later, which makes an ISO a library of packages for a machine with no network.
By default, a package goes in the live system and the installed system. Every package is in the store, wherever else it goes.
A package comes with what it needs. peiso resolves the packages the spec
names together, with ppk's resolver, and carries one version of each
package that they depend on or require. Each place then holds the
packages placed there and everything they need, at the versions the store
holds.
A dependency goes where the package that needs it goes. A package meant for the initramfs, such as a boot hook, must be placed there by the spec, even when a package of the live system depends on it. For the details, see ISO Specs.
How it boots #
- UEFI firmware starts the UKI from the medium's EFI system partition, and the kernel starts prelude from the initramfs.
- prelude runs the live-boot hook, which finds the medium: it tries each
disc, disk and stick with an ISO9660 filesystem, waiting a few seconds
for a USB stick to appear, and keeps the one whose
/peios-mediummatches the identifier the initramfs holds. Another Peios medium attached alongside is never taken for it. - The hook checks the medium's image against the SHA-256 hash the
initramfs holds, and mounts it read-only as the system's
/usr, under a root on a fresh tmpfs. The system's/usr/inventoryrecords what the spec asked for and what was chosen. The hook makes what/live.layoutlists, and applies the system's root skeleton file, which gives the system its directories outside/usrand the/lib64link. It moves the medium's mount to/media/peiosin the system, where the image is read from and an installer reads the store. - prelude switches to the live system and starts its init.
If the hook can't find the medium, or the image isn't the one the
initramfs names, prelude opens its recovery shell when the kernel command
line holds rd.shell.
The live system reads its /usr from the medium, so the medium must stay
attached while it runs. Everything else lives in memory, so nothing the
system writes survives a restart.
Building an ISO
Peios / Developing for Peios / Building ISOs
peiso build builds a bootable Peios ISO from packages you have built.
Do this to try a set of packages as a whole system, or to make a medium
to boot a machine from. For what an ISO holds, see
Peios ISOs.
Before you start #
- Install
peiso, andmkirfandmkukifrom peiosutils, or know where they are. - Install
mkfs.vfat, mtools,xorriso, andmksquashfsfrom squashfs-tools 4.6 or later.peisoruns them, without any privilege. - Have the packages in an artifact directory, such as one that
pekitpacks into. The live system needs a shell and an init, and the initramfs needs prelude, the live-boot hook, and a shell. Packages bring what they depend on or require, so the artifact directory needs those packages too. - Have the kernel package,
dev.peios.kernel, in the artifact directory too, or a Peios kernel image built with its EFI stub.
Write the spec #
Write the spec, such as peios.toml, beside the artifact directory. Paths
in it are relative to the spec:
= true
[[]]
= "artifacts"
[]
= "dev.peios.kernel"
= "console=ttyS0 rd.shell"
[[]]
= "net.busybox.busybox"
= true
[[]]
= "dev.peios.ppk"
[[]]
= "dev.peios.prelude"
= false
= true
[[]]
= "dev.peios.live-root"
= false
= true
The kernel comes from its package, which the ISO carries in its store.
The live system is busybox and ppk, and the initramfs holds busybox,
whose shell the live-boot hook runs, with prelude and the hook itself.
Each place also holds every package its packages depend on or require,
and each package is carried at the newest version the artifact directory
holds, unless the spec gives a version. For every key, see
ISO Specs.
Check what the spec brings #
Run peiso resolve to list every package the ISO would carry, without
building it:
Each line is a package, the places that hold it, and what first asked for it. A package in neither place is in the store only:
dev.peios.kernel@0.25.0-indev-1?arch=x86_64 store (the request for dev.peios.kernel)
dev.peios.prelude@0.0.7-1?arch=x86_64 initramfs (the request for dev.peios.prelude)
org.gnu.glibc@2.44-1?arch=x86_64 liveboot,initramfs (net.busybox.busybox@1.37.0-1 requires libc.so.6)
Build the ISO #
Run peiso build with the spec and where to write the ISO:
Give --mkirf, --mkuki and --mksquashfs with their paths if they
aren't on PATH.
peiso says what it is doing, and prints the ISO's path when it is done:
peiso: fetching net.busybox.busybox@1.37.0-1?arch=x86_64
peiso: fetching dev.peios.ppk@0.1.0-1?arch=x86_64
peiso: fetching dev.peios.prelude@0.0.7-1?arch=x86_64
peiso: fetching dev.peios.live-root@0.1.0-1?arch=x86_64
peiso: fetching dev.peios.kernel@0.25.0-indev-1?arch=x86_64
peiso: writing the live system's image
peiso: composing the initramfs
peiso: building the UKI
peiso: writing the ISO
peios.iso
Boot it #
Boot the ISO in QEMU with OVMF, its UEFI firmware. OVMF writes to its variables, so give it a copy of them:
prelude reports each step of boot on the console, and starts the live system's init. The live-boot hook says where it found the medium, and checks the live system's image before it mounts it:
ppk-live-root: found the medium on /dev/sr0
ppk-live-root: checking the live system's image
To boot a computer, write the ISO to a USB stick and start the computer from it. The ISO is also a disk with an EFI system partition, so it boots from a stick as it does from a disc.
If peiso refuses #
peiso checks the spec and resolves every package before it builds
anything. It refuses a package, or a dependency, that no repository
holds at a version that will do, and says what needed it:
peiso: dev.peios.peios-experimental@2026.8-11 depends on dev.peios.bootconfig >= 0.21.0-alpha11-1, but no artifact directory holds dev.peios.bootconfig for x86_64: artifacts
It refuses a spec with no package in the live system, or none in the initramfs, since such an ISO couldn't boot. It also refuses what a spec can say but Peios can't do yet, such as a repository on the network, and says why.
If a tool it runs fails, peiso stops and shows what the tool said.
ISO Specs
Peios / Developing for Peios / Building ISOs
An ISO spec is a TOML file that says which packages an ISO carries, where they come from, and where each goes. Paths in it are relative to the spec's directory. Any key not listed here is an error, so that a misspelt key can't silently change nothing.
Top-level keys #
| Key | Default | Meaning |
|---|---|---|
edition | The Peios edition the live system is, such as "Experimental". Its package is dev.peios.peios- followed by the edition in lowercase, such as dev.peios.peios-experimental, and the live system holds it and everything it needs. | |
edition_package | The package of an edition that isn't one of Peios's own, such as com.example.peios-inhouse, in place of edition. Give one or the other. | |
version | the newest | The edition package's version, as for a [[package]]. |
disable_default_repos | false | Leave out the default repository, pkgs.peios.org. It isn't available yet, so a spec must set this to true and give a [[repository]]. |
Repositories #
Each [[repository]] is a place packages come from. A package is taken
from the first repository, in the order given, that holds the version
chosen. If two hold the same version of a package, they must agree on what
it is.
| Key | Meaning |
|---|---|
filepath | An artifact directory. Required. |
Kernel #
[kernel] is the kernel the ISO boots: a package, such as
dev.peios.kernel, or a file. Give one or the other.
| Key | Default | Meaning |
|---|---|---|
package | The package holding the kernel, at usr/lib/modules/vmlinuz. The ISO carries it in its store, with what it needs, and a [[package]] naming it says where else it goes. | |
version | the newest | The kernel package's version, as for a [[package]]. |
file | A kernel image on this machine, built with its EFI stub. | |
cmdline | empty | The kernel command line. rd.shell makes prelude open its recovery shell if boot fails. |
Packages #
Each [[package]] is a package the ISO carries, and says where it goes.
There are four places: the live system's /usr, an installed system's
/usr, the live medium's initramfs, and an installed system's initramfs.
Every package is in the ISO's store wherever else it goes, so a package in
none of them is carried for fetching from later. An edition's package can't
also be given as a [[package]].
| Key | Default | Meaning |
|---|---|---|
name | The package's name. Required, and given once. | |
version | the newest | The versions that will do, as a version constraint, such as ">= 1.2". A version on its own, such as "1.2.0-1", is that version exactly. The newest version that will do is carried. |
root | true | Shorthand for liveboot and installed together. |
liveboot | root | Whether the live system holds the package and everything it needs. |
installed | root | Whether an installed system's /usr, its SYSTEM closure, holds it. |
initramfs | false | Shorthand for liveboot_initramfs and installed_initramfs together. |
liveboot_initramfs | initramfs | Whether the live medium's initramfs holds it. |
installed_initramfs | initramfs | Whether an installed system's initramfs, its INITRAMFS closure, holds it. |
A place named on its own overrides its shorthand. So most packages need
none of these, a package only for the live medium has installed = false,
and one only for the initramfses has initramfs = true and root = false.
The live medium's boot hook has liveboot_initramfs = true and an installed
system's installed_initramfs = true, each with root = false.
At least one package must be in the live system, and at least one in the live medium's initramfs. A spec with no package in an installed system can't be installed from; one with packages there must also have one in an installed system's initramfs.
What packages bring #
A package brings every package it depends on, and a package providing
each capability it requires, such as sh or libc.so.6. peiso chooses
them with ppk's resolver, from the edition's package, the kernel
package, and every [[package]] together:
- Each package name is chosen once, at the newest version that satisfies what asks for it first. Anything that asks for another version is an error, which names both.
- A capability is satisfied by a package already chosen if one provides
it. Otherwise, the package providing it is chosen. If several packages
provide it, name the one to carry with a
[[package]].
The ISO's store holds every package chosen. The live system holds the
edition, each package with liveboot = true, and everything they need, and
each other place likewise holds its packages and everything they need. An
installed system holds the edition too. A place takes the versions and
providers the store holds, so
the live system and the initramfs never hold two versions of a package.
A dependency goes where the package that needs it goes, and nowhere else.
A package of the live system can depend on one meant for the initramfs,
such as dev.peios.live-boot on its boot hook, dev.peios.live-boot-irf.
The live system then holds the hook as well, and the initramfs holds it
only if the spec places it there.
To see what a spec brings before building it, run peiso resolve. See
Building an ISO.
Registry seeds #
Packages ship seed masters under /usr/share/regim, but the spec chooses
which the image applies. No release metadata is read for this policy.
[]
= ["base-service"]
= ["seeds/console-shell.reg"]
= ["first-boot"]
All three lists default to empty. A bare seed name selects
usr/share/regim/<name>.reg from the composed live closure, including
dependencies. A package carried only in the store or initramfs cannot
supply it. A relative path ending in .reg selects a file beside the
spec, staged using its filename. Names use ASCII letters, digits, dots,
underscores, and hyphens. Absolute file paths, unknown keys, and duplicate
destination names, within or across queues, are errors.
| List | Medium directory | Applied on |
|---|---|---|
apply | /lcl/policy/autoapply.d | The live medium and an installed system. |
live | /lcl/policy/autoapply.live.d | The live medium only. |
install | /lcl/policy/autoapply.install.d | An installed system, after an installer promotes it. |
When any seed is named, peiso also stages the executable
/lcl/policy/autorun.d/10-apply-seeds.sh. The live-root hook copies the
medium's /lcl into the live system's root, preserving modes. After registryd
starts, peinit runs the script, applying the common queue and then the
live queue with reg apply --once-delete. The install queue remains
untouched. An installer must remove the live queue and promote the
install queue into the target's common queue.
Seed files have mode 0644 and the script has mode 0755. Their paths,
contents, and modes contribute to the medium identifier. With no seeds,
peiso stages no /lcl tree.
Layouts #
[initramfs] and [liveboot] give what the initramfs and the live system
hold outside /usr, written as an environment profile's keys are. For the
format, see Environments.
| Key | Meaning |
|---|---|
symlinks | Each link's path and target. A target that starts with : is in usr. |
dirs | Empty directories. |
include | Profile fragments whose links and directories the layout holds as well, each relative to the spec's directory. A fragment that names packages is refused, since the spec chooses those. |
A table replaces the default, rather than adding to it. The defaults are:
[]
= ["proc", "sys", "tmp"]
[]
= { = ":bin", = ":sbin" }
The initramfs's /init isn't in its layout: prelude's package claims it,
and composing the initramfs creates the link. A layout can't also give a
path that a package claims.
A layout needs no directories or links that fsbase's skeleton gives, such
as /var, /lcl, /tmp or /lib64. Each root gets those from the root
skeleton file its own closure holds, at /usr/share/skeleton. Carry
dev.peios.fsbase in the live system and dev.peios.fsbase-irf in the
initramfs. peiso applies the initramfs's file after composing it, and
the live-boot hook applies the live system's at boot, with each
directory's security descriptor. An initramfs can't hold descriptors, so
its directories get none. peiso warns when the initramfs has no skeleton
file.
Don't list a skeleton directory in [liveboot]. The layout's directories
are made first, and the skeleton leaves an existing directory as it is, so
it would lose the skeleton's descriptor.
Refused until supported #
A spec can already use these keys, but peiso refuses each, saying why,
until Peios can do what it asks:
| Key | Needs |
|---|---|
url in a [[repository]] | Repositories on the network. |
autoinstall, offerinstall in a [[package]] | An installer. |
Test Ownership
Peios / Developing for Peios / Qualification
Keep a test beside the component whose contract it checks. A test that needs a VM still belongs to that component if its assertions concern that component's behavior. The VM is apparatus, not an ownership rule.
Choose an owner #
| Test or helper | Owner |
|---|---|
| Unit tests and isolated API checks | The component |
| Native contract tests using a real kernel | The component |
| Behavior across several real services | Integration Tests |
| Complete boot, upgrade, and release qualification | Integration Tests |
| Generic VM lifecycle and host utilities | Provium |
| Component-specific fixtures and helpers | The component |
For example, a resolver test using a stub network manager belongs to resolvd. A scenario asserting behavior across real resolvd and netd belongs to Integration Tests. An authd event test can use eventd as observation apparatus while checking authd's documented event contract.
Keep one maintained copy #
A component exports its suite through tests/integration/suite.json.
The kernel uses peios/tests/integration/suite.json. The manifest lists
owned test files and maps helper and fixture sources into a virtual layout.
Cross-component scenarios have a manifest in the central repository.
The central suites.lock.json records each repository's exact commit and
manifest hash. The runner reads files from those Git objects and assembles
the layout in a fresh run directory. It rejects duplicate export paths.
Shared helpers come from their owning repositories, not copied snapshots
inside each consumer.
Keep fast checks in ordinary component CI. Run native conformance with supplied images and tools. Use the central runner for both component and system selections, so both produce the same provenance and result format.
Preserve migration evidence #
The migration map accounts for 604 imported test files. Imported assertions
retain their historical specification references. One resolver test moves
its inline probe into a supplied tool; its assertions remain unchanged. The
map records source paths and hashes; helper adaptations are listed
separately in migration-adaptations.json.
The central legacy package-event scenario exercises .peipkg. It does not
establish compatibility with PPK blobs and manifests. Archived recipes
preserve fixture requirements without activating retired image builders.
Running Conformance Tests
Peios / Developing for Peios / Qualification
Run the host checks before using the qualification runner. They need pekit on a Linux host:
The qualification runner itself needs Python 3.11 or later and Git.
A native run also needs a suitable QEMU host, the required privileges, networking tools, and Peios images. Provium checks host prerequisites. Prepare images outside the runner, with the fixtures and services described by the selected suite. The archived profile recipes document those inputs.
Prepare the composition #
Copy examples/composition.json. Replace every placeholder with a supplied
path, its hash, and the exact component source revisions in the image.
Calculate a file or directory hash with:
Supply signed guest tools when a test requests them. Their signatures must match the image's trust policy. The runner checks hashes, not signatures; verify signature authority when preparing the supplied artifacts.
Use kernel-only for kernel and network apparatus, prelude for early
boot, and peinit for full-system service tests. A component selection can
need more than one profile. Prelude tests also require PT_MKIRF to name a
recorded artifact; no sibling build or host-path fallback is used.
Select and run tests #
Keep all repositories named by the lock available, including helper owners. The runner reads their recorded Git objects without switching branches. List a component's test files:
Stage a run without starting Provium:
Run with a fresh output directory. Avoid single quotes and control characters in that path because the imported helpers use shell commands:
Repeat --suite for several components. Select system for the central
scenarios; omit --suite for all test files. An empty selection is an error.
Slow cases are included. A timeout stops the runner and its child processes.
Component bundles also expose a check-integration script.
Set PEIOS_QUALIFY to the central executable and supply the same lock,
composition, and fresh output path. These entry points do not build images.
Test a candidate #
Commit the candidate suite and use a clean checkout. Add an explicit
--candidate authd=/path/to/authd to select its committed test source.
This overrides one suite pin and records the selected commit. It does not
replace the image or infer which binaries the image contains.
Update the supplied composition when testing candidate binaries. Keep the test revision and image component revision distinct in the result record. After reviewing permanent suite changes, refresh the lock deliberately:
Review the lock diff before committing it. Pin updates are separate from running tests and do not publish any repository.
Composition Format
Peios / Developing for Peios / Qualification
A composition is a JSON object with format set to 1.
Paths in artifacts are absolute or relative to the composition file.
Every artifact has a path and sha256. Other fields refer to an artifact
with an object such as {"artifact": "kernel"}.
Fields #
| Field | Meaning |
|---|---|
mode | system by default; harness for local runner checks |
artifacts | Named regular files or directory trees and their hashes |
runner | Artifact reference for the executable Provium runner |
components | Image component names mapped to exact Git commit IDs |
profiles | Named boot profiles using recorded artifact references |
host_tools | Executable names mapped to supplied artifact references |
guest_tools | Test tool names with unsigned and optional signed inputs |
environment | Explicit PT_* and supported *_TEST_* artifacts |
packages | Optional declared package identities and manifest references |
file_timeout_seconds | Per-file timeout; default 300 seconds |
System mode requires a declared component composition, boot profiles, and a
recorded qemu-system-x86_64 executable. Harness mode uses Provium's local
backend, skips VM host preflight, and never produces OS qualification.
The host runtime remains a dependency in either mode. Local mode requires
selected test manifests to declare harness_only: true; ordinary native
suites cannot run on the local backend.
The image composition is an operator declaration. The runner does not
inspect an image to prove that its binaries came from those commits.
Package declarations use name, version, arch, and manifest.
The runner checks that each supplied manifest has the declared identity;
it does not resolve dependencies, install packages, or verify image contents.
Profile inputs #
A profile accepts kernel, initrd, root, cmdline_file, and
agent_overlay_path as artifact references. It also accepts cmdline,
guest_os, inject_agent, and agent_boot_timeout as ordinary values.
Every profile needs a kernel or a root containing one. Agent injection
requires an explicit agent overlay.
A disks entry accepts path, id, readonly, and mediated.
Its path is an artifact reference. Writable disks use separate working
copies; read-only media keep their supplied snapshot. Final working-disk
hashes are recorded separately from original input hashes.
Build commands and profile discovery directories are rejected. The runner
passes --no-build to Provium and writes its own explicit configuration.
The historical build.sh and sign.sh helper names resolve supplied guest
tools; they do not build or sign anything.
Hashes and storage #
A file hash is SHA-256 of its bytes. A directory hash covers sorted relative
paths, modes, file hashes, and link targets using the runner's canonical
JSON encoding. Use peios-qualify hash for trees. Links must be relative and
remain inside the tree. Special files and symlink artifact roots are rejected.
Each run copies and verifies supplied artifacts before execution. Keep enough disk space for those copies and writable disk snapshots. The output directory must not already exist. Preserve the result directory with the release evidence; its hashes are useful only while the corresponding inputs remain available.
Candidate binary inputs include PEINIT_TEST_BINARY, TRUSTD_TEST_BINARY,
LOREGD_TEST_BINARY, NETD_TEST_BINARY, RESOLVD_TEST_BINARY,
NSS_NET_TEST_BINARY, and NSS_IDENTITY_TEST_BINARY. Service seed inputs
use NETD_TEST_SERVICE or RESOLVD_TEST_SERVICE. All are artifact
references.
The resolver probe uses guest_tools.pt-nss.unsigned; its source and dynamic
linking requirements are in the resolver's integration bundle.
Qualification Results
Peios / Developing for Peios / Qualification
The runner writes run.json before staging inputs and updates it as the run
progresses. It records suite commits, source hashes, supplied artifact
hashes, the composition, command, environment, and host details.
stdout.jsonl preserves Provium's per-file reports. stderr.log preserves
diagnostics, and events.msgpack preserves the event stream.
Status and exit codes #
| Status | Meaning | Exit code |
|---|---|---|
prepared | Inputs staged; no tests executed | 0 |
passed | Every selected file reported successful cases | 0 |
incomplete | At least one case was skipped | 3 |
failed | Failure, timeout, missing report, or changed immutable input | 1 |
blocked | Inputs could not be staged or validated | 2 |
interrupted | The user interrupted execution | 130 |
Malformed arguments also return 2. A file with no reported cases is a failure. Missing or duplicated file reports fail the run. A zero exit code from Provium cannot hide failed cases or an incomplete report set.
qualification is true only for a passed system-mode run. It applies to
the recorded selection and supplied composition, not an entire OS release.
A harness run can pass while qualification remains false.
Release evidence #
Keep component fast checks, native conformance, system scenarios, and release acceptance as separate gates. A successful host check establishes runner behavior; it does not establish that a Peios image boots or that its services work together.
Review the selected suites and skipped cases before accepting a release. Also review the provenance declaration: hashes identify bytes, but do not establish signing authority or prove the declared source-to-image mapping. The runner records selected host executable hashes; host libraries, QEMU data files, privileges, and kernel behavior remain environmental inputs.
Candidate overlays, such as PT_EVENTD_ROOT, must be supplied as hashed
artifacts. A test that requires an absent candidate overlay can skip; the
result then remains incomplete. Do not treat that as a successful release
gate or suppress the skip to make the result green.
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.
1.1 Overview
Peios / Developing for Peios / Go SDK Reference / Go SDK Conventions
The Go SDK uses Go values and interfaces for portable formats and native Peios operations. Its package documentation describes each public API; this chapter explains the ownership and authority rules shared by them.
1.1.1 Packages and authority #
Security formats and MessagePack codecs run without a Peios kernel. Native file, token, socket, process, registry, and event operations target Linux on x86-64 with the Peios kernel interface. Compiling on another Linux system does not supply those operations.
Native errors use syscall.Errno and support errors.Is. An access check
reports a decision; the kernel still checks authority when you perform
the operation. Process creation uses Go's os/exec and normal kernel
inheritance. Activating process mitigations cannot clear existing bits.
1.1.2 Handles and buffers #
Close owned token, key, transaction, and file handles. Operations accepting
syscall.Conn protect a descriptor from concurrent close and reuse during
the call. A raw directory descriptor remains your responsibility: keep it
open throughout the operation.
Descriptor parsers and event readers return owned data. Borrowed MessagePack cursor views remain tied to the caller's input buffer. MessagePack maps preserve pair order and duplicate keys. Decoder position advances only after a successful decode.
1.1.3 Identity scopes #
Token.Impersonate runs its callback on a dedicated, locked thread.
The scope restores identity before returning and retires the thread if
restoration fails. A callback panic is rethrown after cleanup.
WithIdentityThread supports repeated identity changes within one locked
thread. The scope rejects calls after the callback or from another thread.
Neither API transfers its identity to goroutines created by the callback.
Installing a process token is a separate operation.
1.1.4 Security formats #
Binary descriptors retain entry order, unknown entry bodies, and metadata that text cannot express. Text formatting rejects unsupported entries rather than discarding them. An absent discretionary access control list (DACL) differs from an empty one. The present-null form is rejected.
Conditions have a 128-level expression limit, including long AND or OR
chains. Parsing rejects deeper expressions with EINVAL, matching the
formatter. Nested operands also have a depth bound.
Inheritance resolves creator identities and generic rights for the receiving object. It preserves explicit entries and protected lists. Stripping inherited entries preserves descriptor metadata and revision floors. Parsed lists can retain exact revision bytes during serialization.
1.2 Registry and Event Lifetimes
Peios / Developing for Peios / Go SDK Reference / Go SDK Conventions
Registry keys and event rings expose state that can change while your application reads it. The Go SDK gives returned data an explicit lifetime and reports changes that prevent a complete read.
1.2.1 Registry values and sources #
Registry writes use the base layer when Layer is empty. A nil or zero
expected sequence disables compare-and-set. Delete operations reject an
expected sequence because their kernel operation has no comparison field.
Notifications are armed and read on the same key handle.
Allocating value helpers have a 16 MiB limit. QueryInto, ValuesInto,
and ValueAtInto accept caller buffers; a nil buffer probes the required
size and returns ERANGE. Batch counts are meaningful on success, and a
size probe can report zero records.
TakeFile and TakeTransactionFile transfer descriptor ownership into
registry handles. Close the resulting handle rather than closing its
adopted descriptor separately.
registry/source.Source.Serve bounds concurrent handlers and serializes
response writes. It closes the source on return or cancellation, waits
for workers, and reports transport errors. Handlers must observe
cancellation and provide storage and transaction semantics. Decoders
permit trailing extension fields; the handler chooses its version policy.
1.2.2 Events and waits #
AttachAll visits the complete CPU slot range and skips empty slots.
Each reader begins at its oldest surviving record and follows resizes.
Returned events own their data and survive subsequent reads or closure.
Drain Next until no event is available, then wait with Wait(ctx).
Cancellation or close can take up to 50 ms to interrupt a futex wait.
Lost counts observed sequence gaps, not losses before attachment.
Readers do not establish an ordering between different CPUs.
Low-level attachments and mappings have separate lifetimes: close both.
EventAt returns owned data and a wire size, or EAGAIN for an empty,
overwritten, or changed slot. Advance the absolute cursor by the wire
size. A generation change requires a fresh attachment and mapping.
A context deadline bounds Ring.Wait. A canceled context permits a
nonblocking readiness check; available data takes precedence over
cancellation in that low-level method.
Emission policy is read afresh for each call. Essential events bypass
registry policy; other tiers use defaults and the deepest valid Enabled
value. This avoids retained watch handles at the cost of registry work
on each policy check.
1.2.3 Messages and sessions #
A received socket message owns its delivered handles. Call Message.Close
when finished. Receive closes all delivered handles if control data is
truncated. ReceivePartial keeps handles that fit, closes excess handles,
and reports truncation flags for the caller to assess.
A partial send does not resend ancillary data. Zero-length sequence-packet messages can transfer handles without an extra payload byte.
OpenSessions returns a snapshot reader. Next returns io.EOF at the
end; a malformed line returns EPROTO and is consumed so reading can
continue. Closing the last token destroys a used dynamic session.
DestroyEmptySession handles an unused session. Session enumeration
requires the appropriate classified securityfs mount and access rights.
2.1 Security Descriptors and Selectors
Peios / Developing for Peios / Go SDK Reference / Go SDK Security
security.SecurityInformation is the bitmask that selects components of a
security descriptor. Use its named constants with file and registry descriptor
operations:
| Constant | Value | Selected component |
|---|---|---|
security.InfoOwner | 0x01 | Owner SID. |
security.InfoGroup | 0x02 | Group SID. |
security.InfoDACL | 0x04 | Discretionary ACL. |
security.InfoSACL | 0x08 | Full system ACL. |
security.InfoLabel | 0x10 | Mandatory-integrity label within the SACL. |
Combine selectors with |, for example security.InfoOwner | security.InfoDACL. InfoLabel can accompany owner, group, or DACL selection,
but must not be combined with InfoSACL; the kernel rejects that
combination with EINVAL.
InfoLabel reads or writes a descriptor containing the label ACE in its SACL.
Its payload is not a raw integrity SID. Reading the label requires
READ_CONTROL; writing it requires WRITE_OWNER. Raising a label above the
caller's integrity also requires SeRelabelPrivilege. Selecting the full SACL
instead requires ACCESS_SYSTEM_SECURITY, gated by SeSecurityPrivilege.
Updates preserve components that were not selected. In particular, selecting
only InfoLabel changes the mandatory label without replacing the other SACL
entries. All selected components must pass their applicable authorization
checks.
2.1.1 File descriptors #
file.GetDescriptor(f, info) returns owned descriptor bytes;
file.SetDescriptor(f, info, sd) applies selected components from binary
descriptor bytes. Both accept syscall.Conn, including *os.File. The
path-relative variants are file.GetDescriptorAt(dirfd, path, info, flags)
and file.SetDescriptorAt(dirfd, path, info, sd, flags).
For example, read and parse the mandatory label:
package example
import (
"os"
"github.com/peios/peios-go/file"
"github.com/peios/peios-go/security"
)
func readLabel(f *os.File) (security.Descriptor, error)
To request a medium-integrity, no-write-up label, build the descriptor and select only its label:
func setMediumLabel(f *os.File) error
The second example uses the first example's imports. These functions perform native Peios operations and still depend on the caller's authority; constructing valid SDDL does not grant permission to set it.
2.1.2 Registry keys #
(*registry.Key).GetDescriptor(info) returns binary descriptor bytes, and
(*registry.Key).SetDescriptor(info, sd, tx) writes selected components. They
use the same security.Info* selectors, including InfoLabel, and the same
prohibition on combining label and full-SACL selection. Pass a
*registry.Transaction for a transactional update, or nil for an update
without an explicit transaction.
Use security.ParseDescriptor to decode returned bytes and
Descriptor.MarshalBinary to encode a descriptor for an update.
security.ParseSDDL is available when constructing a descriptor from text. An
absent DACL and an empty DACL are different: preserve that distinction when
building or rewriting descriptors.