# File security

---

# File security

_Peios Kernel / Internals / KACS / File security_

> Find the Peios kernel articles about file security.

Use these articles to understand file security in the Peios kernel.

- [The Handle Model](</kernel/internals/kacs/file-security/the-handle-model.md>)
- [KACS-Native Open](</kernel/internals/kacs/file-security/kacs-native-open.md>)
- [Legacy Open Compatibility](</kernel/internals/kacs/file-security/legacy-open-compatibility.md>)
- [Use-Time Semantics](</kernel/internals/kacs/file-security/use-time-semantics.md>)
- [Descriptor storage and caching](</kernel/internals/kacs/file-security/descriptor-storage-and-caching.md>)
- [Mount classes and bootstrap descriptors](</kernel/internals/kacs/file-security/mount-classes-and-bootstrap-descriptors.md>)
- [The Set-Security Interface](</kernel/internals/kacs/file-security/the-set-security-interface.md>)
- [Sharing and Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md>)
- [Byte-Range Locks](</kernel/internals/kacs/file-security/byte-range-locks.md>)
- [Leases](</kernel/internals/kacs/file-security/leases.md>)
- [Special Attributes](</kernel/internals/kacs/file-security/special-attributes.md>)

---

# The Handle Model

_Peios Kernel / Internals / KACS / File security_

> FACS is the file-specific enforcement surface of KACS — mount policy, scope, how a handle is acquired, and stacked backing files.

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

FACS, the File Access Control Shim, is the file-specific enforcement
surface of KACS. It replaces Linux DAC — UID, GID and mode-bit checks
— with security-descriptor evaluation on files.

Enforcement follows the handle pattern. AccessCheck runs once at open
time, the granted mask is cached on the file description, and later
operations test the cached mask:

```
(fd.granted & required) == required ? allow : deny
```

