isolation

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: AGPL-3.0 Imports: 16 Imported by: 0 modules, 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 isolation runs job-supplied processes under a queue-configured OS identity instead of the worker daemon's own account.

Without it, submitting a job is arbitrary code execution as the worker service account: every task inherits the daemon's uid and environment. OpenJD's own model assumes a per-queue OS user performs this containment.

The platform-specific pieces are confined to this package. Callers deal only in Spec (a username) and Credential (an opaque handle).

Platform support

POSIX: setuid/setgid/supplementary groups, workdir chown/chmod, and the ancestor-traversability boot check. make test-isolation runs these against real accounts in a container.

Windows: LogonUserW produces a primary token, LoadUserProfileW mounts the target's registry hive and profile directory, session directories are secured with a protected NTFS DACL, and task processes are contained in a job object. make test-isolation-windows runs these against real local accounts, its privileged tier as SYSTEM via a scheduled task. That target exits 0 when the shell is not elevated, so check its output for skips before trusting a local pass; CI asserts every test by name.

A Windows worker must run as a service under LocalSystem, or as an account granted SeAssignPrimaryTokenPrivilege. CreateProcessAsUser, which os/exec calls whenever SysProcAttr.Token is set, requires that privilege, and an elevated Administrator does not hold it by default. Capable() reports this at boot with a message saying how to fix it.

The s4u credential provider is not implemented and is refused explicitly. Its logon needs no password but yields a token with no network credentials, so UNC and share access fail as ANONYMOUS inside the task.

Index

Constants

This section is empty.

Variables

View Source
var ErrNotCapable = errors.New("isolation: worker cannot assume another OS identity")

ErrNotCapable is returned by Capable when this worker cannot drop privileges.

View Source
var ErrRefusedPrivileged = errors.New("isolation: refusing to run as a privileged account")

ErrRefusedPrivileged is returned when a Spec names a privileged account. Honoring one would make isolation a means of escalation rather than of containment, so this refusal is not configurable.

Functions

func Apply

func Apply(cmd *exec.Cmd, cred *Credential) error

Apply attaches cred to cmd so the process starts under that identity. A nil cred (no isolation) is a no-op.

Implementations must preserve any SysProcAttr fields the caller already set, such as Setpgid, which the executor relies on to reap a whole process tree.

func CheckGroupNotPrivileged

func CheckGroupNotPrivileged(name string, gid uint32) error

CheckGroupNotPrivileged rejects an explicitly requested group the same way CheckNotPrivileged rejects a privileged account: gid 0 and a fixed set of privileged group names are refused outright, regardless of what a queue operator configured.

func CheckNotPrivileged

func CheckNotPrivileged(name string, uid uint32) error

CheckNotPrivileged rejects privileged targets by name and by uid. uid is ignored on Windows, where callers pass 1.

func ChownRecursive

func ChownRecursive(root string, cred *Credential) error

ChownRecursive walks root and chowns every entry to cred's uid/gid. Apply only affects the process launched via exec.Cmd; files the daemon writes directly to disk (e.g. staged inputs, pre-created staged-output directories) are untouched by it and remain daemon-owned unless chowned explicitly. A nil cred is a no-op, matching Apply's no-isolation behavior.

It uses os.Lchown, not os.Chown, on every entry. root is daemon-created, but its contents come from job-supplied staging paths, and the operator's usual sync command (rsync -a) preserves symlinks rather than following them. os.Chown dereferences a symlink and would chown whatever it points at, including a target outside root, to the run-as-user identity, giving that identity write access to a path a job chose. os.Lchown chowns the symlink entry itself and never follows it.

func CredentialDir

func CredentialDir(dataDir string) string

CredentialDir returns the directory holding stored run-as-user secrets for a worker whose data directory is dataDir. Both the set-credential subcommand and the worker's provider construction use it, so the two agree on where the file lives.

func SecureWorkDir

func SecureWorkDir(dir string, cred *Credential) error

SecureWorkDir restricts dir to cred's identity: chown to cred's uid/gid, then chmod 0700. Called once at session creation so a session's scratch directory is unreadable to any user but the one its tasks run as. A nil cred is a no-op, matching Apply's no-isolation behavior.

func ValidateTraversable

func ValidateTraversable(paths ...string) error

ValidateTraversable checks path and every existing ancestor of it for the execute ("search") bit for others, returning an actionable error naming the first offending directory instead of silently widening it.

It never chmods anything. Creating a directory 0711 (session.Manager's session root, staging's scratch base) affects only a directory the call is creating; widening an existing directory is different. An operator-chosen path may sit under a directory restricted on purpose (/root above all), which sqi must not widen to make isolation work, so it refuses with an error instead.

A missing ancestor is not an error: os.MkdirAll creates it (at the correct mode) the first time the path is used, so there is nothing to validate yet.

Called from two places: cmd/sqi-worker's boot-time validateIsolationAncestors (only when isolation.required is set; see its doc for why Provider.Capable() is the wrong gate), and per assignment from session.Manager.Create / staging.Stager.StageIn when an assignment carries run-as-user isolation, so that case fails only the one task rather than the whole worker.

func WriteFileFchown

func WriteFileFchown(path string, data []byte, perm os.FileMode, cred *Credential) error

WriteFileFchown (re)writes path with data, refusing to write through any filesystem entry a job could have swapped in at that deterministic path, and, when cred is non-nil, chowns the result to cred's identity via fchown on the still-open descriptor.

