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. Verified against real accounts in a container (make test-isolation).
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. Verified against real local accounts by make test-isolation-windows, which runs its privileged tier as SYSTEM via a scheduled task. That target exits 0 when the shell is not elevated, so a skip verifies nothing — see its own output before trusting a local pass; CI asserts every test by name for this reason.
A Windows worker MUST run as a service under LocalSystem, or as an account granted SeAssignPrimaryTokenPrivilege. CreateProcessAsUser — which os/exec invokes 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 naming the fix.
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 ¶
- Variables
- func Apply(cmd *exec.Cmd, cred *Credential) error
- func CheckGroupNotPrivileged(name string, gid uint32) error
- func CheckNotPrivileged(name string, uid uint32) error
- func ChownRecursive(root string, cred *Credential) error
- func CredentialDir(dataDir string) string
- func SecureWorkDir(dir string, cred *Credential) error
- func ValidateTraversable(paths ...string) error
- func WriteFileFchown(path string, data []byte, perm os.FileMode, cred *Credential) error
- type Config
- type Credential
- type CredentialStore
- type FakeAccount
- type Provider
- type Spec
Constants ¶
This section is empty.
Variables ¶
var ErrNotCapable = errors.New("isolation: worker cannot assume another OS identity")
ErrNotCapable is returned by Capable when this worker cannot drop privileges.
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 an ESCALATION mechanism rather than a containment one, 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 is a no-op, which is the pre-isolation path.
Implementations MUST preserve any SysProcAttr fields the caller already set — notably Setpgid, which the executor relies on to reap a whole process tree.
func CheckGroupNotPrivileged ¶
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 ¶
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.
Uses os.Lchown, NOT os.Chown, on every entry. root is daemon-created, but its CONTENTS are not: they come from job-supplied staging paths, and the operator's canonical 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 entirely — to the run-as-user identity, handing that identity write access to an arbitrary daemon-chosen (or worse, attacker-chosen-via-symlink) path. os.Lchown chowns the symlink entry itself and never follows it, closing that escalation.
func CredentialDir ¶
CredentialDir returns the directory holding stored run-as-user secrets for a worker whose data directory is dataDir. One helper, used by both the set-credential subcommand and the worker's own provider construction, so the two can never disagree about 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 ¶
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 chmod's anything — an earlier revision of this package's EnsureTraversable helper widened an existing directory's mode to make it traversable, which is exactly the anti-pattern this validation replaces: creating a directory 0711 from birth (see session.Manager's session root, staging's scratch base) is a different, safe operation, since it can only ever affect a directory the creating call itself is making for the first time. An operator-chosen path may sit under a directory that is deliberately restricted (/root, above all others) and must never be widened by sqi to make isolation "just work" — refusing to proceed with a clear, actionable error is the correct behavior instead.
A missing ancestor is not an error: os.MkdirAll creates it (at the correct mode) the first time the path is actually used, so there is nothing to validate yet.
Called from two places, never unconditionally: cmd/sqi-worker's boot-time validateIsolationAncestors (only when isolation.required is set — see its own doc for why Provider.Capable() alone is the wrong gate: root and will-actually-isolate are not the same predicate), and per-assignment from session.Manager.Create / staging.Stager.StageIn the moment an assignment actually carries run-as-user isolation, so that case fails only the one task rather than the whole worker.
func WriteFileFchown ¶
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 outright.
- 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+overwrites THAT inode, and a subsequent path-based chown would then hand the target uid ownership of it — escalation.
This mirrors internal/worker/pathmap's writeSecure exactly (see its doc): any existing entry at path is removed first (best-effort; 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 ever following it, so an attacker-planted symlink's target — or a hardlink's other name for the same inode — is never touched, only the entry at path is; O_EXCL then guarantees the create only succeeds when nothing (attacker-planted or otherwise) currently occupies that name. A naive O_EXCL-only create (this function's own previous shape) refused ANY pre-existing entry outright, including a second EMBEDDED FILE legitimately sharing the same name — two environments, or an environment and the step, each declaring one named "run" — which OpenJD's own last-wins semantics (see fmtres.AddFileVars's doc) requires this call to allow. Remove-then- create restores that: a legitimate second write succeeds (last-wins), while an attacker's swap is simply unlinked, never written through. If a job wins the race and recreates something in the tiny window between Remove and this Open, the O_EXCL create fails closed (EEXIST), which only ever fails that one task — a job can DoS itself this way, nothing more.
fchown (f.Chown) acts on the inode via the already-open descriptor, so it is immune to the directory entry being replaced after this call returns: there is nothing left at the path to race.
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 for why.
Provider string
// Logger records which identity-resolution path produced a Credential —
// notably 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 ¶
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 server-side and never in AssignMsg, because the worker↔server broker has no authentication yet.
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) — exactly the shape needed to exercise
// stripGID0FromSupplementary's gid-0 filter and its deliberate 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
// silently proceeded would run job code as the daemon 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 the things that actually break here — real uid/gid switching, supplementary groups, workdir ownership, 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 ¶
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 for its current verification status).