The mask is set once and never modified, and it is immutable for the
descriptor's whole lifetime regardless of any later descriptor change. <a id="cite-facs.handle.mask-immutable"></a>
A file's DACL can be rewritten while a process holds it open, and that
process keeps the rights it was granted. A few operations use a live
AccessCheck instead; [Use-Time Semantics](</kernel/internals/kacs/file-security/use-time-semantics.md#trm-3-9-4>) lists them.

A second immutable mask is stamped alongside it: the **continuous
audit mask** ([Auditing in AccessCheck](</kernel/internals/kacs/access-check/auditing-in-accesscheck.md#trm-3-8-9>)), which every use-time operation consults to
decide whether to emit a per-operation audit event. It travels with
the granted mask through every path described below. <a id="cite-facs.handle.audit-mask-stamped"></a>

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

## Mount policy

Every mounted filesystem exposes exactly one FACS mount-policy class,
scoped to the kernel superblock object rather than to a pathname or a
bind mount — several paths or bind mounts over one superblock all
observe the same class. <a id="cite-facs.handle.policy-per-superblock"></a>

**`unmanaged`** puts the mount outside the handle model entirely: no
granted mask is stamped on its file descriptions. <a id="cite-facs.handle.unmanaged-no-mask"></a> **`facs_deny_missing`**
is FACS-managed and denies access where a descriptor is missing.
**`facs_synthesize_ephemeral`** synthesises missing descriptors and
caches them in memory only. **`facs_synthesize_persistent`**
synthesises them and writes them back immediately. The three `facs_*`
classes are the only managed ones.

The default classifier is conservative. Hardcoded pseudo-filesystems —
`/proc`, `/sys`, nullfs — are `unmanaged`. Filesystems that cannot
reliably store the canonical descriptor xattr are
`facs_synthesize_ephemeral`: ramfs, FAT, exFAT, NFS client mounts,
ISO9660, and cgroup2. StrataFS is fixed at `facs_deny_missing`. Everything else
— tmpfs, squashfs, ext4, btrfs — defaults to `facs_deny_missing`
unless a trusted policy agent adopts it.

Userspace cannot set a superblock to `unmanaged` through the public
ABI; the class is reserved for the kernel classifier and the hardcoded
rules. Attempting to set a policy on a magic-derived `unmanaged`
superblock fails with `EOPNOTSUPP`, and so does attempting to change
StrataFS's. <a id="cite-facs.handle.unmanaged-not-settable"></a>

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

## Scope

The sole-authority claim covers local FACS-managed filesystems. It
does not cover:

- `O_PATH` descriptors, which are not managed;
- NFS client mounts, which are ephemeral-synthesising and retain dual
  authority with the server;
- `/proc`, which is unmanaged and PIP-protected; or
- `/sys`, which is unmanaged and carries a hardcoded rule instead —
  writes there require Administrators or SYSTEM, enforced against a
  built-in descriptor. <a id="cite-facs.handle.sysfs-write-builtin-descriptor"></a>

Descriptors for processes obtained through `pidfd` bypass FACS at open
as well. <a id="cite-facs.handle.pidfd-bypasses-open"></a>

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

## Handle acquisition

A descriptor carries its granted mask through every acquisition path,
and transfer is an intentional capability-delegation mechanism.

- `dup`/`dup3` and `fork` produce the same open file description and
  therefore the same rights; <a id="cite-facs.handle.dup-fork-same-rights"></a>
- descriptors without `FD_CLOEXEC` survive exec unchanged; <a id="cite-facs.handle.exec-preserves-mask"></a>
- `SCM_RIGHTS` transfers the descriptor as a capability token, with
  possession as authorization and no re-check of the receiver's
  identity; and <a id="cite-facs.handle.scm-rights-capability"></a>
- `pidfd_getfd()` is gated by an AccessCheck for `PROCESS_DUP_HANDLE`
  against the target process, after which the caller receives the
  descriptor with its full mask. <a id="cite-facs.handle.pidfd-getfd-gate"></a>

The security boundary is at open time. Every subsequent transfer
carries the mask unchanged.

This means mandatory subject policy — MIC and PIP — is evaluated once,
at open, against the opener. <a id="cite-facs.handle.mic-pip-at-open"></a> A high-integrity process that opens a
file and passes the descriptor to a low-integrity one has effectively
delegated its access. That is the handle model: authority is on the
handle, not on the holder.

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

## Stacked backing files

When a stacking filesystem creates a kernel-private backing file for a
managed user-visible file, the outer file's granted and continuous
audit masks are captured into the backing-file blob, and the backing
file's ordinary blob receives that exact snapshot when the provider is
opened. <a id="cite-facs.handle.backing-snapshot-captured"></a> No new AccessCheck runs against the task executing the
stacking filesystem. <a id="cite-facs.handle.backing-no-new-accesscheck"></a>

The inheritance is deliberately narrow. It is admitted only through
the kernel's typed backing-file allocation path, only from a managed
non-`O_PATH` outer file, and it retains no reference to that outer
file — only the values. <a id="cite-facs.handle.backing-admission-narrow"></a> It is not a general snapshot-cloning
mechanism.

An active StrataFS copy-up context takes precedence: a backing open
that does not match its exact object and phase does not fall back to
inherited authority. <a id="cite-facs.handle.copy-up-context-precedence"></a> When an exactly-bound copy-up backing file is
adopted by the outer descriptor, the outer snapshot is installed into
both blobs as a single transition, after which the backing file
behaves like any other stacked open.

For an OverlayFS provider, this handoff also reaches the exact private
backing files opened beneath the staged file. KACS validates the bounded
chain before changing any snapshot, then copies the original outer handle's
granted and continuous-audit masks into both blobs of every admitted file.
The handoff runs after the staged open and before publication. It does not
relax the active copy-up context's object and phase checks.

The user-visible operation is checked and continuously audited once,
against the outer handle. Immediate provider re-entry through
`security_file_permission` or `security_mmap_file` neither repeats the
caller authorization nor emits a second caller audit event. <a id="cite-facs.handle.no-duplicate-provider-check"></a> The
backing file keeps the snapshot for later descriptor-local
enforcement, including `mprotect()` after a stacked mmap, and the
`mmap_backing_file` handoff verifies that the outer, backing and
captured snapshots still agree before the provider mapping is
installed. <a id="cite-facs.handle.mmap-backing-verifies-agreement"></a>

This suppresses duplicate *KACS* authorization only. It bypasses
nothing else — not another LSM, not filesystem errors, not read-only
mounts, immutable state, quota, space, I/O, or format validation. <a id="cite-facs.handle.backing-suppresses-kacs-only"></a>

## Operational consequences

Treat a transferred descriptor as a capability carrying its established
rights. Passing it to a less privileged process does not rerun the original
open against the receiver's token. Fork can retain those open descriptions;
exec retains descriptors without close-on-exec. Review descriptor inheritance
as part of a launcher or request broker's authority design.

Changing a descriptor, token, or central policy does not retrospectively
revoke that cached file-handle grant. Conversely, losing a token privilege
does not prove an old descriptor lost its usable rights. Test changed policy
with fresh opens. Mappings have their own creation-time checks and page
permissions, not a fresh policy decision for every memory access.

An `O_PATH` handle does not carry ordinary data-access authority; descriptor
management uses its documented live checks. Append-only authority does not
authorize truncation or shared writable mapping. A remote filesystem can also
apply server-side authority after the local check. These boundaries belong
to [use-time semantics](/kernel/internals/kacs/file-security/use-time-semantics.md)
and [legacy-open compatibility](/kernel/internals/kacs/file-security/legacy-open-compatibility.md),
not a general promise that every operation consults only one immutable mask.

---

# KACS-Native Open

_Peios Kernel / Internals / KACS / File security_

> Opening a file by naming every right up front — handle modes, rights granted through the parent, share access, create dispositions, the creator's access and what the open reports.

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

> [!IMPORTANT]
> The [open-interface comparison](/kernel/userspace/native/kacs/abi-status-and-naming-differences.md#trm-3-d-6) records unresolved differences and the [limited pinned-source findings](/kernel/userspace/native/kacs/abi-status-and-naming-differences.md#trm-3-d-6-1) applied here. Creator-SD rejection, the accepted create-option bits, and native-open versus SD-query no-follow behavior were checked in source; the other differences remain unresolved. No runtime test or historical release boundary is established.

`kacs_open` takes an explicit desired access mask. The caller names
every right it will need — `FILE_READ_DATA`, `FILE_WRITE_DATA`,
`WRITE_DAC`, `READ_CONTROL`, any combination — and AccessCheck
evaluates the whole requested mask at open. If every requested right
is granted the descriptor's mask is set to the requested mask; if any
is denied, the open fails. <a id="cite-facs.open.strict-all-or-nothing"></a> This is the **strict** mode, in contrast to
the legacy path's subset behaviour ([Legacy Open Compatibility](</kernel/internals/kacs/file-security/legacy-open-compatibility.md#trm-3-9-3>)).

`MAXIMUM_ALLOWED` asks for everything the caller may have. Any
concrete bits named with it have to be granted; the cached mask is
then the full computed maximum rather than the requested set. <a id="cite-facs.open.maximum-allowed-computes-max"></a>
`MAXIMUM_ALLOWED` may also be named alone. <a id="cite-facs.open.maximum-allowed-alone"></a> The maximum includes
the rights granted through the parent directory, described below, and
excludes the rights a read-only file withholds ([Special
Attributes](</kernel/internals/kacs/file-security/special-attributes.md#trm-3-9-13>)).

A caller reads back what an open was granted with `kacs_query_open`,
which reports the cached mask, the open's share access, and whether the
file is delete-pending. <a id="cite-facs.open.query-open"></a> It is how a caller learns the result of a
`MAXIMUM_ALLOWED` open. The query needs no right: it reveals only what
the descriptor already carries. It fails with `EOPNOTSUPP` on an
unmanaged descriptor, including an `O_PATH` one.

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

## Handle modes <a id="cite-facs.open.handle-modes"></a>

A Linux open file has a mode — readable, writable, or neither — which
the VFS uses for its own accounting, such as write access to an
executable and file leases. A native open derives that mode from the
rights it is granted: `FILE_READ_DATA` gives `FMODE_READ`, either
write right gives `FMODE_WRITE`, and `FILE_EXECUTE` gives `FMODE_EXEC`,
which enables `execveat(fd, "", ..., AT_EMPTY_PATH)`. <a id="cite-facs.open.execute-only-handle"></a>

An open granted none of these is a **control handle**: a managed
descriptor with no data mode, carrying only metadata, security or
delete rights. <a id="cite-facs.open.control-handle"></a> It can read attributes, read and change the
security descriptor, set a delete disposition, rename, and take part in
share checks. It cannot read or write the file's contents. No native
open needs to name a data right to obtain a descriptor. <a id="cite-facs.open.no-required-data-right"></a>

The mode is chosen **before** the file is opened, so that the VFS never
takes write access, read accounting or a lease break for an open that
does not hold the matching right. For an explicit mask the mode follows
the requested bits. For `MAXIMUM_ALLOWED`, KACS first evaluates the
maximum against the file's current descriptor and takes the mode from
the data rights that maximum contains. <a id="cite-facs.open.mode-before-open"></a>

The open hook then runs the authoritative check, as for every open. If
the descriptor changed between the two evaluations, the hook's result
stands. A strict request that is now denied fails as any denied open
does. A `MAXIMUM_ALLOWED` open is stamped with the new maximum, less
any data right its mode cannot exercise, so that `kacs_query_open`
never reports a right the descriptor cannot use. <a id="cite-facs.open.hook-authoritative"></a>

A `MAXIMUM_ALLOWED` open granted a write right takes write access like
any writer. Such an open of a file being executed fails with `ETXTBSY`,
and it breaks other holders' read leases.

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

## Directories

Directory rights share bit positions with file data rights:
`FILE_LIST_DIRECTORY` is `FILE_READ_DATA` (0x0001), `FILE_ADD_FILE` is
`FILE_WRITE_DATA` (0x0002), and `FILE_ADD_SUBDIRECTORY` is
`FILE_APPEND_DATA` (0x0004). A directory open with `FILE_LIST_DIRECTORY`
is opened `FMODE_READ`; a directory open without it is a control
handle. <a id="cite-facs.open.dir-list-mode"></a>

The two write aliases are not cacheable directory handle rights,
though. `kacs_open` rejects a desired mask naming `FILE_ADD_FILE`,
`FILE_ADD_SUBDIRECTORY` or `FILE_DELETE_CHILD` on a directory with
`EOPNOTSUPP`. <a id="cite-facs.open.dir-write-aliases-eopnotsupp"></a> Those are parent-directory authorization rights for
namespace operations, evaluated live at the operation, not rights a
handle carries.

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

## Special nodes and symlinks

Existing FIFOs, pathname socket nodes, and character and block device
nodes on managed mounts are ordinary filesystem file objects for
authorization: the file object type, the file right mapping, and the
file GenericMapping for metadata, standard and generic rights. <a id="cite-facs.open.special-nodes-are-file-objects"></a>

A special node still has to be opened with a data right, because its
driver decides what an open without one means; a FIFO refuses it. A
native open of a special node granted no data right fails with
`EINVAL`. <a id="cite-facs.open.special-nodes-need-data-right"></a> `FILE_EXECUTE` is not a valid data substitute for them — a
`kacs_open` naming it on such a node fails closed. <a id="cite-facs.open.execute-not-valid-on-special-nodes"></a> The Linux object
implementation may still impose its own device- or
filesystem-specific denial after KACS has authorized the file object.

Symlink objects are file objects for `kacs_get_sd`, `kacs_set_sd` and
`readlink`, but they are not opened as terminal objects by
`kacs_open`. Following is the default resolution behaviour, and
`AT_SYMLINK_NOFOLLOW` fails with `ELOOP`. <a id="cite-facs.open.symlink-nofollow-eloop"></a> This differs deliberately
from `kacs_get_sd` and `kacs_set_sd`, where the same flag resolves the
symlink object itself.

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

## Rights granted through the parent <a id="cite-facs.open.parent-grants"></a>

Two rights may be granted by the parent directory when the file's own
descriptor withholds them, as NTFS grants them (MS-FSA 2.1.5.1.2.1):

- **`DELETE`** is granted if the parent grants `FILE_DELETE_CHILD`. <a id="cite-facs.open.delete-through-parent"></a>
- **`FILE_READ_ATTRIBUTES`** is granted if the parent grants
  `FILE_LIST_DIRECTORY`. A caller who may list a directory may already
  see what its entries' attributes would show. <a id="cite-facs.open.read-attributes-through-parent"></a>

AccessCheck runs first against the file. For each of these two rights
that it does not grant, it runs again against the parent directory for
the parent right. The parent is the directory the open resolved the
file through, so for a file with several hard links it is the parent
of the link that was opened. <a id="cite-facs.open.parent-is-opened-link"></a> A `MAXIMUM_ALLOWED` open includes
whichever of the two the parent grants.

The same pair of checks governs every other operation that deletes or
reads attributes by name: unlink, rmdir and rename by path, delete on
close, superseding a file, and `stat` by path ([Use-Time
Semantics](</kernel/internals/kacs/file-security/use-time-semantics.md#trm-3-9-4-2>)). <a id="cite-facs.open.delete-fallback"></a>

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

## Share access <a id="cite-facs.open.share-access"></a>

Every open of a regular file or directory on a managed mount takes part
in NT share-mode checking ([Sharing and Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md#trm-3-9-10>)). A native open
states the sharing it allows in `kacs_open_how.share_access`, read only
when `flags` carries `KACS_OPEN_SHARE_ACCESS`:

| Value | Name | Others may open with |
|---|---|---|
| 0x1 | `KACS_FILE_SHARE_READ` | `FILE_READ_DATA` or `FILE_EXECUTE` |
| 0x2 | `KACS_FILE_SHARE_WRITE` | `FILE_WRITE_DATA` or `FILE_APPEND_DATA` |
| 0x4 | `KACS_FILE_SHARE_DELETE` | `DELETE` |

Without the flag the open shares all three, as a legacy open does, and
`share_access` has to be zero. <a id="cite-facs.open.share-default-all"></a> An open that conflicts with
another fails with `EBUSY` and the status `KACS_STATUS_SHARING_VIOLATION`.

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

## Create dispositions <a id="cite-facs.open.create-dispositions"></a>

| Value | Name | If it exists | If it does not |
|---|---|---|---|
| 0 | `FILE_SUPERSEDE` | Delete and recreate | Create |
| 1 | `FILE_OPEN` | Open | Fail |
| 2 | `FILE_CREATE` | Fail | Create |
| 3 | `FILE_OPEN_IF` | Open | Create |
| 4 | `FILE_OVERWRITE` | Truncate to zero | Fail |
| 5 | `FILE_OVERWRITE_IF` | Truncate to zero | Create |

`FILE_SUPERSEDE` deletes the existing name and creates a new file
under it, requiring `DELETE` on the existing file — or
`FILE_DELETE_CHILD` on the parent — together with `FILE_ADD_FILE` on
the parent. <a id="cite-facs.open.supersede-rights"></a> The existing file's other opens have to share `DELETE`,
and a read-only or delete-pending file cannot be superseded. The new
file gets a new inode and a new descriptor, inherited or
caller-supplied. The superseded pathname is broken away from the old
hardlink set and names the new inode; other pre-existing hardlinks
continue to name the old inode, and already-open descriptors still
reference it. <a id="cite-facs.open.supersede-new-inode"></a>

`FILE_OVERWRITE` truncates in place — same inode, same descriptor,
hardlinks preserved — and requires `FILE_WRITE_DATA`. <a id="cite-facs.open.overwrite-in-place"></a>

On an `unmanaged` mount, `FILE_OPEN` and `FILE_OPEN_IF` succeed and
return an unmanaged descriptor with no stamped mask rather than
failing; the creating dispositions fail with `EOPNOTSUPP`. <a id="cite-facs.open.unmanaged-create-eopnotsupp"></a>

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

## Create options

| Value | Name | Description |
|---|---|---|
| 0x0001 | `KACS_CREATE_OPT_DIRECTORY` | The target has to be a directory. When creating, create a directory rather than a regular file; when opening an existing non-directory, fail with `ENOTDIR`. <a id="cite-facs.open.create-opt-directory"></a> |
| 0x0002 | `KACS_CREATE_OPT_DELETE_ON_CLOSE` | Mark the file for deletion when this open closes. Requires `DELETE`, which may come through the parent. |

All other bits are reserved and have to be zero; a nonzero reserved
bit fails with `EINVAL`. <a id="cite-facs.open.reserved-create-option-einval"></a>

Delete-on-close is NT's: the obligation belongs to the open, and when
the open closes the file becomes **delete-pending**. The name is removed
at the last close of any open of the file, from any process
([Sharing and Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md#trm-3-9-10-3>)). <a id="cite-facs.open.delete-on-close-nt"></a> `dup()`, `fork()` and `SCM_RIGHTS`
preserve the obligation because they preserve the open file
description; it is discharged when the description's last reference
closes. <a id="cite-facs.open.delete-on-close-lineage"></a> `kacs_set_disposition` with `KACS_DISPOSITION_ON_CLOSE` sets or
clears it on an open that has `DELETE`.

Delete-on-close applies to regular files and directories. A directory
is removed only if it is empty when it is deleted. <a id="cite-facs.open.delete-on-close-directories"></a> A read-only
regular file cannot be opened with delete-on-close: the open fails with
`EPERM` and the status `KACS_STATUS_CANNOT_DELETE`.

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

## Caller-supplied descriptors

The descriptor format and size bound are defined in [SD Structure](https://learn.peios.org/specifications/pcds/security-descriptor/structure#binary-format).

When a disposition results in a new file the caller may supply a
descriptor. A null pointer with zero length means the new file's
descriptor is inherited from the parent directory through the
inheritance algorithm. <a id="cite-facs.open.null-descriptor-inherits"></a>

Supplying one on a branch that opens an *existing* object is invalid
input rather than something silently ignored. `FILE_OPEN_IF`
resolving to an existing object fails with `EINVAL`, and so do
`FILE_OVERWRITE` and the existing-object branch of
`FILE_OVERWRITE_IF`, since those retain the existing inode and its
descriptor. <a id="cite-facs.open.supplied-on-existing-einval"></a> `FILE_OPEN` with a descriptor supplied fails with
`EOPNOTSUPP`. <a id="cite-facs.open.supplied-with-file-open-eopnotsupp"></a>

Creator-supplied descriptors are validated at create time. An owner
SID has to be the caller's own or a token group marked
`SE_GROUP_OWNER`, unless `SeRestorePrivilege` is enabled, in which
case any owner is allowed. <a id="cite-facs.open.supplied-owner-constraint"></a> A supplied SACL is treated as a full SACL
input rather than a label-only fragment, and therefore requires
`SeSecurityPrivilege`. <a id="cite-facs.open.supplied-sacl-requires-privilege"></a> If that SACL carries an explicit mandatory
label ACE, the label also has to satisfy the ordinary label-write
constraint: at or below the caller's integrity level, unless
`SeRelabelPrivilege` is held. <a id="cite-facs.open.supplied-label-constraint"></a>

Generic rights in the descriptor's ACEs are mapped to file rights when
the descriptor is stored, whether it was supplied, inherited or taken
from the token's default DACL ([The Set-Security Interface](</kernel/internals/kacs/file-security/the-set-security-interface.md#trm-3-9-6-7>)).

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

## The creator's access <a id="cite-facs.open.creator-access"></a>

The parent's create rights authorize the creation: `FILE_ADD_FILE` or
`FILE_ADD_SUBDIRECTORY`, together with the supersede rules above. The
handle a creating open returns is then granted the access it asked
for, as in Windows, even where the new file's descriptor would not
grant it to its creator. <a id="cite-facs.open.creator-granted-requested"></a> A creator can therefore create a file with a
restrictive descriptor and still write it, in one step, and a folder
can accept files whose inherited permissions exclude the people who put
them there.

The grant replaces only the **normal discretionary pass**. The kernel
computes the new object's descriptor first, then runs the strict check
against it, with the normal DACL walk treated as granting the creator
everything. <a id="cite-facs.open.creator-normal-pass-only"></a> Every other layer still evaluates the new descriptor and
can refuse:

- the mandatory integrity label and PIP;
- the restricted-token pass;
- confinement, which stays absolute ([Application Confinement](</kernel/internals/kacs/access-check/application-confinement.md#trm-3-8-6>));
- central access and auditing policy; and
- privilege-only rights, such as `ACCESS_SYSTEM_SECURITY`.

So a low-integrity creator under an inherited high-integrity label
cannot write what it created, and a confined application cannot write
outside what its confinement identity is granted. A `MAXIMUM_ALLOWED`
creating open is granted every right of the object type that those
layers allow. A refused check rolls the creation back — the newly
created file or directory is removed — and the syscall fails. <a id="cite-facs.open.failed-check-rolls-back"></a>

The grant belongs to the creating open alone. `FILE_OPEN_IF` or
`FILE_OVERWRITE_IF` that finds an existing object is an ordinary open,
and every later open of the new object is checked against its
descriptor as normal. <a id="cite-facs.open.creator-grant-only-when-creating"></a>

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

## Ancestor pinning

`KACS_OPEN_PIN_ANCESTORS` pins the opened file's ancestor directories:
while the open lasts, none of them can be renamed or removed by anyone
([Sharing and Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md#trm-3-9-10-6>)). It requires `SeLockParentagePrivilege` enabled;
without it the open fails with `EPERM`. <a id="cite-facs.open.pin-requires-privilege"></a>

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

## Lease keys

With `KACS_OPEN_LEASE_KEY`, `kacs_open_how.lease_key` and `lease_fd`
identify the opener to the lease manager given by `lease_fd`. Opening a
file does not break leases that the same manager holds under the same
key ([Leases](</kernel/internals/kacs/file-security/leases.md#trm-3-9-12>)). <a id="cite-facs.open.lease-key-exemption"></a> `lease_fd` has to be a lease-manager
descriptor, or the open fails with `EBADF`.

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

## Modes and status

`kacs_open_how` carries no POSIX mode field, so the raw Linux inode
mode for native creation is fixed: `0600` for regular files, `0700`
for directories. <a id="cite-facs.open.fixed-create-modes"></a> These are compatibility metadata only — and if Linux
DAC ever denies an operation KACS would have authorized, the operation
fails closed.

Native creation does not create FIFOs, socket nodes, device nodes or
symlinks. <a id="cite-facs.open.no-native-special-creation"></a> Those stay on the Linux namespace APIs — `mknod()`,
`mkfifo()`, Unix `bind()` to a path — governed by the namespace hooks.
NTFS is excluded from native creation entirely. <a id="cite-facs.open.ntfs-excluded"></a>

`kacs_open_how` is size-versioned. A caller passes the size it was
built with — 32 bytes for the original layout, 56 bytes with the lease
fields — and fields beyond that size read as zero. A size below 16
bytes fails with `EINVAL`. <a id="cite-facs.open.how-size-versioned"></a> New fields are added at the end, behind a
flag, so that an existing caller's meaning never changes.

The syscall reports what happened through `status_out`: created,
opened, overwritten, or superseded. `KACS_STATUS_SUPERSEDED` is used
only when an existing object was actually replaced — a
`FILE_SUPERSEDE` that finds no target and simply creates one reports
`KACS_STATUS_CREATED`. <a id="cite-facs.open.status-superseded-only-if-replaced"></a>

When the open fails for a reason one errno cannot tell apart,
`status_out` also names the NT condition: <a id="cite-facs.open.failure-status"></a>

| Status | Errno | Condition |
|---|---|---|
| `KACS_STATUS_SHARING_VIOLATION` | `EBUSY` | Another open's share access conflicts with this one. |
| `KACS_STATUS_DELETE_PENDING` | `EBUSY` | The file is delete-pending. |
| `KACS_STATUS_CANNOT_DELETE` | `EPERM` | Delete-on-close on a read-only file. |

On any other failure `status_out` is left unwritten.

---

# Legacy Open Compatibility

_Peios Kernel / Internals / KACS / File security_

> Linux open flags cannot express WRITE_DAC or READ_CONTROL — how FACS maps them to core and compat rights, and what O_PATH does.

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

> [!IMPORTANT]
> The open-interface references contain [unresolved documentation differences](/kernel/userspace/native/kacs/abi-status-and-naming-differences.md#trm-3-d-6). Read that note alongside this page; no runtime behavior or release boundary has been established for those differences.

Linux's `open()` and `openat()` cannot express rights like `WRITE_DAC`
or `READ_CONTROL`. FACS maps the open flags to a **core** set of
required rights plus a **compat** set of POSIX-expected ones, and
evaluates both in a single AccessCheck.

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

## Core rights <a id="cite-facs.legacy.core-rights"></a>

The core set is the minimum for a usable descriptor, and the open
fails if any of it is denied.

For regular files, device nodes, FIFOs and pathname sockets:

| Flags | Core rights |
|---|---|
| `O_RDONLY` | `FILE_READ_DATA \| FILE_READ_ATTRIBUTES` |
| `O_WRONLY` | `FILE_WRITE_DATA \| FILE_READ_ATTRIBUTES` |
| `O_RDWR` | `FILE_READ_DATA \| FILE_WRITE_DATA \| FILE_READ_ATTRIBUTES` |

For directories, `O_RDONLY` gives
`FILE_READ_ATTRIBUTES | FILE_TRAVERSE`. Directory core deliberately
excludes `FILE_LIST_DIRECTORY`, so a directory opened `O_RDONLY` can
be used for `fchdir()` and `fstat()` without listing permission;
listing is a compat right. <a id="cite-facs.legacy.directory-core-excludes-list"></a>

Two modifiers apply in order. `O_APPEND` replaces `FILE_WRITE_DATA`
with `FILE_APPEND_DATA`, and `O_TRUNC` adds `FILE_WRITE_DATA`. Given
both, the replacement happens first and the re-addition second, so
core ends up with `FILE_APPEND_DATA` and `FILE_WRITE_DATA` together. <a id="cite-facs.legacy.append-trunc-order"></a>

`FILE_READ_ATTRIBUTES` is always core: a descriptor granting data
access but denying attribute reads is not openable through the legacy
APIs at all. <a id="cite-facs.legacy.read-attributes-always-core"></a>

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

## Compat rights <a id="cite-facs.legacy.compat-rights"></a>

Requested alongside core and silently omitted where denied:
`FILE_READ_EA` for `fgetxattr()`; `READ_CONTROL` for reading the
descriptor; `FILE_WRITE_ATTRIBUTES` for `futimens()`; `FILE_WRITE_EA`
for `fsetxattr()`; `FILE_WRITE_DATA` on `O_APPEND` opens so
`ftruncate()` works where the descriptor allows it; `WRITE_DAC`,
because POSIX permits `fchmod()` on any descriptor; `WRITE_OWNER`, for
`fchown()` on the same grounds; `SYNCHRONIZE`;
`FILE_LIST_DIRECTORY`, enabling `readdir()` on directory descriptors;
and `FILE_EXECUTE`, enabling `fexecve()` on regular files.

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

## The flow

The full requested mask is core plus compat. AccessCheck returns the
subset the descriptor allows. If every core right is present the
actual granted mask — which may include all, some or none of compat —
is stamped on the descriptor; otherwise the open fails with `EACCES`. <a id="cite-facs.legacy.core-missing-eacces"></a>

Both open paths run the same pipeline with different success
criteria. Native open is **strict**: everything requested has to be
granted. Legacy open is **subset**: only core has to be fully present.

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

## Sharing, deletion and read-only <a id="cite-facs.legacy.share-participation"></a>

A legacy open of a regular file or directory on a managed mount takes
part in NT share-mode checking. It shares read, write and delete, so
legacy opens never conflict with each other, but it fails with `EBUSY`
where a native open has denied its class of access ([Sharing and
Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md#trm-3-9-10-1>)). It also fails with `EBUSY` if the file is delete-pending,
as an `O_PATH` open of a delete-pending file does. <a id="cite-facs.legacy.delete-pending-ebusy"></a>

A legacy open for writing of a read-only regular file fails with
`EACCES`, and the compat write rights are omitted from a read-only
open of one ([Special Attributes](</kernel/internals/kacs/file-security/special-attributes.md#trm-3-9-13-2>)). <a id="cite-facs.legacy.readonly"></a>

`FILE_READ_ATTRIBUTES`, which every legacy open requires, may be
granted through the parent's `FILE_LIST_DIRECTORY` ([KACS-Native
Open](</kernel/internals/kacs/file-security/kacs-native-open.md#trm-3-9-2-8>)).

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

## O_PATH

`O_PATH` descriptors are not FACS-managed. The VFS opens them without
calling the open hook, so they carry no granted mask and are left
unmanaged. KACS checks one thing as they open: an `O_PATH` open of a
delete-pending file fails with `EBUSY`. <a id="cite-facs.legacy.o-path-unmanaged"></a> They serve as namespace
anchors for the `*at()` syscalls.

`fstat()` and `fstatfs()` on them are allowed unconditionally. <a id="cite-facs.legacy.o-path-fstat-unconditional"></a>
`fchdir()` runs a live `FILE_TRAVERSE` check at use time. <a id="cite-facs.legacy.o-path-fchdir-live"></a> `fchmod()`,
`fchown()`, `fgetxattr()`, `fsetxattr()`, `ioctl()` and `mmap()` are
denied with `EBADF` — though `futimens()` currently has no such guard. <a id="cite-facs.legacy.o-path-ebadf"></a>
`execveat(fd, "", ..., AT_EMPTY_PATH)` has exec permission enforced by
a live AccessCheck in the bprm hook, and `kacs_get_sd` and
`kacs_set_sd` with `AT_EMPTY_PATH` likewise run live, which gives
race-free object identity without snapshot authorization. <a id="cite-facs.legacy.o-path-live-checks"></a>

That `fstat()` is unconditional means `FILE_READ_ATTRIBUTES` is not
authoritative for attribute confidentiality. In practice size,
timestamps and inode number are rarely confidential. The descriptor
itself *is* protected: `kacs_get_sd` on an `O_PATH` handle performs a
live check.

---

# Use-Time Semantics

_Peios Kernel / Internals / KACS / File security_

> Every operation on an open descriptor is a mask check against the granted mask — data, metadata, traversal, append-only, fcntl and ioctl.

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

Every operation on an open descriptor is a mask check against the
granted mask, with one exception: `execveat(AT_EMPTY_PATH)` uses a
live AccessCheck. <a id="cite-facs.use.mask-check-per-operation"></a>

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

## Data operations <a id="cite-facs.use.data-operations"></a>

| Operation | Required right |
|---|---|
| Read | `FILE_READ_DATA` |
| Sequential write, no append intent | `FILE_WRITE_DATA` |
| Append-intent write (`O_APPEND` descriptor or `RWF_APPEND`) | `FILE_APPEND_DATA` or `FILE_WRITE_DATA` |
| Positioned write, or a no-append override | `FILE_WRITE_DATA` — denied on append-only descriptors |
| Directory listing | `FILE_LIST_DIRECTORY` |
| `ftruncate` | `FILE_WRITE_DATA` |
| `fallocate` allocation (`ALLOCATE_RANGE`, with or without `KEEP_SIZE`) | `FILE_APPEND_DATA` or `FILE_WRITE_DATA` |
| `fallocate` mutation (`PUNCH_HOLE`, `ZERO_RANGE`, `COLLAPSE_RANGE`, `INSERT_RANGE`, `UNSHARE_RANGE`, `WRITE_ZEROES`) | `FILE_WRITE_DATA` |
| `mmap PROT_READ` | `FILE_READ_DATA` |
| `mmap PROT_WRITE \| MAP_SHARED` | `FILE_WRITE_DATA` — `FILE_APPEND_DATA` alone is insufficient <a id="cite-facs.use.mmap-shared-write-needs-write-data"></a> |
| `mmap PROT_WRITE \| MAP_PRIVATE` | `FILE_READ_DATA` — copy-on-write, no write to the file <a id="cite-facs.use.mmap-private-needs-read"></a> |
| `mmap PROT_EXEC` | `FILE_EXECUTE` |
| `mprotect` | As `mmap`, for the new protection flags |
| `flock LOCK_SH` / `F_RDLCK` | `FILE_READ_DATA` |
| `flock LOCK_EX` / `F_WRLCK` | `FILE_WRITE_DATA` or `FILE_APPEND_DATA` |
| `fsync` / `fdatasync` | `SYNCHRONIZE` <a id="cite-facs.use.fsync-requires-synchronize"></a> |

A `fallocate` mode outside the supported set fails closed, and
`PUNCH_HOLE` additionally requires `KEEP_SIZE`. <a id="cite-facs.use.fallocate-unsupported-mode-fails"></a>

Reads, writes, truncation and content-changing `fallocate` on a
regular file are also checked against other opens' byte-range locks
when they are issued, and fail with `EAGAIN` on a conflict ([Byte-Range
Locks](</kernel/internals/kacs/file-security/byte-range-locks.md#trm-3-9-11-2>)). Memory-mapped access is not.

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

## Metadata operations <a id="cite-facs.use.metadata-operations"></a>

| Operation | Required right |
|---|---|
| `stat` / `lstat` / path `statx` | `FILE_READ_ATTRIBUTES`, or `FILE_LIST_DIRECTORY` on the parent <a id="cite-facs.use.stat-through-parent"></a> |
| `fstat` / descriptor `statx` | `FILE_READ_ATTRIBUTES` |
| `fstatfs` | `FILE_READ_ATTRIBUTES` |
| path and descriptor `file_getattr` | `FILE_READ_ATTRIBUTES`; by path, also through the parent |
| path and descriptor `file_setattr` | `FILE_WRITE_ATTRIBUTES` |
| `truncate` by pathname | `FILE_WRITE_DATA` |
| `chmod` / `fchmodat` / `fchmod` | `WRITE_DAC` <a id="cite-facs.use.chmod-requires-write-dac"></a> |
| `chown` / `lchown` / `fchownat` / `fchown` | `WRITE_OWNER` <a id="cite-facs.use.chown-requires-write-owner"></a> |
| `utimensat` / `utimes` / `futimens` | `FILE_WRITE_ATTRIBUTES` |
| `getxattr` / `lgetxattr` / `fgetxattr` | `FILE_READ_EA` |
| `setxattr` / `lsetxattr` / `removexattr` / `fsetxattr` / `fremovexattr` | `FILE_WRITE_EA` |
| `listxattr` / `llistxattr` / `flistxattr` | none <a id="cite-facs.use.listxattr-needs-no-right"></a> |
| get `security.peios.sattr` | `FILE_READ_ATTRIBUTES` |
| set or remove `security.peios.sattr` | `FILE_WRITE_ATTRIBUTES` |
| `access` / `faccessat` `F_OK` | `FILE_READ_ATTRIBUTES`, or `FILE_LIST_DIRECTORY` on the parent |
| `access` / `faccessat` `R_OK` | `FILE_READ_DATA` |
| `access` / `faccessat` `W_OK` | `FILE_WRITE_DATA` |
| `access` / `faccessat` `X_OK` | `FILE_EXECUTE` |

Descriptor-based `file_getattr` and `file_setattr` with `AT_EMPTY_PATH`
retain the open file through the operation and metadata cleanup. A concurrent
close cannot invalidate an operation that has already acquired its file
reference. This also covers unsupported-operation and other error paths.

Reads and writes of the canonical descriptor xattr are denied
unconditionally through the xattr hooks — `security.peios.sd`, or
`system.ntfs_security` on NTFS. All descriptor access goes through
`kacs_get_sd` and `kacs_set_sd`. POSIX ACL xattr writes are denied
unconditionally too, with `EOPNOTSUPP` rather than `EACCES` so that
probe-then-tolerate callers behave sensibly. <a id="cite-facs.use.posix-acl-write-eopnotsupp"></a>

The special-attributes xattr, `security.peios.sattr`, is not raw
storage either: KACS answers reads and writes of it itself, with the
attribute rights above and the value format in [Special
Attributes](</kernel/internals/kacs/file-security/special-attributes.md#trm-3-9-13-1>). The signature xattr, `security.peios.sig`, is governed by
[Binary Signature Verification](</kernel/internals/kacs/executable-trust/signature-verification.md#trm-3-6>).

Path-based attribute reads may be granted through the parent:
a caller who may list a directory may read the attributes of its
entries, as a native open may ([KACS-Native Open](</kernel/internals/kacs/file-security/kacs-native-open.md#trm-3-9-2-8>)).

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

## Directory traversal <a id="cite-facs.use.directory-traversal"></a>

Path resolution checks `FILE_TRAVERSE` on managed directory
components. A token holding `SeChangeNotifyPrivilege` bypasses the
intermediate checks, including on directories whose descriptor is
missing. <a id="cite-facs.use.change-notify-bypasses-traverse"></a>

Explicit changes of the current or root directory are not intermediate
resolution: `chdir()` and `chroot()` take a live `FILE_TRAVERSE` check
on the final directory, and the privilege bypass does not apply
([Privilege Catalogue](</kernel/internals/kacs/privileges/privilege-catalogue.md#trm-3-4-2>)). <a id="cite-facs.use.chdir-chroot-live-check"></a> An ordinary `fchdir()` checks the descriptor's cached mask;
an `O_PATH` `fchdir()` runs live. <a id="cite-facs.use.fchdir-cached-mask"></a>

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

## Watch placement <a id="cite-facs.use.watch-placement"></a>

Placing a watch — `inotify_add_watch()`, `fanotify_mark()` on an
inode, `F_NOTIFY` — is a read of the object by other means: a watch on
a directory reveals the names of its children as they come and go, a
watch on a file reports its activity. Linux gates it on read
permission, but under KACS a bare `MAY_READ` never reaches a
descriptor (read rights are decided at open), so the `path_notify`
hook checks the read-class right live against the object's own
descriptor: `FILE_LIST_DIRECTORY` for a directory, `FILE_READ_DATA`
for anything else. A denial is `EACCES`, and `SeChangeNotifyPrivilege`
does not bypass it — that privilege covers traversal, not reading. <a id="cite-facs.use.watch-change-notify-no-bypass"></a>

Mount, filesystem and mount-namespace marks are not object watches and
have no single descriptor to check. Linux requires `CAP_SYS_ADMIN` for
them, and for the fanotify permission classes (`FAN_CLASS_CONTENT`,
`FAN_CLASS_PRE_CONTENT` — the ones whose holder can veto or delay
opens and reads system-wide); the capability switchboard ([DAC Neutralisation](</kernel/internals/kacs/linux-credentials/dac-neutralisation.md#trm-3-10-2>))
resolves that to `SeTcbPrivilege`, so these are TCB-only. <a id="cite-facs.use.fanotify-mount-marks-tcb"></a> PIP
dominance is not part of the decision: a permission-event holder
intercepts opens of the *object*, never the opening process, and a
holder that is by construction TCB dominates every process anyway.

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

## Append-only enforcement <a id="cite-facs.use.append-only-enforcement"></a>

A handle carrying `FILE_APPEND_DATA` but not `FILE_WRITE_DATA` allows
only true append-intent writes. Append intent means the effective
write position is forced to end-of-file by `O_APPEND` or per-I/O
`RWF_APPEND`, and is not negated by `RWF_NOAPPEND` on the same
operation. <a id="cite-facs.use.append-intent-definition"></a> Requesting both `RWF_APPEND` and `RWF_NOAPPEND` together
fails with `EACCES`. <a id="cite-facs.use.append-noappend-conflict-eacces"></a>

Denied on such a handle: positioned writes without effective append
intent — `pwrite64`, `pwritev`, `pwritev2` with an explicit offset,
io_uring writes with an explicit offset, and AIO writes with an
offset; any write using `RWF_NOAPPEND`, since it can negate append
semantics inherited from `O_APPEND`; shared writable `mmap` and
`mprotect` upgrades to `PROT_WRITE`; and the `fallocate` mutation
modes. <a id="cite-facs.use.append-only-denied-set"></a>

<a id="trm-3-9-4-6"></a>

## fcntl <a id="cite-facs.use.fcntl"></a>

For `F_SETFL`, KACS evaluates the mutable status flags Linux accepts —
`O_APPEND`, `O_NONBLOCK`/`O_NDELAY`, `O_DIRECT`, `O_NOATIME`.
Clearing `O_APPEND` is denied on a handle with `FILE_APPEND_DATA` but
not `FILE_WRITE_DATA`; setting it is always allowed, being a privilege
reduction. <a id="cite-facs.use.setfl-clear-append-denied"></a> Adding `O_NOATIME` requires `FILE_WRITE_ATTRIBUTES` and
clearing it is always allowed. <a id="cite-facs.use.setfl-noatime"></a> Changing only `O_NONBLOCK`, `O_NDELAY`
or `O_DIRECT` needs no KACS right, though ordinary Linux validation
still applies. <a id="cite-facs.use.setfl-flags-need-no-right"></a>

These commands are descriptor-local and require no KACS right, and
none of them widens the cached mask: `F_CREATED_QUERY`; `F_DUPFD`,
`F_DUPFD_CLOEXEC` and `F_DUPFD_QUERY`, which preserve the same file
description and mask; `F_GETFD` and `F_SETFD`; `F_GETFL`; and the
async-notification set `F_GETOWN`, `F_GETOWN_EX`, `F_GETOWNER_UIDS`,
`F_GETSIG`, `F_SETOWN`, `F_SETOWN_EX` and `F_SETSIG`, where Linux pid
and signal validation still applies. <a id="cite-facs.use.fcntl-descriptor-local"></a>

These are object-state queries or mutations, checked against the
cached mask before Linux-specific validation:

| Command | Required right |
|---|---|
| `F_GETLK` / `F_GETLK64` / `F_OFD_GETLK` | Any data right |
| `F_GETLEASE` / `F_GETDELEG` | `FILE_READ_ATTRIBUTES` |
| `F_GETPIPE_SZ` | `FILE_READ_ATTRIBUTES` |
| `F_SETPIPE_SZ` | `FILE_WRITE_ATTRIBUTES` |
| `F_GET_SEALS` | `FILE_READ_ATTRIBUTES` |
| `F_ADD_SEALS` | `FILE_WRITE_ATTRIBUTES` |
| `F_GET_RW_HINT` / `F_GET_FILE_RW_HINT` | `FILE_READ_ATTRIBUTES` |
| `F_SET_RW_HINT` / `F_SET_FILE_RW_HINT` | `FILE_WRITE_ATTRIBUTES` |

Lock, lease and delegation commands — `F_SETLK`, `F_SETLKW`,
`F_SETLK64`, `F_SETLKW64`, `F_OFD_SETLK`, `F_OFD_SETLKW`,
`F_SETLEASE`, `F_SETDELEG` — pass through the fcntl hook so that the
later file-lock hook can enforce them against normalised `F_RDLCK`,
`F_WRLCK` or `F_UNLCK` values. <a id="cite-facs.use.fcntl-lock-passthrough"></a> An unknown lock type fails closed
there.

For `F_NOTIFY`, removing a watch — a zero event mask, ignoring
`DN_MULTISHOT` — requires nothing. Installing one with any known `DN_*`
event requires `FILE_LIST_DIRECTORY`. <a id="cite-facs.use.fcntl-notify-install"></a> Unknown `DN_*` bits on a managed
descriptor fail closed. <a id="cite-facs.use.fcntl-notify-unknown-bits"></a>

Unmanaged descriptors sit outside the handle check entirely, and an
unknown fcntl command on a managed one fails closed. <a id="cite-facs.use.unknown-fcntl-fails-closed"></a>

<a id="trm-3-9-4-7"></a>

## ioctl <a id="cite-facs.use.ioctl-classification"></a>

Known ioctls are classified by required right; an unclassified one is
allowed if the descriptor carries at least one data right. The 32-bit
compat aliases take the same right as their native command, including
`FS_IOC32_GETFLAGS`, `FS_IOC32_SETFLAGS`, `FS_IOC32_GETVERSION`,
`FS_IOC32_SETVERSION` and the compat preallocation commands. <a id="cite-facs.use.ioctl-compat-aliases"></a>

**Descriptor-local**, requiring nothing: `FIOCLEX` and `FIONCLEX`,
which change close-on-exec state; `FIONBIO`, which changes nonblocking
state; and `FIOASYNC`, which changes async notification state with
Linux and fops validation still applying. <a id="cite-facs.use.ioctl-descriptor-local"></a>

**Common VFS:**

| ioctl | Required right |
|---|---|
| `FIBMAP` | `FILE_READ_DATA` |
| `FIGETBSZ` | `FILE_READ_ATTRIBUTES` |
| `FIFREEZE` / `FITHAW` | `FILE_WRITE_ATTRIBUTES` |
| `FITRIM` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_GETFSUUID` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_GETFSSYSFSPATH` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_GETLBMD_CAP` | `FILE_READ_ATTRIBUTES` |

`FIFREEZE`, `FITHAW` and `FITRIM` mutate filesystem operational
state, and Linux's own `CAP_SYS_ADMIN` checks still apply on top. <a id="cite-facs.use.ioctl-freeze-cap-sys-admin"></a>

**File and object:**

| ioctl | Required right |
|---|---|
| `FS_IOC_FIEMAP` | `FILE_READ_DATA` |
| `FIONREAD` | `FILE_READ_DATA` on a regular file; any data right otherwise |
| `FS_IOC_GETFLAGS` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_SETFLAGS` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_GETVERSION` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_SETVERSION` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_RESVSP` / `FS_IOC_RESVSP64` | `FILE_APPEND_DATA` or `FILE_WRITE_DATA` |
| `FS_IOC_UNRESVSP` / `FS_IOC_UNRESVSP64` | `FILE_WRITE_DATA` |
| `FS_IOC_ZERO_RANGE` | `FILE_WRITE_DATA` |
| `FICLONE` / `FICLONERANGE` | `FILE_WRITE_DATA` |
| `FIDEDUPERANGE` | `FILE_WRITE_DATA` |
| `FIOQSIZE` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_FSGETXATTR` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_FSSETXATTR` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_GETFSLABEL` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_SETFSLABEL` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_GET_ENCRYPTION_PWSALT` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_GET_ENCRYPTION_POLICY` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_GET_ENCRYPTION_POLICY_EX` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_SET_ENCRYPTION_POLICY` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_ADD_ENCRYPTION_KEY` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_REMOVE_ENCRYPTION_KEY` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_GET_ENCRYPTION_KEY_STATUS` | `FILE_READ_ATTRIBUTES` |
| `BLKGETSIZE64` | `FILE_READ_ATTRIBUTES` |
| `BLKFLSBUF` | `FILE_WRITE_DATA` |

On directories, `FS_IOC_GETFLAGS` and `FS_IOC_SETFLAGS` take the same
rights as on files. <a id="cite-facs.use.ioctl-flags-on-directories"></a>

Anything unclassified is allowed on any data right. For device nodes,
pipes and sockets, device-specific ioctl semantics are outside FACS
scope: the node's descriptor is the authorization boundary, and
Linux's device-specific validation may still deny. <a id="cite-facs.use.ioctl-device-semantics-out-of-scope"></a>

A pinned inode ([Binary Signature Verification](</kernel/internals/kacs/executable-trust/signature-verification.md#trm-3-6>)) narrows all of this. Every content-, range- or
allocation-mutating ioctl is rejected on one, and so is every ioctl
the classifier does not recognise — unknown ioctls fail closed there
rather than falling back to the data-right rule.

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

## Execution <a id="cite-facs.use.execution"></a>

Execution is nominally a two-layer check. The **mode execute bit** is
the prerequisite meaning "this file is a program", set by package
managers and `chmod +x`, applying to `execve` and `execveat` but not
to `mmap(PROT_EXEC)`. The **descriptor's `FILE_EXECUTE`** is the
access control, gating both.

KACS enforces only the second. Nothing in the kernel module tests the
execute mode bit; the prerequisite survives because Linux's own
`generic_permission()` refuses `MAY_EXEC` on a file with no execute
bit set, by way of `capable_wrt_inode_uidgid(CAP_DAC_OVERRIDE)`. <a id="cite-facs.use.exec-mode-bit-from-linux"></a> The
`+x` requirement is therefore a Linux DAC property that KACS inherits
rather than a FACS rule, and it is one of the few decisions where mode
bits still matter ([DAC Neutralisation](</kernel/internals/kacs/linux-credentials/dac-neutralisation.md#trm-3-10-2>)).

For descriptor-based exec — `execveat` with `AT_EMPTY_PATH`, including
on `O_PATH` handles — a live AccessCheck for `FILE_EXECUTE` runs
against the re-opened file rather than the cached mask being consulted. <a id="cite-facs.use.execveat-live-check"></a>

---

# Descriptor storage and caching

_Peios Kernel / Internals / KACS / File security_

> Descriptor storage and caching: behaviour and implementation of the Peios kernel.

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

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

## Xattr protection <a id="cite-facs.storage.xattr-protection"></a>

FACS intercepts every raw xattr operation on the canonical descriptor
xattr — `security.peios.sd`, or `system.ntfs_security` on NTFS — and
denies all three directions. An NTFS inode with no `$Secure` entry,
whose descriptor is an inline attribute the driver never reads, counts
as carrying no descriptor: the mount's missing-descriptor policy
decides for it, as it does for a file with no `security.peios.sd`.

**Writes** are denied: all modification goes through the set-security
interface. **Removal** is denied: a descriptor is never detached from
a file. And **reads** are denied, which is the least obvious of the
three and the most important. <a id="cite-facs.storage.xattr-read-denied"></a> The raw xattr holds the entire
descriptor including the SACL, so allowing a read under
`READ_CONTROL` alone would leak SACL content that properly requires
`ACCESS_SYSTEM_SECURITY`. All reads go through `kacs_get_sd`, which
distinguishes the two.

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

## Caching

A validated, parsed descriptor object is cached in the inode's LSM
blob, holding immutable self-relative bytes together with a
prevalidated component layout — enough for AccessCheck readers never
to reparse untrusted storage bytes. <a id="cite-facs.storage.cache-parsed-in-inode-blob"></a>

**Readers** on the AccessCheck path use the RCU-published pointer.
Once a current entry exists, a reader does not take the inode mutex
merely to run AccessCheck. <a id="cite-facs.storage.readers-rcu-no-mutex"></a> It either completes the evaluation inside
an RCU read-side critical section, or pins the object with a refcount
while still under RCU and drops the RCU lock before doing anything
that can allocate, sleep or emit an audit event. A pin is acquired
with a non-zero refcount check and dropped afterwards.

**Writers** allocate a new object, swap the pointer atomically, and
free the old one after a grace period and after reader pins have
drained. <a id="cite-facs.storage.writers-rcu-swap"></a> No partial read is possible.

**Population** is lazy, on first access. The xattr is read through an
internal kernel path that bypasses the read-denial hook, and the
parsed result is installed by compare-and-swap; a thread that loses
the race frees its own copy. <a id="cite-facs.storage.population-lazy-cas"></a>

Both native and legacy open finish descriptor-cache resolution before
acquiring the central access policy (CAAP) cache mutex. Resolution can take
an inode security mutex, while set-security takes that inode mutex before
CAAP; acquiring them in the opposite order could deadlock an open against a
descriptor update. <a id="cite-facs.storage.open-resolves-before-caap"></a> Open retains a pin on the immutable descriptor
selected by that resolution, before releasing the protection used to select
it. The pin survives the subsequent CAAP wait and access check. Clearing or
replacing the inode's cache after selection cannot by itself cause a spurious
denial or change which descriptor this open evaluates; a later open resolves
again and can select the replacement. A missing or corrupt selected entry
still fails closed. <a id="cite-facs.storage.open-pins-selected-descriptor"></a>

Live file access checks, executable integrity-label reads, descriptor queries,
and copy-up descriptor reads also retain the immutable entry selected during
resolution until they finish evaluating or copying it. This includes the
inode-only descriptor read used by stacking filesystems. Invalidation after
selection cannot alone cause a refusal or substitute a different descriptor;
the next operation resolves again. A selected missing or corrupt descriptor
still fails closed even if another thread repairs the cache before the reader
finishes. <a id="cite-facs.storage.readers-pin-selected-descriptor"></a>

CAAP is evaluated under its own, later cache lock; the descriptor selection
and CAAP evaluation are not an atomic snapshot of both policies. The inode
mutex is not held for the access check, and CAAP is not held across lazy
descriptor population.

**Eviction** frees the cached descriptor when the inode is evicted,
through an RCU-safe callback with the same pin draining, so in-flight
permission checks complete before the object goes away. <a id="cite-facs.storage.eviction-rcu-safe"></a>

**Invalidation** happens on write, but not atomically with it. The
set-security path deliberately releases the inode security lock across
the xattr write and re-acquires it afterwards to publish the new
parsed object, because holding it across the write would invert the
`i_rwsem` ordering the access path requires. <a id="cite-facs.storage.setsd-releases-lock-across-write"></a> Two concurrent
set-security calls on one inode are therefore last-writer-wins rather
than serialised end to end, and there is a window in which the xattr
and the cache disagree. <a id="cite-facs.storage.concurrent-setsd-last-writer-wins"></a> Readers are never blocked, and no reader sees
a partially written object — the exposure is which of two racing
writes lands, not a torn state.

Invalidation is also driven from the **other end**, by the write
itself: any canonical descriptor xattr landing on an inode drops that
inode's cached entry, whoever wrote it and by whatever path. <a id="cite-facs.storage.xattr-write-drops-cache"></a> The
set-security path above then publishes the new parsed object as usual;
for anything else, the next reader re-reads the authoritative bytes.

This is keyed on the xattr rather than on the writer, because the
writer is not always the one holding the cache. A descriptor set
through a stacking filesystem reaches **two** inodes — the one the
caller named, and the real one beneath, which the write is re-entered
on. <a id="cite-facs.storage.stacking-two-inodes"></a> Only the first is refreshed by the set-security path. The second
is not merely cold: a stacking filesystem resolves and caches
descriptors during its own metadata work on an inode it has just
created, so it can hold an entry from the moment the object existed
and keep serving it after the xattr underneath has changed. Keying on
the xattr closes that without either side needing to know the other is
there.

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

## Missing descriptors <a id="cite-facs.storage.deny-missing-denies"></a>

Under **`facs_deny_missing`**, no descriptor means deny. Two
exceptions keep the repair path open. `SeChangeNotifyPrivilege`
bypasses intermediate traverse checks including on directories with no
descriptor, though not explicit `chdir()`, `chroot()` or `fchdir()`
use-time checks. And `O_PATH` opens bypass the open hook entirely, so
a file with a missing descriptor can still be acquired as an `O_PATH`
reference — which is exactly the repair route: `open(path, O_PATH)`
then `kacs_set_sd` with `AT_EMPTY_PATH` under `SeRestorePrivilege`. <a id="cite-facs.storage.missing-repair-route"></a>

Under the **synthesise classes**, a missing descriptor is generated
from two sources in order. <a id="cite-facs.storage.synthesis-order"></a> First, **inheritance from the parent**: if
the parent has one, the inheritance algorithm runs as though a new
file were being created. Otherwise the **mount-level template**,
applied where there is no parent descriptor — typically only at the
mount root. With no template configured, the fallback grants
`GENERIC_ALL` to SYSTEM and `BUILTIN\Administrators` and
`GENERIC_READ | GENERIC_EXECUTE` to Everyone, owned by SYSTEM with
SYSTEM as group. <a id="cite-facs.storage.synthesis-fallback-descriptor"></a>

Because these files already exist, the accessor is not their creator.
Where inheritance needs creator inputs — owner, primary group, default
DACL — a synthetic system-policy creator supplies them: the template's
owner, group and DACL if one exists, the fallback's otherwise. **The
accessor's token never affects the synthesised descriptor**, and the
synthesis path takes no subject token at all. <a id="cite-facs.storage.synthesis-ignores-accessor"></a>

Inheritance is recursive — a parent whose own descriptor is missing is
synthesised first, walking toward the mount root where the template
terminates it. <a id="cite-facs.storage.synthesis-recursive"></a> The walk is bounded at 32 ancestor levels; a target
nested deeper than that below the nearest resolvable ancestor fails
closed with `EACCES` rather than synthesising. <a id="cite-facs.storage.synthesis-depth-limit"></a>

Resolution does not nest FACS inode locks. It releases the current inode's
lock before resolving an ancestor or calling the filesystem's descriptor
xattr handler, which may itself resolve a lower inode in a stacked
filesystem. Referenced dentries and immutable descriptor-cache entries keep
the inputs alive across that work. <a id="cite-facs.storage.resolution-no-nested-inode-locks"></a>

Before publishing the result, resolution reacquires the inode lock and
checks both the mount-policy generation and the inode's cache mutation
sequence. An explicit replacement or invalidation makes it discard the
obsolete result and retry, including when an empty cache was populated and
cleared or invalidated while still empty. Ordinary cached files also retry
a competing reader publication, then use the current entry. A failed reread
never makes an entry from an old policy generation current again.
<a id="cite-facs.storage.resolution-revalidates-unlocked-work"></a>

StrataFS re-reads the current provider descriptor on every check, including
when an earlier result was missing or corrupt. Concurrent reader publication
does not restart these reads: without an explicit invalidation or policy
change, N checks perform N descriptor reads (each may query size and then
bytes). A reader may reuse a result published by another reader whose read
began later than its own; an older read cannot overwrite that later result,
including a missing or corrupt result. Its own read error is still returned.
Explicit writes and policy changes continue to trigger revalidation and may
require another read. This does not alter the fixed deny-missing policy or a
handle's frozen grant. <a id="cite-facs.storage.stratafs-read-contention"></a>

An **ephemeral** synthesis is cached in the inode blob only and never
written back, leaving the original filesystem unmodified. <a id="cite-facs.storage.ephemeral-not-written-back"></a> A
**persistent** one is additionally written to the xattr so the medium
acquires durable descriptors — but never inline. <a id="cite-facs.storage.persistent-written-back"></a>

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

## Deferred write-back <a id="cite-facs.storage.write-back-deferred"></a>

Writing the xattr takes the inode's `i_rwsem`. Synthesis may be reached
from a metadata operation whose VFS caller already holds that lock, so
inline write-back would self-deadlock even though resolution releases its
FACS inode lock around parent resolution and xattr reads. Write-back
therefore runs with no FACS or VFS lock held.

Synthesis caches the descriptor immediately and marks the entry
pending. <a id="cite-facs.storage.synthesis-marks-pending"></a> The access decision is correct from that cached value the
instant synthesis completes — correctness never depends on the xattr
reaching disk. The write-back runs later from a task-work callback
firing as the triggering syscall returns to userspace, so a persistent
descriptor is normally on disk by the time the operation that first
observed it missing returns. <a id="cite-facs.storage.write-back-task-work"></a>

A pending entry is generation-tagged exactly like an ephemeral one, so
a policy or template change before the write-back discards it and
re-synthesises; a stale pre-change descriptor is never pinned to disk.

Write-back is best-effort, and can be because the synthesised
descriptor is a deterministic function of the parent or the template —
the on-disk xattr is a cache of a recomputable value, not unique
state. If it does not happen, because the entry was evicted or the
task exited first, the identical descriptor is re-synthesised on next
access and retried. A failed or skipped write-back never fails the
operation that triggered synthesis. <a id="cite-facs.storage.write-back-best-effort"></a> Kernel threads, and a failure to
queue the callback, fall back to re-synthesis the same way.

Once written, the cached entry becomes an ordinary xattr-backed
descriptor: durable, no longer generation-tagged, never synthesised
again, and owed no further write-back. <a id="cite-facs.storage.written-back-becomes-ordinary"></a>

An ancestor synthesised only to supply inheritance inputs for a
descendant is itself pending, and persists under the same rules when
it is next accessed in its own right. <a id="cite-facs.storage.ancestor-also-persists"></a>

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

## Corrupt descriptors <a id="cite-facs.storage.corrupt-fails-closed"></a>

A descriptor xattr that exists but fails structural validation is
corrupt, and the policy is fail-closed: deny all access, do not call
AccessCheck, and never treat a truncated DACL as an empty one.

Every encounter emits an audit event, fired exactly once per inode per
cache population rather than per access, so a hot corrupt inode does
not flood the log. <a id="cite-facs.storage.corrupt-audit-once-per-population"></a>

Recovery is a process holding `SeRestorePrivilege` calling
set-security to overwrite it. Offline repair tools can also rewrite
xattrs directly on an unmounted filesystem.

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

## NFS client mounts <a id="cite-facs.storage.nfs-dual-authority"></a>

NFS is the one managed class where the sole-authority guarantee does
not hold. The server enforces its own access control independently:
FACS evaluates locally against a synthesised descriptor, and the
server may deny I/O that FACS allowed. A locally authorized `open()`
can therefore produce a descriptor whose `read()` calls fail. This is
inherent to network filesystems with server-side enforcement, and
nothing suppresses the server's denial.

## Related explanations

- [Mount classes and bootstrap descriptors](</kernel/internals/kacs/file-security/mount-classes-and-bootstrap-descriptors.md>)

---

# Mount classes and bootstrap descriptors

_Peios Kernel / Internals / KACS / File security_

> Mount classes and bootstrap descriptors: behaviour and implementation of the Peios kernel.

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

## Mount policy classes

The superblock policy object carries the class ([The Handle Model](</kernel/internals/kacs/file-security/the-handle-model.md#trm-3-9-1>)) and, for
synthesise-class mounts, an optional mount-level default template.

The default classifier maps from the superblock's filesystem magic.
`PROC_SUPER_MAGIC` and `SYSFS_MAGIC` are **unmanaged**: these expose
kernel state through inode-shaped handles with no on-disk identity and
no descriptor to consult. <a id="cite-facs.storage.proc-sysfs-unmanaged"></a> `NULL_FS_MAGIC` is unmanaged too — nullfs is
the immutable, permanently empty filesystem the kernel mounts as the
mount-namespace root, with the mutable rootfs mounted on top of it. It
declares no xattr support at all, so it can never carry a descriptor,
and its single root inode is immutable and childless: nothing to stamp
and nothing to protect. <a id="cite-facs.storage.nullfs-unmanaged"></a>

`STRATAFS_SUPER_MAGIC` is fixed at **`facs_deny_missing`** for the
superblock's lifetime, because StrataFS delegates every check to
current provider objects and must never synthesise a descriptor for
its merged namespace. <a id="cite-facs.storage.stratafs-fixed-deny-missing"></a> An attempt to change it fails with
`EOPNOTSUPP`.

`RAMFS_MAGIC`, `NFS_SUPER_MAGIC`, `MSDOS_SUPER_MAGIC`,
`EXFAT_SUPER_MAGIC`, `ISOFS_SUPER_MAGIC` and `CGROUP2_SUPER_MAGIC` are
**`facs_synthesize_ephemeral`** — either no persistent backing at all,
or storage with no native descriptor slot. <a id="cite-facs.storage.ephemeral-magics"></a>

Everything else, including `TMPFS_MAGIC`, `SQUASHFS_MAGIC`,
`EXT4_SUPER_MAGIC` and `BTRFS_SUPER_MAGIC`, defaults to
**`facs_deny_missing`**. <a id="cite-facs.storage.default-deny-missing"></a> These can all carry the descriptor xattr
natively and are expected to on every inode that participates in
access checks.

`TMPFS_MAGIC` covers both userspace tmpfs mounts and the kernel-mounted
instances established before any userspace runs. The latter are not
exempt from the default; they are handled by seeding.

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

## Kernel-internal mounts <a id="cite-facs.storage.kernel-internal-mounts"></a>

Two filesystems are mounted by the kernel before any userspace process
exists and before anything can call `kacs_set_mount_policy` or
`kacs_set_sd`: the mutable root filesystem mounted by
`init_mount_tree`, a tmpfs mounted on top of the immutable nullfs
namespace root and made `/` by `set_fs_root`; and the devtmpfs
instance mounted by `devtmpfs_init` and populated by the `kdevtmpfs`
thread.

Both are `TMPFS_MAGIC` and therefore `facs_deny_missing`, and their
root inodes are kernel-created, never passing through a
userspace-supplied artifact, so they carry no descriptor at the moment
they become reachable. To make the class viable the kernel seeds one.

The mutable root filesystem is a tmpfs whatever the command line says.
<a id="cite-facs.storage.rootfs-always-tmpfs"></a> Upstream Linux makes it a ramfs
when the command line carries `root=`, or a `rootfstype=` that does not
name tmpfs, and ramfs stores no extended attributes: the seed below
would have nowhere to go, nothing the boot archive unpacks would
inherit a descriptor, and StrataFS, which reads a provider's stored
descriptor and never a synthesised one, would refuse every view an
initramfs mounts over it. An installed system always boots with
`root=`, so the upstream rule is not followed.

The rootfs root is seeded inside `init_mount_tree`, immediately after
`vfs_kern_mount` returns and before the mount is published into
`init_mnt_ns`, with the inode's `i_rwsem` held. <a id="cite-facs.storage.rootfs-seed-timing"></a> The devtmpfs root is
seeded inside `devtmpfs_init`, after `vfs_kern_mount` and before
`kdevtmpfs` starts, likewise under `i_rwsem`. <a id="cite-facs.storage.devtmpfs-seed-timing"></a> The nullfs root is not
seeded — it is unmanaged, empty, and incapable of xattr storage. <a id="cite-facs.storage.nullfs-not-seeded"></a>

A rootfs seed that fails panics the kernel. <a id="cite-facs.storage.rootfs-seed-failure-is-fatal"></a>
A boot that went on without it would fail later, in whatever first
reached the initramfs through a StrataFS view, with nothing to connect
the refusal to its cause.

The seeded descriptor is byte-for-byte identical in both places: owner
and group SYSTEM (`S-1-5-18`), a DACL of one `ACCESS_ALLOWED` ACE
granting `GENERIC_ALL` to SYSTEM flagged
`OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE` so that inheritance
derives a child descriptor for every inode created on the mount
afterwards, and no SACL. <a id="cite-facs.storage.seeded-descriptor-contents"></a>

The writes go through the kernel-internal xattr path, bypassing both
the FACS denial hooks and the LSM setxattr permission hook. <a id="cite-facs.storage.seed-writes-bypass-hooks"></a> They
consult no token — at the point either runs there may be no meaningful
subject — and the seeded descriptor is the sole authority for the
mount until trusted userspace replaces it. They depend on nothing
beyond the LSM scaffold that allocates inode and superblock blobs.

These are not exempt from later management: trusted userspace can
overwrite the per-inode descriptor or change the superblock's class
once it holds the privileges. <a id="cite-facs.storage.seeded-mounts-still-manageable"></a>

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

## Boot artifacts <a id="cite-facs.storage.boot-artifacts-not-seeded"></a>

A filesystem shipped as a boot artifact — a squashfs concatenated into
the initrd, a vendor squashfs delivered as a package, a flashed
partition image — defaults to `facs_deny_missing` and the kernel does
**not** seed it. These are already-populated trees the kernel cannot
extend at mount time, and in the read-only case cannot extend at all.

The obligation falls on the build pipeline, which emits
`security.peios.sd` on every inode ordinary access checks will reach.
`mksquashfs`, the ext utilities and the standard userland xattr
surfaces all preserve `security.*` natively.

An artifact without descriptors is a packaging defect. FACS treats
every missing descriptor on a `facs_deny_missing` mount as a
corruption indicator and denies. The operator path is to rebuild the
artifact, or to adopt the superblock under a synthesise class.

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

## Administration <a id="cite-facs.storage.set-mount-policy"></a>

The privilege gate below is verified in kernel source
[`8e0e22de3a59cad506bbbf8873de456e16ad272d`](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/capability.c#L613-L637),
including its use by both [set](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/mount_policy.c#L369-L380)
and [get](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/mount_policy.c#L479-L496). This is source-level
verification, not a deployed-kernel test or a historical release boundary.

Trusted userspace adopts a mounted filesystem by calling
`kacs_set_mount_policy` on a descriptor naming any object on the
target superblock; `O_PATH` descriptors are valid targets. The change
applies to the superblock, not the pathname used to reach it.

Setting a policy is volume management: the call requires
`SeManageVolumePrivilege` or `SeTcbPrivilege`, enabled, and must
successfully mark the enabled privilege as used; `kacs_get_mount_policy`
is gated the same way. <a id="cite-facs.storage.set-mount-policy-privilege"></a> Every change writes a
`kacs.mount.policy.changed` record ([Audit Event Schemas](</kernel/internals/kacs/auditing/event-families-and-delivery.md#trm-3-c>)), whose subject is the caller
and which names the filesystem's type, the policy set
(`object.mount.policy`), the one it replaced
(`object.mount.policy-previous`) and the new generation
(`object.mount.policy-generation`). Every refusal is decided before the
change, so a record is always of a change made; the template is not
carried. <a id="cite-facs.storage.set-mount-policy-recorded"></a> The
public ABI accepts only the three managed classes; `unmanaged`,
unknown values, nonzero reserved flags and malformed arguments all
fail closed. <a id="cite-facs.storage.set-mount-policy-input-validation"></a> The one
policy the kernel sets on its own initiative is for a tmpfs that a token
without the privilege brought into being inside its own mount namespace,
which is stamped `synth-ephemeral` with a creator-owned template at
`sb_kern_mount` ([A Private Mount Table](</kernel/internals/kacs/mount-namespaces/a-private-mount-table.md#trm-3-13-1>)).

The optional template is accepted only with a synthesise class. <a id="cite-facs.storage.template-requires-synthesise"></a> It is
a complete self-relative descriptor rather than a subset, passes
structural validation, and is at most 65535 bytes. <a id="cite-facs.storage.template-validation"></a> A null pointer with
zero length clears it. <a id="cite-facs.storage.template-null-clears"></a> Setting `facs_deny_missing` clears it and
rejects non-empty template input. <a id="cite-facs.storage.deny-missing-clears-template"></a> Pointer and length mismatches and
invalid bytes fail before any state changes.

Policy changes are **lazy**. They do not walk the filesystem and do
not stamp anything. <a id="cite-facs.storage.policy-change-lazy"></a> The superblock carries a monotonic generation
counter, incremented on every successful policy or template
replacement. <a id="cite-facs.storage.generation-counter"></a> Missing-descriptor, ephemeral-synthetic and
not-yet-written-back persistent-synthetic cache entries record the
generation they came from and are discarded and repopulated when it
changes. <a id="cite-facs.storage.generation-discards-synthetic"></a> Xattr-backed and corrupt-descriptor caches are not made valid
by a policy change, and open file descriptions keep their immutable
masks. <a id="cite-facs.storage.policy-change-keeps-xattr-caches"></a>

---

# The Set-Security Interface

_Peios Kernel / Internals / KACS / File security_

> The single syscall all descriptor modification flows through — ownership, integrity labels, the SeRestorePrivilege bypass and mandatory attributes.

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

All descriptor modification flows through one syscall. The caller
provides a file descriptor or path, a bitmask naming which components
to modify, and a self-relative descriptor blob carrying the new
values.

| Flag | Component | Required right |
|---|---|---|
| `OWNER_SECURITY_INFORMATION` | Owner SID | `WRITE_OWNER` <a id="cite-facs.set-sd.owner-requires-write-owner"></a> |
| `GROUP_SECURITY_INFORMATION` | Group SID | `WRITE_OWNER` |
| `DACL_SECURITY_INFORMATION` | Discretionary ACL | `WRITE_DAC` <a id="cite-facs.set-sd.dacl-requires-write-dac"></a> |
| `SACL_SECURITY_INFORMATION` | System ACL | `ACCESS_SYSTEM_SECURITY` <a id="cite-facs.set-sd.sacl-requires-access-system-security"></a> |
| `LABEL_SECURITY_INFORMATION` | Mandatory integrity label | `WRITE_OWNER`, plus the integrity constraints below <a id="cite-facs.set-sd.label-requires-write-owner"></a> |

The blob is validated structurally — parseable, well-formed ACEs,
valid SIDs, at most 65535 bytes. With an existing valid file security descriptor,
only the indicated components are merged into it. Unindicated components
are preserved unchanged. <a id="cite-facs.set-sd.merge-preserves-unindicated"></a>

The input is always one self-relative descriptor subset, never a raw
SID or ACL fragment. `SACL_SECURITY_INFORMATION` and
`LABEL_SECURITY_INFORMATION` cannot be combined in one call, because
both target the SACL field with incompatible meanings; the pair fails
with `EINVAL`. <a id="cite-facs.set-sd.sacl-label-exclusive"></a>

A `SACL_SECURITY_INFORMATION` write replaces the object's **entire**
SACL. <a id="cite-facs.set-sd.sacl-write-replaces-all"></a> A `LABEL_SECURITY_INFORMATION` write interprets the input SACL
as the label subset only: no SACL component removes the explicit
mandatory label and returns the object to the default unlabelled
state; a present SACL contains exactly one non-inherit-only
`SYSTEM_MANDATORY_LABEL_ACE` and nothing else; and the object's
non-label SACL ACEs are preserved. <a id="cite-facs.set-sd.label-write-subset"></a>

After merging, the result still has a non-null owner — the group SID
may be null — and a merge that would leave no owner fails. <a id="cite-facs.set-sd.owner-must-remain"></a>

MIC and PIP apply to these checks. A low-integrity caller cannot
modify a high-integrity file's descriptor even where the DACL grants
`WRITE_OWNER`. <a id="cite-facs.set-sd.mic-pip-apply"></a>

A read-only mount withholds the write along that path whatever the
descriptor grants: the call fails with `EROFS`, as every modifying
operation through a read-only bind does, and the descriptor stays
writable through any writable path to the same object. The mount is
consulted after the access check, so a caller the descriptor refuses
sees the denial rather than a read-only error that would confirm the
object exists. <a id="cite-facs.set-sd.read-only-mount-erofs"></a>

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

## Component merging and replacement

For a file whose cached descriptor is valid, [the C dispatcher](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/sd_access.c#L197-L255) selects the merge path. The [control-bit merge](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/token_runtime.rs#L4232-L4264) starts from the destination control value and replaces these bits from the input when their component is selected:

| Selected component | Replaced control bits |
|---|---|
| Owner | `OWNER_DEFAULTED` |
| Group | `GROUP_DEFAULTED` |
| DACL | `DACL_DEFAULTED`, `DACL_TRUSTED`, `DACL_AUTO_INHERIT_REQ`, `DACL_AUTO_INHERITED`, `DACL_PROTECTED` |
| Full SACL | `SACL_DEFAULTED`, `SACL_AUTO_INHERIT_REQ`, `SACL_AUTO_INHERITED`, `SACL_PROTECTED` |

This copies more than ACE lists, but is not byte-identical descriptor replacement. If group is not selected, [the destination group remains](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/token_runtime.rs#L4347-L4351). The [resource-manager control byte remains the destination's](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/token_runtime.rs#L4410-L4416), as does its `RM_CONTROL_VALID` state. A label-only merge does not replace the full-SACL control-bit set in the table.

A missing or invalid cached file security descriptor does **not** take that merge path. The dispatcher requires enabled `SeRestorePrivilege` and calls the [replacement builder](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/token_runtime.rs#L4420-L4468), which requires owner, group and DACL selections and validates the supplied owner and label. Do not apply valid-descriptor field-retention guarantees to that repair case.

These details are source-checked against kernel commit [`8e0e22de`](https://github.com/peios/pkm/tree/8e0e22de3a59cad506bbbf8873de456e16ad272d), not a runtime-validated restore procedure.

<a id="trm-3-9-6-7"></a>

## Generic rights <a id="cite-facs.set-sd.generic-rights-mapped"></a>

Generic rights in a written DACL or SACL are mapped to file rights
before the descriptor is stored, as they are when a file is created.
An ACE that applies to the file has `GENERIC_READ`, `GENERIC_WRITE`,
`GENERIC_EXECUTE` and `GENERIC_ALL` replaced by the file rights they
stand for. An ACE that applies to the file and is also inherited is
split into a mapped ACE for the file and an inherit-only copy that
keeps the generic rights for the children it will reach. Inherit-only
ACEs are stored as given. A descriptor therefore reads back the same
whether it was supplied at creation, inherited, or set afterwards
([The DACL Walk](</kernel/internals/kacs/access-check/the-dacl-walk.md#trm-3-8-2-2>)).

The same rule applies to every object type with a set path —
registry keys, processes, tokens, System V IPC objects and the rest —
each through its own GenericMapping.

A descriptor change breaks other holders' handle caching on the file
([Leases](</kernel/internals/kacs/file-security/leases.md#trm-3-9-12-3>)).

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

## Ownership <a id="cite-facs.set-sd.ownership"></a>

A new owner may be set only to the caller's own SID, or to a group SID
on the token carrying `SE_GROUP_OWNER`. `SeTakeOwnershipPrivilege`
allows setting ownership to the caller's own SID regardless of what
the current descriptor says, and `SeRestorePrivilege` allows any
arbitrary SID. <a id="cite-facs.set-sd.take-ownership-and-restore"></a>

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

## Integrity labels <a id="cite-facs.set-sd.label-level-constraint"></a>

Without enabled `SeRelabelPrivilege` a caller may set a label only at or below
its own integrity level; with it, the label-level check permits any level.
Other access and validation checks still apply.

The constraint applies through **both** paths — the dedicated label
subset, and a label ACE embedded in a full SACL write. A SACL write
whose ACL contains a mandatory label ACE raising integrity above the
caller's level requires `SeRelabelPrivilege` exactly as the label path
does, even though the SACL component itself is gated only by
`ACCESS_SYSTEM_SECURITY`. <a id="cite-facs.set-sd.label-constraint-via-sacl"></a>
`SeSecurityPrivilege` or `SeRestorePrivilege` alone is not sufficient for
a label above the caller's integrity: the [label-assignment check](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/token_runtime.rs#L4180-L4197) independently requires enabled
`SeRelabelPrivilege`.

<a id="trm-3-9-6-4"></a>

## The SeRestorePrivilege bypass

`SeRestorePrivilege` fires inside the AccessCheck pipeline, so it
bypasses the check only where `kacs_set_sd` runs a **live** one: an
`O_PATH` descriptor with `AT_EMPTY_PATH`, a pidfd, a token descriptor
with `AT_EMPTY_PATH`, or a path. <a id="cite-facs.set-sd.restore-bypass-live-only"></a> On those paths it grants every
requested right, `WRITE_OWNER`, `WRITE_DAC` and
`ACCESS_SYSTEM_SECURITY` included.

Called on an ordinary file descriptor the required rights are checked
against the cached mask instead, no AccessCheck runs, and the
privilege has no effect at all. <a id="cite-facs.set-sd.restore-no-effect-on-fd"></a> A caller needing the bypass has to use
the `O_PATH` route — which is the mechanism behind backup restoration,
administrative repair, and the missing-descriptor repair path
([File Descriptor Storage](</kernel/internals/kacs/file-security/descriptor-storage-and-caching.md#trm-3-9-5>)).

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

## Mandatory resource attributes <a id="cite-facs.set-sd.mandatory-attribute-requires-tcb"></a>

When a caller modifies the SACL, the existing and new SACLs are
compared for changes to `SYSTEM_RESOURCE_ATTRIBUTE_ACE` entries. An
existing attribute carrying `CLAIM_SECURITY_ATTRIBUTE_MANDATORY`
(0x0020) cannot be removed, nor its values modified, without
`SeTcbPrivilege` — and an attempt without it fails the entire call
rather than silently dropping the change.

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

## Write mechanics

The updated descriptor is serialised to self-relative binary form and
written to the xattr through an internal kernel path bypassing the
denial hook, and the in-memory cache is updated. <a id="cite-facs.set-sd.write-bypasses-denial-hook"></a> An audit event is
emitted if the file's SACL carries a matching audit ACE. <a id="cite-facs.set-sd.audit-on-matching-ace"></a>

The cache update is not atomic with the xattr write; [File Descriptor Storage](</kernel/internals/kacs/file-security/descriptor-storage-and-caching.md#trm-3-9-5>) describes
the lock ordering that forces this and the last-writer-wins window it
produces.

---

# Sharing and Deletion

_Peios Kernel / Internals / KACS / File security_

> NT share modes enforced for every process, delete-pending files, deletion and renaming through an open handle, and pinning a file's ancestors.

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

KACS keeps NT's sharing and deletion rules in the kernel, for every
process. An open says which kinds of access it lets other opens have at
the same time. A file can be marked for deletion through any open that
holds `DELETE`, and is removed when the last open of it closes. Deletion
and renaming can be done through an open handle rather than by name.

These rules apply to regular files and directories on FACS-managed
mounts. <a id="cite-facs.share.scope"></a> They do not apply to device nodes, FIFOs, sockets or symbolic
links, to unmanaged mounts such as `/proc`, `/sys` and nullfs, or to
`O_PATH` descriptors, which take no part in share checks.

<a id="trm-3-9-10-1"></a>

## Share modes <a id="cite-facs.share.check"></a>

The rules are those of MS-FSA 2.1.5.1.2.1 and 2.1.5.1.2.2. Access falls
into three classes:

| Class | Rights | Share bit that admits it |
|---|---|---|
| Read | `FILE_READ_DATA`, `FILE_EXECUTE` | `FILE_SHARE_READ` |
| Write | `FILE_WRITE_DATA`, `FILE_APPEND_DATA` | `FILE_SHARE_WRITE` |
| Delete | `DELETE` | `FILE_SHARE_DELETE` |

An open whose granted access contains none of these rights takes no part
in share checking: it neither conflicts with other opens nor constrains
them. <a id="cite-facs.share.attribute-only-opens"></a> Opening for attributes or for the security descriptor is
always possible, whatever other opens deny.

An open that does take part conflicts with an existing open, and fails
with `EBUSY`, when either of them holds access of a class the other
does not share. <a id="cite-facs.share.conflict-both-ways"></a> A native open is judged by the access it was
**granted**, not what it asked for, so a `MAXIMUM_ALLOWED` open is
judged by what it received. A native open reports the conflict as
`KACS_STATUS_SHARING_VIOLATION`. A successful open registers its access
and share mode until it closes.

**Legacy opens take part.** A plain `open(2)` shares all three classes,
so legacy opens never conflict with each other. A legacy open is judged
by its mode instead of its granted mask, because its mask carries
optional compat rights it may never use: a readable open, file or
directory, holds the read class, and a writable one the write class.
<a id="cite-facs.share.legacy-opens"></a> A legacy open of a file another
open has denied to its class fails with `EBUSY`, as a native open does.

**A running program takes part.** Executing a file holds it as an open
with read access that shares read and delete but not write. This is the
NT form of Linux's refusal to write a running executable, which still
applies first, with `ETXTBSY`. A program can be replaced by renaming a
new file over its name while it runs. <a id="cite-facs.share.exec"></a>

An open's share registration lasts as long as its open file
description. A memory mapping holds the description, so a mapped file
keeps its registration after its descriptor is closed, until it is
unmapped.

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

## Denying only what you could do yourself <a id="cite-facs.share.deny-limits"></a>

Share modes would let any reader lock others out of a file, such as a
system configuration file it can only read. KACS limits each denial to
what the opener could do itself. Where an open omits a share bit it is
not entitled to deny, that bit is silently set, and the open proceeds as
if it had shared it.

- **Denying read** follows MS-FSA. It takes effect only if the opener
  has `FILE_WRITE_DATA` on the parent directory (2.1.5.1.2.2). On the
  first open of a directory it also needs the generic write rights on
  the directory itself (2.1.5.1.2). <a id="cite-facs.share.deny-read"></a>
- **Denying write** takes effect only if the opener's descriptor grants
  it `FILE_WRITE_DATA` or `FILE_APPEND_DATA` on the object. <a id="cite-facs.share.deny-write"></a>
- **Denying delete** takes effect only if the opener could delete the
  object: `DELETE` on it, or `FILE_DELETE_CHILD` on its parent. <a id="cite-facs.share.deny-delete"></a>

These decide whether the opener *could* exercise the right, not
whether it asked to. Each is an AccessCheck against the current
descriptor, made only for an open that omits the corresponding share
bit. An open that shares everything, which includes every legacy open,
costs nothing extra.

<a id="trm-3-9-10-7"></a>

## Overriding share modes <a id="cite-facs.share.override"></a>

Backup and restore tools have to read and replace files that others
hold open. A native open's backup and restore intents
([Privilege-Based Grants](</kernel/internals/kacs/privileges/the-privilege-model.md>)) also let it set aside other opens'
denials:

- backup intent with `SeBackupPrivilege` enabled ignores other opens'
  denial of read;
- restore intent with `SeRestorePrivilege` enabled ignores other opens'
  denial of write and delete.

The override skips only the share check. Lease breaks still happen, so
a client caching the file flushes first. The overriding open's own
share mode still binds later opens, and every override is audited. <a id="cite-facs.share.override-audited"></a>

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

## Delete-pending files <a id="cite-facs.delete.pending"></a>

A file is **delete-pending** when it has been marked to be deleted at
its last close. Any open of the file that holds `DELETE` can set or
clear the mark with `kacs_set_disposition`. An open created with
`KACS_CREATE_OPT_DELETE_ON_CLOSE` sets it when it closes. <a id="cite-facs.delete.set-clear"></a>

While a file is delete-pending:

- its name stays in place: `stat` and directory listings still show it;
- every new open of it fails with `EBUSY`, whatever the access asked,
  including attribute-only and `O_PATH` opens; a native open reports
  `KACS_STATUS_DELETE_PENDING`; <a id="cite-facs.delete.pending-opens-fail"></a>
- unlinking or renaming it by name fails with `EBUSY`;
- a delete-pending directory accepts no new entries: creating, linking
  or renaming into it fails with `EBUSY`; and
- creating a file of the same name fails, because the name still
  exists.

When the last open of the file closes, from whichever process, the
name is removed. <a id="cite-facs.delete.last-close"></a> The removal is authorized by the token of the open
that set the mark, captured when it was set, not by whoever happens to
close last; the closing task needs no right. A removal that fails at
close, for example because a directory gained an entry, is audited,
and the file is left in place and no longer delete-pending. <a id="cite-facs.delete.close-failure-audited"></a>

The name removed is the link the marking open was opened through,
followed across any renames since. Other hard links to the file remain.
If that name is already gone by the last close, nothing more is done.

A directory is removed at its last close only if it is empty then; one
that is not stays, and the failed removal is audited. A delete-pending
directory accepts no new entries meanwhile, so it can only empty. A
read-only regular file cannot be marked unless the caller sets it aside ([Special
Attributes](</kernel/internals/kacs/file-security/special-attributes.md#trm-3-9-13>)).

<a id="trm-3-9-10-4"></a>

## The disposition call <a id="cite-facs.delete.disposition-call"></a>

`kacs_set_disposition(fd, flags)` sets a file's delete disposition
through an open handle. Its flags are those of NT's
`FILE_DISPOSITION_INFORMATION_EX`:

| Flag | Value | Meaning |
|---|---|---|
| `KACS_DISPOSITION_DELETE` | 0x01 | Mark the file for deletion. Without it, clear the mark. |
| `KACS_DISPOSITION_POSIX_SEMANTICS` | 0x02 | With `DELETE`: remove the name now. |
| `KACS_DISPOSITION_ON_CLOSE` | 0x08 | Set or clear this open's delete-on-close obligation instead of the file's mark. |
| `KACS_DISPOSITION_IGNORE_READONLY` | 0x10 | Delete a read-only file. Requires `FILE_WRITE_ATTRIBUTES` as well. |

The open has to hold `DELETE`, or the call fails with `EACCES`. <a id="cite-facs.delete.disposition-needs-delete"></a> The
right was checked when the handle was opened, including through the
parent; the call checks the handle's mask, not the descriptor.

**POSIX semantics** remove the name at once, as `unlink(2)` does, and
open handles carry on with the unnamed file. <a id="cite-facs.delete.posix-now"></a> This is how a
Windows client's POSIX-semantics delete, and a Peios program's "delete
this file I hold open", are carried out. A directory has to be empty,
or the call fails with `ENOTEMPTY`.

Other opens of the file were checked against this open's `DELETE` when
each was opened, so the call does not repeat the share check. A read-only
regular file without `IGNORE_READONLY` fails with `EPERM`. Calling it on
an unmanaged descriptor fails with `EOPNOTSUPP`.

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

## Renaming through a handle <a id="cite-facs.rename.handle"></a>

`kacs_rename(fd, newdirfd, newpath, flags)` moves the link an open
handle names to `newpath`, resolved relative to `newdirfd` as by
`renameat2()`. Its flags are those of NT's `FILE_RENAME_INFORMATION_EX`:

| Flag | Value | Meaning |
|---|---|---|
| `KACS_RENAME_REPLACE_IF_EXISTS` | 0x01 | Replace an existing file at the destination. |
| `KACS_RENAME_POSIX_SEMANTICS` | 0x02 | Replace a destination file that is open, if its opens share delete. |
| `KACS_RENAME_IGNORE_READONLY` | 0x40 | Replace a read-only destination file. |

An open file's name follows renames, so the handle always names its
current link; renaming by handle cannot hit a different file that has
since taken the old name. On StrataFS the link is found from the file's
provider instead ([Stacked filesystems](#trm-3-9-10-9)). Authorization is:

- `DELETE` in the handle's granted mask, for removing the source link; <a id="cite-facs.rename.needs-delete"></a>
- a live check for `FILE_ADD_FILE`, or `FILE_ADD_SUBDIRECTORY` for a
  directory, on the destination directory; and
- where a file is replaced, a live check for `DELETE` on it or
  `FILE_DELETE_CHILD` on its parent. <a id="cite-facs.rename.replace-checks"></a>

A replaced file that is open fails the rename with `EBUSY`, unless
`POSIX_SEMANTICS` is given and all its opens share delete. A replaced
file that is delete-pending, or read-only without `IGNORE_READONLY`,
also fails. A directory is never replaced. A destination that exists
without `REPLACE_IF_EXISTS` fails with `EEXIST`. If the handle's link
has already been removed, the call fails with `ENOENT`.

<a id="trm-3-9-10-8"></a>

## Deleting and renaming by name <a id="cite-facs.share.unlink-rename-by-name"></a>

NT treats deleting a file by name as an open with `DELETE`, so the
Linux calls obey the same rules. `unlink(2)`, `rmdir(2)` and `rename(2)`
fail with `EBUSY` when the source, or a file the rename would replace:

- is held by an open that does not share delete; or
- is delete-pending.

This covers `rm`, `mv`, and editors that save by renaming a new file
over the old one. The limit on denials means that only someone who
could delete a file can stop others deleting it. Their access checks
are unchanged ([Use-Time Semantics](</kernel/internals/kacs/file-security/use-time-semantics.md#trm-3-9-4>)). Plain deletion by name is still
immediate: the name goes at once, and open handles carry on.

<a id="trm-3-9-10-6"></a>

## Ancestor pinning <a id="cite-facs.pin.ancestors"></a>

Windows will not rename or remove a folder while a file beneath it is
open. Linux has no such rule, and Peios keeps Linux's for its own
programs. An open made with `KACS_OPEN_PIN_ANCESTORS` asks for the
Windows rule for that one file: while it is open, each directory above
it, up to the root of the mount it was opened through, is **pinned**.
A pinned directory cannot be renamed, removed, or replaced by a rename,
by any process; those calls fail with `EBUSY`. <a id="cite-facs.pin.refuses-rename-rmdir"></a>

The pin follows the link the file was opened through, and the
directories it pins are those above that link when the open was made.
It is held as a count on each directory, so many pinned files beneath
one directory pin it once each. The counts are taken in a single walk
that is repeated if a rename moves one of the directories while the
walk is in progress, and dropped when the open's description closes.
<a id="cite-facs.pin.counts"></a> The pinned file itself is not pinned: renaming or deleting it is
governed by share modes.

Pinning blocks other people's work, so it requires
`SeLockParentagePrivilege`. File servers hold it, to give the Windows
clients they serve the folder protection those clients expect from each
other. <a id="cite-facs.pin.privilege"></a>

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

## Stacked filesystems <a id="cite-facs.share.stacked"></a>

A stacking filesystem shows files that live on another filesystem
beneath it, the **provider**. StrataFS gives every lookup of a name a
new inode of its own, so KACS keeps a file's share registrations,
delete-pending mark and pin counts on the provider's inode instead. All
routes to a file therefore see the same state: the merged view, another
StrataFS mount over the same stratum, and the stratum itself. A regular
file's open registers through the backing file that StrataFS opens on
the provider. A directory's open has no backing file, so it registers on
its provider itself. <a id="cite-facs.share.stratafs-provider"></a>

**Copy-up.** When StrataFS copies a regular file up to its writable
stratum, the file's opens move their registrations to the copy. A
directory copied up while it is open keeps its registrations and pins
on the former provider, so opens and removals made after the copy-up do
not see them. A directory present in more than one stratum cannot be
renamed in any case. <a id="cite-facs.share.stratafs-copy-up"></a>

**Renaming through a handle.** A StrataFS open's own name is the one it
was looked up by, which goes out of date when the file is renamed. The
provider is renamed in its own filesystem, which keeps its name current,
so `kacs_rename` finds the handle's link there:

1. it takes the provider's path within its stratum;
2. it looks that path up again through the mount the handle was opened
   through, and locks it as `rename(2)` would;
3. it checks that the name still reaches the same provider, retrying if
   a rename moved it meanwhile.

After a copy-up the handle names the copy. A name that a higher stratum
masks is not the handle's file, and the call fails with `ENOENT`, as it
does when the link has been removed. A file whose provider is a
read-only stratum fails with `EROFS`, as `rename(2)` does. <a id="cite-facs.rename.stratafs"></a>

**Overlayfs.** A file's opens register on its real inode through their
backing files. A directory opened through overlayfs opens its real
directory as a plain open, so the real directory sees a legacy open that
shares everything, and the native open's share mode is not enforced. <a id="cite-facs.share.overlayfs"></a>

---

# Byte-Range Locks

_Peios Kernel / Internals / KACS / File security_

> NT byte-range locks, kept by the kernel and enforced on every read and write — when they are checked, what they block, and the limit on who can block whom.

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

An NT byte-range lock reserves part of a file for one open. An
exclusive lock keeps every other open from reading or writing the range;
a shared lock keeps everyone, its holder included, from writing it.
Unlike Linux's advisory `fcntl` and `flock` locks, these are
**enforced**: a read or write that conflicts with another open's lock
fails, whichever program issued it. <a id="cite-facs.lock.enforced"></a> KACS keeps them for regular files
on FACS-managed mounts; `kacs_lock` on anything else fails with
`EOPNOTSUPP`.

Linux's own locks are unchanged and independent. A program that takes
`fcntl` locks neither sees nor conflicts with byte-range locks, except
that its reads and writes are checked against them like everyone
else's.

<a id="trm-3-9-11-1"></a>

## Taking and releasing locks <a id="cite-facs.lock.call"></a>

`kacs_lock(fd, args, size)` takes or releases a lock through an open
handle. `struct kacs_lock_args` gives the range as `offset` and
`length`, the operation, and flags:

| Operation | Value | Meaning |
|---|---|---|
| `KACS_LOCK_SHARED` | 1 | Take a shared lock. |
| `KACS_LOCK_EXCLUSIVE` | 2 | Take an exclusive lock. |
| `KACS_LOCK_UNLOCK` | 3 | Release a lock this open holds over exactly this range. |
| `KACS_LOCK_CANCEL` | 4 | Cancel this open's waiting request named by `cookie`. |

The open has to hold a data right — `FILE_READ_DATA`, `FILE_WRITE_DATA`
or `FILE_APPEND_DATA` — or the call fails with `EACCES`. <a id="cite-facs.lock.needs-data-right"></a> A lock
belongs to the open file description that took it, so descriptors
duplicated from it share its locks. When the description closes, its
locks are released and its waiting requests cancelled. <a id="cite-facs.lock.owner-and-release"></a>

Lock conflicts follow MS-FSA 2.1.4.10. Two locks of different opens
conflict where their ranges overlap and either is exclusive. An open's
exclusive lock also conflicts with its own overlapping exclusive lock.
A zero-length lock is a point at its offset, and the range from offset
zero with length zero conflicts with nothing. <a id="cite-facs.lock.conflicts"></a>

A request that conflicts waits until it can be granted, unless it
carries `KACS_LOCK_FAIL_IMMEDIATELY`, in which case it fails with
`EAGAIN`. A waiting request can be interrupted by a signal (`EINTR`),
or cancelled by another thread with `KACS_LOCK_CANCEL` and the same
`cookie`, in which case it fails with `ECANCELED`. Waiting requests are
granted in the order they arrived as the conflicting locks go.
<a id="cite-facs.lock.waiting"></a> Unlocking a range this open does not hold exactly fails with `ENOLCK`.

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

## What locks block <a id="cite-facs.lock.io-checks"></a>

Each operation that reads or changes a file's contents is checked
against the locks of **other** opens:

| Operation | Checked as |
|---|---|
| Read | A read of its range |
| Write, including append | A write of its range |
| `truncate`, `ftruncate` | A write of the range between the old and new size |
| An open that truncates | Not checked, as on Windows: `O_TRUNC`, and a native open with `OVERWRITE`, `OVERWRITE_IF` or `SUPERSEDE` |
| `fallocate` that changes contents | A write of the range it changes, to end of file for collapse and insert |

An open that truncates is let through as Windows lets an overwriting
`CreateFile` through: the locks it drops go with the data, and the
holders' later I/O is checked against what is left. <a id="cite-facs.lock.open-truncate-unchecked"></a>

An exclusive lock blocks reads and writes; a shared lock blocks writes.
A shared lock also blocks its own holder's writes. A conflicting
operation fails with `EAGAIN`; it does not wait. <a id="cite-facs.lock.io-eagain"></a>

The check covers every way of issuing these operations: `read`,
`write` and their vectored and positioned forms, `sendfile`, `splice`
and `copy_file_range`, direct I/O, AIO and io_uring.

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

## When a lock takes effect <a id="cite-facs.lock.at-issue"></a>

An I/O is checked against the lock list when it is **issued**. Granting
a lock does not wait for I/O already admitted: an I/O that passed its
check before a conflicting lock was granted may finish after it, and
counts as having happened before the lock. This is the guarantee
Windows gives. No lock is held across the I/O itself, so asynchronous
I/O completing elsewhere needs no special treatment, and an I/O cannot
deadlock against a lock request.

A file with no byte-range locks costs one check that its lock list is
empty.

<a id="trm-3-9-11-4"></a>

## Memory mappings are not covered <a id="cite-facs.lock.mmap-excluded"></a>

Loads and stores through a memory mapping are not checked against
locks, as on Windows, where mapped views bypass byte-range locks.
Mapping a file, and changing a mapping's protection, are checked only
by the handle's rights ([Use-Time Semantics](</kernel/internals/kacs/file-security/use-time-semantics.md#trm-3-9-4-1>)).

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

## Who can block whom <a id="cite-facs.lock.dos-limit"></a>

Enforced locks would let any reader stop others using a file. KACS
limits their reach as it limits share modes: a lock blocks other opens'
reads and writes only if the open that took it could write the file
itself, that is, if the file's descriptor grants its opener
`FILE_WRITE_DATA` or `FILE_APPEND_DATA`. A lock taken by an opener who
could not write the file still conflicts with other locks, so
cooperating readers can coordinate with it, but it blocks no I/O.

<a id="trm-3-9-11-6"></a>

## Stacked filesystems <a id="cite-facs.lock.stacked"></a>

Through StrataFS, a lock belongs to the backing file its open reaches
and is held on the provider, so it covers every route to that file. A
copy-up gives the file a new provider: locks taken before it stay with
the former provider, and I/O through the copy is not checked against
them. Locks through overlayfs are not supported, and `kacs_lock` fails
with `EOPNOTSUPP`.

---

# Leases

_Peios Kernel / Internals / KACS / File security_

> NT caching leases kept by the kernel for a lease manager such as a file server — the read, handle and write states, what breaks them, and how breaks are delivered.

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

A lease lets a holder cache a file safely. Its state is any combination
of three NT caching bits:

| State | Value | The holder may cache |
|---|---|---|
| `KACS_LEASE_READ` | 0x1 | The file's contents and attributes, for reading. |
| `KACS_LEASE_HANDLE` | 0x2 | Its open handles, keeping them open after its own client has closed them. |
| `KACS_LEASE_WRITE` | 0x4 | Changes to the contents, not yet written back. |

When another open or operation would make the cached state wrong,
KACS **breaks** the lease: it tells the holder, waits for the holder to
flush and give up the state, then lets the operation proceed. A file
server holds leases on behalf of its clients and relays the breaks to
them, so a local program and a network client see a consistent file.
<a id="cite-facs.lease.purpose"></a>

Leases cover regular files and directories on FACS-managed mounts.
A directory lease can hold only read and handle caching. Below a
stacking filesystem a lease is held on the provider an open reaches
([Stacked filesystems](#trm-3-9-12-6)).

<a id="trm-3-9-12-1"></a>

## Lease managers <a id="cite-facs.lease.manager"></a>

A lease is held through a **lease manager**, created by
`kacs_create_lease_manager(flags, break_timeout_ms)`. The call returns a
descriptor; `KACS_LEASE_MANAGER_CLOEXEC` and
`KACS_LEASE_MANAGER_NONBLOCK` set close-on-exec and non-blocking
reads. Break notices for every lease the manager holds arrive on that
descriptor.

Each lease is identified by its manager and a 16-byte **key** the
manager chooses. Opens with the same key belong to one holder: an open
made with a key does not break the leases its manager holds under that
key ([KACS-Native Open](</kernel/internals/kacs/file-security/kacs-native-open.md#trm-3-9-2-12>)). <a id="cite-facs.lease.key"></a> A file server gives each client lease
its own key, and each oplock its own unique key.

Closing the manager's last descriptor releases all its leases.

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

## Requesting a lease <a id="cite-facs.lease.request"></a>

`kacs_lease(fd, manager_fd, args, size)` requests, changes or releases
the lease on the file `fd` refers to. The open has to have been made
with `KACS_OPEN_LEASE_KEY`, naming the same manager and the key given
in `args`; otherwise the call fails with `EINVAL`.

KACS grants as much of the requested state as current opens allow,
writes the granted state back into `args.state`, and may grant none.
<a id="cite-facs.lease.grant"></a>

- **Read** needs the open to hold a read right, and no open under
  another key to hold write access.
- **Write** needs the open to hold a write right, and no open of the
  file under another key.
- **Handle** is granted with read.

A state of zero releases the lease. A lease is also released when the
last open under its key closes, unless it holds handle caching.

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

## What breaks a lease <a id="cite-facs.lease.break-points"></a>

Only operations from outside the holder break its lease: an operation
through an open under the lease's own key never does.

| Operation by another holder | Breaks | Reason |
|---|---|---|
| Opening the file | Write | `KACS_LEASE_BREAK_OPEN` |
| An open refused by a sharing conflict | Handle, then the open is checked again | `KACS_LEASE_BREAK_SHARING` |
| Writing the file | Read | `KACS_LEASE_BREAK_WRITE` |
| Changing its size | Read | `KACS_LEASE_BREAK_SIZE` |
| Taking a byte-range lock | Read | `KACS_LEASE_BREAK_LOCK` |
| Renaming or linking it, or renaming a directory above it | Handle | `KACS_LEASE_BREAK_NAMESPACE` |
| Deleting it, or setting its delete disposition | Handle | `KACS_LEASE_BREAK_DELETE` |
| Changing its security descriptor | Handle | `KACS_LEASE_BREAK_SECURITY` |
| Changing its attributes or extended attributes | Read | `KACS_LEASE_BREAK_ATTRIBUTES` |
| Adding, removing or renaming an entry of a leased directory | Read and handle | `KACS_LEASE_BREAK_CHILD` |

Breaking write also breaks whatever the new open could not share: a
writer breaks read as well. A broken lease falls to the state the
operation can live with, not necessarily to none.

The holder of a lease that loses only read caching can lose nothing it
has not already written, so such a break is a **notice**: the operation
does not wait for it. Every other break waits. <a id="cite-facs.lease.read-break-no-wait"></a>

Most of these are the points at which Linux breaks its own leases and
NFS delegations, and KACS's leases are entries in the same table, so
the existing break points reach them. KACS adds the others: writes and
size changes through descriptors that were already open, byte-range
locks, security changes, and sharing conflicts.

<a id="trm-3-9-12-4"></a>

## Break notices <a id="cite-facs.lease.notices"></a>

Reading a lease-manager descriptor returns break notices, each a
`struct kacs_lease_break`: the lease's key, the file's device and inode
number, the current and new state, the reason, and an epoch that counts
the lease's breaks. The descriptor is readable with `poll()` when a
notice is waiting.

Notices are never dropped. A lease has at most one break outstanding,
so a manager's queue is bounded by the number of leases it holds.
<a id="cite-facs.lease.lossless"></a>

The holder acknowledges a break with `kacs_lease`, setting
`KACS_LEASE_ACKNOWLEDGE` and a state no greater than the notice's new
state. The waiting operation then proceeds.

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

## Timeouts <a id="cite-facs.lease.timeout"></a>

A break not acknowledged within the manager's break timeout is
completed by KACS: the lease is reduced to the new state, the waiting
operation proceeds, and the manager receives a notice with reason
`KACS_LEASE_BREAK_TIMEOUT`. The timeout is set when the manager is
created, in milliseconds, from 1 to 35 000; zero gives the default of
35 seconds, the time SMB allows a client to acknowledge a break.

An operation waiting on a break can be interrupted by a signal. Only
the waiting operation fails; the break goes on.

<a id="trm-3-9-12-6"></a>

## Stacked filesystems <a id="cite-facs.lease.stacked"></a>

Through StrataFS, a regular file's lease is held on the provider its
open reaches, so it covers every route to that file. A copy-up gives the
file a new provider: a lease taken before it stays with the former
provider, and changes made through the copy do not break it. Leases on
StrataFS directories, and on anything reached through overlayfs, are not
supported; `kacs_lease` fails with `EOPNOTSUPP`.

---

# Special Attributes

_Peios Kernel / Internals / KACS / File security_

> The read-only flag KACS enforces for every process, and the settable Created At date, kept in the special-attributes extended attribute.

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

KACS keeps a file's **special attributes** in the extended attribute
`security.peios.sattr`, beside its security descriptor in
`security.peios.sd`. There are two today:

- **Read-only**, which KACS enforces for every process.
- **Created At**, a settable creation date.

<a id="trm-3-9-13-1"></a>

## Reading and writing them <a id="cite-facs.sattr.access"></a>

The attribute is read and written with the ordinary extended-attribute
calls — `getxattr`, `setxattr` and their descriptor and `*at` forms —
using `struct kacs_sattr` as the value. KACS answers these calls
itself. Reading needs `FILE_READ_ATTRIBUTES`, and writing or removing
needs `FILE_WRITE_ATTRIBUTES`, rather than the extended-attribute
rights. <a id="cite-facs.sattr.rights"></a> Through a descriptor, the right comes from the handle's
granted mask; by path, from a live check, which may grant
`FILE_READ_ATTRIBUTES` through the parent ([KACS-Native Open](</kernel/internals/kacs/file-security/kacs-native-open.md#trm-3-9-2-8>)).

| Field | Meaning |
|---|---|
| `version` | `KACS_SATTR_VERSION`, currently 1. |
| `valid` | The fields a write changes. A read sets every bit. |
| `attributes` | `KACS_SATTR_READONLY` (0x1). |
| `flags` | On a read, `KACS_SATTR_CREATED_AT_SET` if Created At is set. On a write, `KACS_SATTR_CREATED_AT_CLEAR` unsets it. |
| `created_at_sec`, `created_at_nsec` | Created At, as seconds and nanoseconds since the Unix epoch. |

A write changes only the fields its `valid` mask names and leaves the
others as they are. Two programs changing different attributes at once
therefore cannot undo each other's change. <a id="cite-facs.sattr.merge"></a> A write with an unknown
version, `valid` bit, attribute or flag, a nonzero `__pad`, a value of
the wrong size, or `XATTR_CREATE` or `XATTR_REPLACE` fails with
`EINVAL`. Removing the attribute clears read-only and unsets Created
At.

The attribute is stored only while something is set, and reading a
file that has none fails with `ENODATA`: it is not read-only, and has no
Created At.
Tools that copy extended attributes copy a stored attribute with the
rest; a copy that should keep an unset Created At has to read it and
set it on the copy.

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

## Read-only <a id="cite-facs.sattr.readonly"></a>

Read-only protects a file against accidental change, and binds its
owner too, without anyone rewriting its permissions. It is the
attribute Windows programs set and check, and source-control tools
mark checked-in files with it.

On a regular file marked read-only, for every process: <a id="cite-facs.sattr.readonly-enforced"></a>

- An open asking `FILE_WRITE_DATA` or `FILE_APPEND_DATA` fails with
  `EACCES`. A legacy open for writing fails the same way. A
  `MAXIMUM_ALLOWED` open is granted neither right, nor
  `FILE_ADD_SUBDIRECTORY` or `FILE_DELETE_CHILD`, following MS-FSA
  2.1.5.1.2.1. `FILE_OVERWRITE` and `FILE_SUPERSEDE` fail with `EACCES`.
- `truncate` by path fails with `EACCES`.
- Deleting it fails with `EPERM`: `unlink(2)`, a rename that would
  replace it, a delete disposition, and an open with delete-on-close,
  which a native open reports as `KACS_STATUS_CANNOT_DELETE`. The
  disposition and rename calls can set this aside with their
  `IGNORE_READONLY` flags ([Sharing and Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md#trm-3-9-10-4>)).

The check is made at open and at deletion, not on every write: a handle
opened for writing before the file was marked read-only keeps working,
as on Windows. Renaming a read-only file, and changing its other
attributes or its descriptor, are not affected. Anyone with
`FILE_WRITE_ATTRIBUTES` can clear the flag.

On a directory, read-only is kept and reported but not enforced.
Windows uses the flag on folders to mark them as customized, not to
protect them. <a id="cite-facs.sattr.readonly-directories"></a>

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

## Created At <a id="cite-facs.sattr.created-at"></a>

Created At records when a file was created, in the sense a person or a
copy tool means: a copy can carry its original's creation date, and a
Windows client can set it. It is distinct from the filesystem's
**birth time**, which `statx` reports, which nobody can set, and which
records when this inode came into being. Birth time is the forensic
fact; Created At is the user-facing date.

While Created At has not been set, a file's creation date is its birth
time: a reader that finds no Created At, or finds
`KACS_SATTR_CREATED_AT_SET` clear, takes the date from `statx`. KACS
never changes Created At itself, and `statx` continues to report the
birth time.
