fs

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 28, 2026 License: MIT Imports: 12 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package fs provides privileged filesystem operations for Linux system management, driven by an injected exec.Runner rather than a process-global privilege backend.

A Manager is built over a Runner; the backend the Runner reports selects the privilege strategy per operation, with no global state and full unit-test coverage via exectest.FakeRunner:

r, _ := exec.NewRunner(exec.Direct) // the agent runs as root; elsewhere Sudo/Doas
m, err := fs.New(r)
if err != nil { ... }
if err := m.WriteFile(ctx, "/etc/app.conf", data, fs.WriteOptions{Mode: 0o644, Owner: "root", Group: "root"}); err != nil { ... }

When the Runner reports the Direct backend — the deployed root agent — writes and recursive deletes take the TOCTOU-safe, fd-anchored path (O_NOFOLLOW opens, RENAME_NOREPLACE, openat/unlinkat walks). Under Sudo/Doas (a non-root caller, e.g. CI or a dev tool) the same operations shell through the privilege backend (tee/mv/rm/chmod/chown); that path is not symlink-safe, but the security-relevant consumer — the root agent — never takes it.

The fd-anchored primitives (OpenRealDir, FchownNoFollow, SetDirPermissionsNoFollow, ResolveOwnership) and the path predicates (ValidatePath, ResolveAndValidatePath, IsProtectedPath, IsUnderProtectedPrefix) remain exported free functions: they take no privilege and callers (notably the agent's directory action) use them directly.

Index

Constants

This section is empty.

Variables

View Source
var ErrExists = errors.New("destination exists")

ErrExists is returned by WriteFileExclusive when the destination already exists. It is a distinct sentinel, not a generic failure, because the whole point of an exclusive create is to let the caller BRANCH on it: "someone else owns this file" is a normal, expected outcome that usually means "fall back to an ordinary overwrite", while every other error means the write failed.

View Source
var ErrInvalidPath = errors.New("invalid filesystem path")

ErrInvalidPath is returned by ValidatePath when the supplied path would be unsafe to pass as a positional argument to a privileged command (empty, contains a NUL byte, or starts with `-` and would be interpreted as a flag).

View Source
var ErrProtectedTarget = errors.New("recursive ownership change of a protected system tree is not permitted")

ErrProtectedTarget is returned when a recursive ownership change (chown -R) targets a whole top-level system directory (`/`, `/etc`, `/usr`, `/home`, `/root`, …). Recursively re-owning such a tree is a destructive privilege-escalation vector (e.g. handing an attacker ownership of every file under `/`), so it fails closed before chown runs. A managed subdirectory (e.g. /home/alice) and single-file SetOwnership are unaffected.

View Source
var ErrUnsafeMode = errors.New("setuid/setgid mode is not permitted")

ErrUnsafeMode is returned when a privileged file operation is asked to set a setuid or setgid bit. A managed config write must never create a privileged executable: a setuid-root binary the agent drops is a direct local-root privilege-escalation primitive, so the operation fails closed before any command runs. The sticky bit and ordinary permission bits are unaffected.

View Source
var ErrUnsafeParentDir = errors.New("parent directory is writable by non-root")

ErrUnsafeParentDir is returned by the escalated (sudo/doas) WriteFile when the target's parent directory is writable by a non-root user — a directory where an attacker could plant a symlink and redirect a root write. The escalated path fails closed rather than write into such a directory. (The Direct/root path is fd-anchored and does not need this; it is only the shell-based escalated path, used by non-root callers, that cannot openat the target.)

Functions

func FchownNoFollow

func FchownNoFollow(path string, uid, gid int) error

FchownNoFollow sets ownership on a regular file via an O_NOFOLLOW open followed by an fd-based chown (fchown(2)). A symlink at path is rejected — the open fails (ELOOP) rather than dereferencing — so a user who can plant a symlink where a privileged file was just written (e.g. ~/.ssh/authorized_keys inside their own 0700 dir) cannot redirect the chown onto an arbitrary target (e.g. /etc/shadow). Unlike `chown -h`, which would silently chown the planted symlink itself, this surfaces the tampering as an error.

It refuses non-regular files (a directory, device, fifo, …) so it cannot be misused as a directory chown — use OpenRealDir for those.

O_NONBLOCK is set because O_NOFOLLOW only guards symlinks: a user who can plant a path could plant a FIFO instead, and a blocking O_RDONLY open on a FIFO hangs until a writer appears (a local DoS on the root agent). With O_NONBLOCK the open returns immediately for a FIFO (and avoids blocking/side effects on a device node too); the subsequent IsRegular check then rejects it.

func GetOwnership

func GetOwnership(path string) (owner, group string)

GetOwnership returns the current owner and group NAMES of path. It stats the path unprivileged (no Runner needed) and resolves the numeric uid/gid against the user/group database. Any failure — missing path, unreadable parent, an id with no name — yields empty strings for the affected field, matching the best-effort contract callers rely on.

func IsProtectedPath

func IsProtectedPath(path string) bool

IsProtectedPath returns true if path is a system directory that should never be deleted. The path is cleaned and resolved to absolute before checking.

func IsUnderProtectedPrefix

func IsUnderProtectedPrefix(path string) bool

IsUnderProtectedPrefix reports whether path is at or under a security-relevant system prefix that a managed directory delete must refuse. The path is cleaned and resolved to absolute before checking, so traversal tricks (/etc/../etc/sudoers.d) and relative inputs cannot dodge the guard. This is the deny-by-default predicate RemoveDir uses and that the agent's directory action reuses (WS6 #4, #12).

func OpenRealDir

func OpenRealDir(path string) (*os.File, error)

OpenRealDir opens path as a real directory WITHOUT following a final symlink and returns the *os.File, so callers can apply privileged metadata changes through the fd — f.Chown / f.Chmod, which are fchown(2) / fchmod(2) on the open descriptor — instead of path-based chmod/chown.

This closes the TOCTOU window of a path-based "check then act". A path-based chmod/chown re-resolves the path on every call, so a user who controls the directory (e.g. ~/.ssh, owned by the target user) can swap it for a symlink between a prior check and the operation, redirecting a root-run chmod/chown onto the symlink's target. Operating through the returned fd removes the whole class: the descriptor is bound to the inode that was opened, and a later swap of the path cannot redirect operations on it.

  • O_NOFOLLOW makes the open itself fail (ELOOP) if the final path component is a symlink — there is no window to swap one in, because the check and the handle are the same syscall.
  • O_DIRECTORY makes the open fail (ENOTDIR) if the path is not a directory, so a non-directory target is rejected in the same syscall.

The caller MUST Close the returned file.

func Ownership

func Ownership(owner, group string) string

Ownership constructs an "owner:group" string for chown commands. If only owner is provided, returns "owner". If only group is provided, returns ":group". If both are provided, returns "owner:group". Returns empty string if both are empty.

func ResolveAndValidatePath

func ResolveAndValidatePath(path string) (string, error)

ResolveAndValidatePath resolves symlinks in the parent directory of the given path and returns the cleaned, resolved absolute path. This prevents symlink traversal attacks where a symlink could redirect writes to sensitive locations.

func ResolveOwnership

func ResolveOwnership(owner, group string) (uid, gid int, err error)

ResolveOwnership maps owner/group NAMES to numeric uid/gid for the fd-based fchown helpers. An empty name yields -1 ("leave unchanged", the chown(2) sentinel). A name is resolved against the user/group database first and falls back to a numeric id (matching chown(1), which accepts raw ids); a value that is neither a known name nor a number is an error. Callers MUST fail closed on that error rather than silently widening or narrowing ownership.

func SetDirPermissionsNoFollow

func SetDirPermissionsNoFollow(path string, mode os.FileMode, uid, gid int) error

SetDirPermissionsNoFollow applies mode and ownership to a DIRECTORY through an O_NOFOLLOW|O_DIRECTORY fd, so the operation acts on the inode that was opened and a later path swap cannot redirect it. This is the TOCTOU-closing replacement for path-based dir chmod/chown (WS6 #5).

  • A symlink at path fails the open (ELOOP) instead of being dereferenced — a user who can swap a managed directory for a symlink to /etc or /root cannot redirect a root-run chmod/chown onto the target.
  • A non-directory fails the open (ENOTDIR).
  • uid and/or gid of -1 leaves that id unchanged (chown(2) sentinel); when both are -1 the chown is skipped entirely.

The mode is always applied; callers that do not want to change the mode should pass the directory's existing mode.

func ValidatePath

func ValidatePath(path string) error

ValidatePath rejects paths that would be unsafe to pass through a privileged command as positional arguments. The checks are intentionally minimal — no symlink resolution, no allowlisting of roots — so callers that need stricter semantics can layer them on top.

  • empty → ErrInvalidPath (an empty argv entry collapses verb + path and accidentally runs the command against the cwd)
  • NUL byte → ErrInvalidPath (the system call interprets NUL as string termination; a NUL inside the path lets an attacker smuggle a different path past higher-level filters)
  • leading `-` → ErrInvalidPath (would be parsed as a flag by rm, chmod, chown, mkdir, etc. — even with a `--` end-of-options separator some tools still treat it as an option in edge versions)

This is the central chokepoint every privileged file op calls before exec.

Types

type DirEntry

type DirEntry struct {
	Name  string
	IsDir bool
}

DirEntry is one entry returned by Manager.ReadDir: the bare name (not a full path) and whether it is a directory. It is a minimal, backend-portable view — the escalated (find-based) listing cannot cheaply reproduce the full os.DirEntry / FileInfo surface, and the callers that enumerate a managed config directory need only the name plus is-it-a-directory. A symlink is reported with IsDir=false (its own type, not the target's), so a caller iterating regular files processes it like any other non-directory.

type Manager

type Manager interface {
	// ReadFile returns the contents of path. A path that does not exist yields a
	// wrapped fs.ErrNotExist (not a silent empty result), so a caller can tell
	// "absent" from "present but empty"; opt into absent-as-empty with
	// errors.Is(err, fs.ErrNotExist). A present empty file returns (nil, nil).
	ReadFile(ctx context.Context, path string) ([]byte, error)
	// ReadDir lists the immediate entries of a directory (no recursion). A
	// missing directory yields a wrapped fs.ErrNotExist (the same explicit-
	// absence contract as ReadFile); a non-directory target is an error too,
	// never a silent empty listing.
	ReadDir(ctx context.Context, path string) ([]DirEntry, error)
	// WriteFile writes data to path atomically. When the Runner's backend is
	// Direct the write is also symlink-safe (fd-anchored); see the package doc.
	WriteFile(ctx context.Context, path string, data []byte, opts WriteOptions) error
	// WriteFileExclusive writes data to path only if path does not already
	// exist, returning ErrExists (matchable with errors.Is) when it does. The
	// existence test and the create are the SAME atomic operation — on Linux a
	// RENAME_NOREPLACE rename, on the escalated backend an ln(1) — so unlike
	// Exists-then-WriteFile there is no window in which another writer can slip a
	// file in between. Callers that need to know whether THEY created a file, in
	// order to decide whether they may later delete it, must use this rather than
	// probing first: a probe would let them adopt, and then destroy, someone
	// else's file.
	WriteFileExclusive(ctx context.Context, path string, data []byte, opts WriteOptions) error
	// Exists reports whether path exists. The probe runs through the privilege
	// backend so it can see paths in directories the caller cannot traverse
	// (e.g. /etc/sudoers.d, mode 0750). A runner/ctx failure is returned as an
	// error (fail-closed) rather than reported as "absent".
	Exists(ctx context.Context, path string) (bool, error)
	// Mkdir creates a directory per opts.
	Mkdir(ctx context.Context, path string, opts MkdirOptions) error
	// Remove deletes a single file and returns any error.
	Remove(ctx context.Context, path string) error
	// RemoveDir removes a directory and its contents. It refuses any target at
	// or under a security-relevant system prefix (deny-by-default) and, on the
	// Direct backend, never follows a symlink (fd-anchored recursive delete).
	RemoveDir(ctx context.Context, path string) error
	// Copy copies src to dst and applies opts (mode/ownership) to dst.
	Copy(ctx context.Context, src, dst string, opts WriteOptions) error
	// CopyTree recursively copies the tree at src to dst (cp -a), merging into
	// dst rather than nesting under it. A non-zero opts.Mode chmods the dst root;
	// opts.Owner/Group, if set, are applied recursively.
	CopyTree(ctx context.Context, src, dst string, opts WriteOptions) error
	// SetMode sets the file mode (chmod).
	SetMode(ctx context.Context, path string, mode os.FileMode) error
	// SetOwnership sets the file owner and group (chown). Either may be empty;
	// both empty is a no-op.
	SetOwnership(ctx context.Context, path, owner, group string) error
	// SetOwnershipRecursive changes ownership of a path and all its contents
	// (chown -R). Both owner and group empty is a no-op.
	SetOwnershipRecursive(ctx context.Context, path, owner, group string) error
	// IsReadOnly reports whether the filesystem mounted at path is read-only.
	IsReadOnly(ctx context.Context, path string) (bool, error)
	// RemountRW remounts the filesystem at path read-write.
	RemountRW(ctx context.Context, path string) error
	// ListMounts enumerates every mounted filesystem (source/target/fstype/ro).
	// The enumeration counterpart to IsReadOnly/RemountRW — for acting on every
	// matching mount (e.g. remounting all read-only on-disk mounts).
	ListMounts(ctx context.Context) ([]MountInfo, error)
}

Manager is the privileged filesystem surface. Every method takes a context so the caller controls timeout/cancellation. A non-zero exit from a shelled command becomes an *exec.CommandError carrying the exit code and stderr.

func New

func New(runner sysexec.Runner) (Manager, error)

New builds a filesystem Manager driven by runner. A nil runner is rejected (fail-closed). New is pure — it does not probe the host.

type MkdirOptions

type MkdirOptions struct {
	// Mode is applied to the created directory. Zero leaves the OS default
	// (mkdir's mode minus umask) in place.
	Mode os.FileMode
	// Owner and Group set the directory's ownership. Either may be empty.
	Owner, Group string
	// Recursive creates parent directories as needed (mkdir -p).
	Recursive bool
}

MkdirOptions configures a Manager.Mkdir call.

type MountInfo

type MountInfo struct {
	Source   string // backing device or pseudo-source (e.g. /dev/sda1, tmpfs, proc)
	Target   string // mountpoint
	FSType   string // filesystem type (ext4, xfs, tmpfs, ...)
	ReadOnly bool   // the mount carries the "ro" VFS option
}

MountInfo describes one mounted filesystem, as reported by findmnt.

type WriteOptions

type WriteOptions struct {
	// Mode is the file mode applied before the file is reachable by name. Zero
	// means 0644 (the conventional mode for a managed config file), so the
	// resulting inode always carries a deterministic mode rather than depending
	// on the process umask.
	Mode os.FileMode
	// Owner and Group set the file's ownership. Either may be empty; both empty
	// leaves ownership at the OS default.
	Owner, Group string
	// Backup, when non-empty, copies the existing file at the destination to
	// this path before the new content replaces it (no-op if the destination
	// does not yet exist). The copy is taken crash-safely — the destination is
	// never left absent — which the agent's self-update relies on.
	Backup string
}

WriteOptions configures a Manager.WriteFile (or Copy) call.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL