Peios Learn
Documentation

Peios

Peios Peios Kernel Universal Directory Project

Developer Tools

Trail Acta Provium clackatoo CAF GCSL Pekit

Applications

Framewright

Standards and Conventions

Standards and Conventions Peios Specifications
Peios

Access Control

Single-page view · as markdown

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:

NounWhat it isSDK home
SIDThe 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
TokenThe 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 checkThe 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:

  1. Get the subject's token. Usually the caller's — often through peios_token_open_peer on a socket, so you learn who connected — or your own effective token (token_fd = -1).
  2. 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 a peios_sd_builder.
  3. Run the check. peios_access_check tells 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 = peios_token_open_self(0, KACS_TOKEN_QUERY);
if (tok < 0) { /* errno */ }

unsigned char sid[PEIOS_SID_MAX_BYTES];
ssize_t n = peios_token_user(tok, sid, sizeof sid);   /* the user SID */

uint32_t il;
peios_token_integrity(tok, &il);                      /* integrity level RID */

struct peios_privilege_set privs;
peios_token_privileges(tok, &privs);                  /* held/enabled privileges */

close(tok);

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 = accept(listener, NULL, NULL);
int caller = peios_token_open_peer(conn);   /* QUERY | IMPERSONATE rights */
if (caller < 0) { /* errno */ }

/* 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 (peios_token_impersonate(caller) != 0) { /* errno */ }

/* ... do the work here: file opens, access checks, etc. all run as the caller ... */

peios_token_revert();   /* back to your own identity */
close(caller);

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 = socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
connect(jobs, ...);                                   /* who may submit is who may connect */

const char *req = "{\"command\":\"submit\",\"image_path\":\"/usr/bin/backup\"}";
if (peios_socket_send_message(jobs, req, strlen(req), user_token, NULL, 0, 0) < 0) {
    /* EACCES: user_token lacks TOKEN_IMPERSONATE; EPERM: the attach would lower its level */
}

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_IMPERSONATE on 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_message gives the manager a token handle with QUERY | IMPERSONATE | DUPLICATE — enough to inspect the identity, check its level with peios_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_pidfd and peios_token_open_process — the kernel's handle on the peer, never a PID the peer named — which is fork-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 = {
    .privs_to_delete = KACS_SE_DEBUG_PRIVILEGE | KACS_SE_IMPERSONATE_PRIVILEGE,
    .flags           = KACS_TOKEN_RESTRICT_WRITE_RESTRICTED,
};
int weak = peios_token_restrict(my_primary, &spec);

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.h reference — 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 = peios_acl_builder_new();
peios_acl_builder_allow(acl, owner_sid, owner_len, KACS_ACCESS_ALL, 0);
peios_acl_builder_allow(acl, viewers_sid, viewers_len, KACS_ACCESS_READ, 0);

size_t acl_len;
const void *acl_bytes = peios_acl_builder_bytes(acl, &acl_len);

/* Wrap it in a security descriptor with an owner. */
peios_sd_builder *sd = peios_sd_builder_new();
peios_sd_builder_owner(sd, owner_sid, owner_len);
peios_sd_builder_dacl(sd, acl_bytes, acl_len);

size_t sd_len;
const void *sd_bytes = peios_sd_builder_bytes(sd, &sd_len);

(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 = {
    .token_fd = caller_fd,               /* or -1 for my own token */
    .sd       = sd_bytes, .sd_len = sd_len,
    .desired  = KACS_ACCESS_READ | KACS_ACCESS_WRITE,
    .mapping  = peios_file_generic_mapping,
};

uint32_t granted = 0;
int rc = peios_access_check(&req, &granted, NULL);

Step 4 — interpret the result #

if (rc == 0) {
    /* Every desired right was granted. */
} else if (errno == EACCES) {
    /* Denied. `granted` still holds what WAS allowed — for example maybe READ
       succeeded but WRITE did not. Decide per-right from `granted`. */
    bool may_read  = granted & KACS_ACCESS_READ;
    bool may_write = granted & KACS_ACCESS_WRITE;
} else {
    /* A real error: bad token fd, malformed SD, etc. */
    perror("access_check");
}

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 = {
    .key = "name", .value_type = PEIOS_AUDIT_STR,
    .bytes = "jellyfin", .len = strlen("jellyfin"),
};
uint8_t ctx[128];
ssize_t n = peios_audit_context_encode("service", &name, 1, ctx, sizeof ctx);
req.audit_context = ctx;
req.audit_context_len = (size_t)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.h reference — 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.

  1. Initialize struct peios_open_params to zero.
  2. Set desired_access to the file rights the caller needs.
  3. Choose the disposition that matches the operation. Use KACS_DISPOSITION_CREATE when an existing path must be an error, or KACS_DISPOSITION_OPEN when the file must already exist.
  4. For creation, supply the creator descriptor when required by the application's security policy. For an existing file, leave sd as NULL and sd_len as zero.
  5. Call peios_file_open and check its return value before using the descriptor or the status output.
  6. 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).

  1. Choose peios_fd_get_sd when the application already owns a suitable handle. Otherwise, use peios_file_get_sd with the intended path policy.
  2. Probe the required length with a zero-capacity buffer and check for failure before converting the result to size_t.
  3. Allocate the buffer and check that allocation succeeded.
  4. Repeat the query. If the descriptor grows and the call reports ERANGE, probe again or stop according to the application's retry policy.
  5. Parse only the bytes returned by a successful query.
  6. 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:

  1. Create a builder and check that it is not NULL.
  2. Add the replacement components, such as the DACL.
  3. Obtain the encoded bytes and check for a retained builder error.
  4. Call peios_fd_set_sd or peios_file_set_sd with the corresponding KACS_SECINFO_* selection.
  5. 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:

#include <stdio.h>

#include <peios/process.h>

int main(void)
{
    /* Enforce W^X and speculation mitigation lock; abort on failure. */
    if (peios_process_set_mitigations(-1, KACS_MIT_WXP | KACS_MIT_SML) != 0) {
        perror("set_mitigations");
        return 1;   /* refuse to run unhardened */
    }
    /* ... the rest of the program runs with those protections on ... */
}

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_ALL is the mask of all valid bits — useful for validating input, not usually what you'd blanket-enable without thought.
  • KACS_MIT_CFI is a legacy alias that expands to KACS_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.h reference — the call in full.
  • Process mitigations — every mitigation and its threat model.

Peios Learn — documentation for Peios software.

Built with Trail.