Step embedded files are written by the root daemon after job code has already executed as the target uid (the environment onEnter action runs before any task's embedded files are written), at a deterministic path (e.g. {{Task.File.run}}). Between a plain os.WriteFile and a later path-based chown, the target uid could replace that path with:

  • a symlink: an open with no O_NOFOLLOW would follow it and write through to the symlink's target. O_NOFOLLOW refuses the open.
  • a hardlink to a root-owned file elsewhere on the same filesystem: a plain os.WriteFile's O_TRUNC follows the existing directory entry and truncates and overwrites that inode, and a later path-based chown would hand the target uid ownership of it.

This mirrors internal/worker/pathmap's writeSecure (see its doc): any existing entry at path is removed first (fs.ErrNotExist is not an error; there may be nothing there yet), then the file is created fresh with O_EXCL|O_NOFOLLOW. Remove unlinks the directory entry without following it, so a planted symlink's target, or a hardlink's other name for the same inode, is never touched; O_EXCL then makes the create succeed only when nothing occupies that name. Removing first lets a second embedded file with the same name (two environments, or an environment and the step, each declaring one named "run") overwrite the first, as OpenJD's last-wins semantics require (see fmtres.AddFileVars's doc), while a planted entry is unlinked, never written through. If a job recreates something in the window between Remove and this Open, the O_EXCL create fails with EEXIST, which fails only that job's own task.

fchown (f.Chown) acts on the inode through the open descriptor, so replacing the directory entry afterward has no effect on it.

Types

type Config

type Config struct {
	// CredentialStore supplies the secret for the Windows logon_user provider.
	// Ignored on POSIX, where the worker must already run as root.
	CredentialStore CredentialStore

	// Provider selects the Windows credential mechanism
	// (workerconfig.IsolationConfig.Provider). Ignored on POSIX, where the
	// worker must already run as root and there is only one mechanism.
	// "logon_user" is the only supported value; "s4u" is refused (see that
	// field's doc in internal/worker/config).
	Provider string

	// Logger records which identity-resolution path produced a Credential —
	// in particular when the POSIX provider falls back from pure-Go os/user to
	// shelling out to NSS-aware tools (id(1)/getent(1)). Nil is replaced with
	// a discard logger, matching internal/worker/lease and .../executor.
	Logger *slog.Logger
}

Config configures NewProvider.

type Credential

type Credential struct {

	// Home is the target user's home directory. Callers rewrite HOME to this;
	// leaving the daemon's HOME makes DCCs write configs where the task cannot.
	Home string
	// contains filtered or unexported fields
}

Credential holds a resolved POSIX identity.

func (*Credential) Close

func (*Credential) Close() error

Close releases the credential. POSIX credentials hold no OS handle.

type CredentialStore

type CredentialStore interface {
	Secret(user string) (string, error)
}

CredentialStore supplies the secret for a local account, used by the Windows logon_user provider. Declared here rather than in provider_windows.go because Config references it and Config must compile on every platform.

Secrets live on the worker, never on the server and never in AssignMsg, so they never cross the broker.

func NewFileStore

func NewFileStore(_ string) CredentialStore

NewFileStore returns a CredentialStore for dir. On this platform every lookup fails.

type FakeAccount

type FakeAccount struct {
	UID uint32
	GID uint32
	// Groups maps the names of groups this account belongs to onto their
	// gid, so a Spec.Group request can be validated for membership the same
	// way the real provider validates it against os/user.GroupIds(). A group
	// name absent from this map is treated as one the account does not
	// belong to, regardless of whether it "exists" in some other account's
	// entry.
	Groups map[string]uint32
	// SupplementaryGIDs is the raw supplementary group gid list the
	// credential is built from, mirroring what GroupIds()/`id -G` would
	// report for a real account. Unlike Groups, this is not name-keyed and
	// may contain gids with no corresponding entry in Groups (e.g. gid 0, or
	// a privileged named group's gid), the shape needed to exercise
	// stripGID0FromSupplementary's gid-0 filter and its choice to leave
	// privileged named groups alone.
	SupplementaryGIDs []uint32
	Home              string
}

FakeAccount is one entry in a fake provider's account table.

type Provider

type Provider interface {
	// Resolve produces a Credential for spec. It must return an error rather
	// than a nil Credential when the identity cannot be assumed: a caller that
	// proceeded would run job code as the worker while appearing isolated.
	Resolve(ctx context.Context, spec Spec) (*Credential, error)

	// Capable reports whether this worker can assume another identity at all:
	// root on POSIX, the relevant privilege on Windows. Checked once at boot.
	Capable() error
}

Provider turns a Spec into a platform Credential.

func NewFake

func NewFake(accounts map[string]FakeAccount) Provider

NewFake returns an in-memory Provider for unit tests.

A fake cannot verify uid/gid switching, supplementary groups, workdir ownership or Setpgid survival; those need make test-isolation against a real OS. Use this only for policy logic.

func NewFakeIncapable

func NewFakeIncapable(accounts map[string]FakeAccount) Provider

NewFakeIncapable returns an in-memory Provider whose Capable() always reports ErrNotCapable, for tests of the not-capable startup path.

func NewProvider

func NewProvider(cfg Config) (Provider, error)

NewProvider returns the platform Provider: POSIX credential switching via setuid/setgid/supplementary groups, or the Windows LogonUserW-based provider (see the package doc's Windows section).

type Spec

type Spec struct {
	// User is the OS username. Required.
	User string
	// Group is the OS group; empty means the user's primary group.
	Group string
}

Spec names the OS identity a process must run as.

Jump to

Keyboard shortcuts

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