Files
ARTEX/server/execpriv_unix.go
T
BaaRai e73cdeda93 security(agent): share only run-dir leaves; main agent gets its own leaf
The task and chat workspace trees were shared whole with the executor
group, and the main agent and the planner worked in tasks/<id>, the parent
of every worker directory: the executor could rename, remove or replace a
run directory, its own included, and plant entries beside them.

- Layout: no agent working directory is an ancestor of another. The main
  agent and the planner work in tasks/<id>/main, a worker in
  tasks/<id>/i<N>, a chat in sessions/<id>. With the privilege drop on,
  tasks/, sessions/ and tasks/<id> are root:root 0755 and only the leaves
  are root:<exec gid> 2775.
- PrepareExecPrivilege no longer shares tasks/ and sessions/. It sets the
  parents, shares the leaves found on disk with what they hold, and
  registers the run-directory maker (agent.SetRunDirMaker). ensureRunDir
  and the chat session directory go through it: each level is created
  with Mkdir and set through a descriptor opened with O_NOFOLLOW, parents
  before the leaf, so a link planted where a run directory goes is
  refused. Without the drop both stay a plain MkdirAll.
- Uploads for the main agent land in tasks/<id>/main/uploads, and the
  attachment paths given to it use the same directory; session uploads
  create sessions/<id> by the same rule.
- Task archives still pack and delete the whole task directory, so the
  package holds files/tasks/<id>/main and i<N>. The package keeps neither
  owners nor directory modes: the restore puts the layout back
  (installTaskArchiveFiles takes the privilege).
- Existing data is not migrated. Files a task wrote directly in
  tasks/<id>/ stay there with their owner and mode; the main agent starts
  in an empty tasks/<id>/main and its file tools no longer reach them.

Tests: TestRunDirLayout and TestIsRunDirName (agent); root-only
TestRunDirLayoutAsRoot, TestRunDirSiblingsProtectedAsRoot,
TestRunDirLayoutOnExistingTreeAsRoot and
TestTaskArchiveRestoreRunDirOwnershipAsRoot (server). The archive tests
use the main/ and i<N> leaves. SECURITY.md states the invariant, names the
race that remains and drops ensureRunDir from the residual list.
2026-11-20 05:35:55 +01:00

497 lines
16 KiB
Go

//go:build unix
package server
import (
"errors"
"fmt"
"io/fs"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
"github.com/Autumn-27/artex/agent"
)
// Environment names the shims read. They carry no secret: the executor id, the real
// bash path and the executor's home directory.
const (
envExecBash = "ARTEX_EXEC_BASH"
envExecUID = "ARTEX_EXEC_UID"
envExecGID = "ARTEX_EXEC_GID"
envExecHome = "ARTEX_EXEC_HOME"
)
// execHomeDir is the executor's home under the data directory. The server's HOME
// (/root in the image) is not writable for the executor, so caches of npm, go, pip,
// bbot or Playwright would fail there.
const execHomeDir = "exec-home"
func execPrivilegeSupported() bool { return true }
func serverIsRoot() bool { return os.Geteuid() == 0 }
// applyExecCredential runs c as the executor identity. The server's own children
// (custom tools) use it directly; the Norma children go through the shims. Call it
// after c.Env is set: it points HOME and XDG_CACHE_HOME at the executor's home.
func applyExecCredential(c *exec.Cmd, p ExecPrivilege) {
if !p.Enabled {
return
}
if c.SysProcAttr == nil {
c.SysProcAttr = &syscall.SysProcAttr{}
}
c.SysProcAttr.Credential = &syscall.Credential{Uid: p.UID, Gid: p.GID, Groups: []uint32{p.GID}}
if home := execHomeEnv(); home != nil {
if c.Env == nil {
c.Env = os.Environ()
}
c.Env = append(c.Env, home...) // later entries win in exec.Cmd
}
}
// execHomeEnv returns HOME and XDG_CACHE_HOME for an executor process, or nil when
// PrepareExecPrivilege has not set up the home.
func execHomeEnv() []string {
home := os.Getenv(envExecHome)
if home == "" {
return nil
}
return []string{"HOME=" + home, "XDG_CACHE_HOME=" + filepath.Join(home, ".cache")}
}
// prepareExecHome creates the executor's home, owned by the executor, and records
// its path for the shims and applyExecCredential.
func prepareExecHome(p ExecPrivilege, dataDir string) error {
abs, err := filepath.Abs(dataDir)
if err != nil {
return err
}
home := filepath.Join(abs, execHomeDir)
if err := os.MkdirAll(home, 0o700); err != nil {
return err
}
fi, err := os.Lstat(home)
if err != nil {
return err
}
if !fi.IsDir() {
return fmt.Errorf("%s is not a directory", home)
}
if err := os.Lchown(home, int(p.UID), int(p.GID)); err != nil {
return err
}
if err := os.Chmod(home, 0o700); err != nil {
return err
}
return os.Setenv(envExecHome, home)
}
// execScriptDir is the directory under the data directory that custom-tool scripts
// are written to when agent processes run as the executor.
const execScriptDir = "exec-scripts"
// prepareExecScriptDir creates the script directory and returns its path. It is
// owned by root with the executor as its group and mode 0750: the executor can
// reach and read a script there, and cannot create, rename or replace an entry.
// The run directory is no place for the script: the executor can write there, and
// could turn the script's directory into a symlink that root then writes through.
func prepareExecScriptDir(p ExecPrivilege, dataDir string) (string, error) {
abs, err := filepath.Abs(dataDir)
if err != nil {
return "", err
}
dir := filepath.Join(abs, execScriptDir)
if err := os.Mkdir(dir, 0o750); err != nil && !errors.Is(err, fs.ErrExist) {
return "", err
}
fi, err := os.Lstat(dir)
if err != nil {
return "", err
}
if !fi.IsDir() {
return "", fmt.Errorf("%s is not a directory", dir)
}
if err := os.Lchown(dir, 0, int(p.GID)); err != nil {
return "", err
}
if err := os.Chmod(dir, 0o750); err != nil {
return "", err
}
return dir, nil
}
// prepareExecScript lets the executor read a script the server wrote: the file stays
// root-owned and becomes readable by the executor group only.
func prepareExecScript(p ExecPrivilege, path string) error {
if !p.Enabled {
return nil
}
if err := os.Chown(path, -1, int(p.GID)); err != nil {
return err
}
return os.Chmod(path, 0o640)
}
// PrepareExecPrivilege sets up the state the executor needs before the server opens
// its stores. Only the run directories are shared with the executor group (setgid,
// group read/write, umask 002): tasks/<id>/main, tasks/<id>/i<N> and sessions/<id>.
// Their parents (tasks/, sessions/ and tasks/<id>) are root:root 0755, so the
// executor cannot create, rename or remove a run directory, and no run directory is
// an ancestor of another. Inside a run directory new subdirectories inherit the
// group. The key files and the config file (which can hold the database DSN) are
// restricted to root. Nothing else under the data directory changes; directories a
// root-only path needs are left as they are. It sets p.ScriptDir to the script
// directory it creates.
func PrepareExecPrivilege(p *ExecPrivilege, dataDir, keyDir, configPath string) error {
if !p.Enabled {
return nil
}
gid := int(p.GID)
if err := shareRunDirs(dataDir, gid); err != nil {
return fmt.Errorf("share the run directories with the executor group: %w", err)
}
agent.SetRunDirMaker(func(base, leaf string) error { return makeRunDir(base, leaf, gid) })
if err := prepareExecHome(*p, dataDir); err != nil {
return fmt.Errorf("prepare the executor home: %w", err)
}
scriptDir, err := prepareExecScriptDir(*p, dataDir)
if err != nil {
return fmt.Errorf("prepare the executor script directory: %w", err)
}
p.ScriptDir = scriptDir
tasks := filepath.Join(dataDir, "tasks")
for _, name := range []string{"jwt.key", "secret.key"} {
if keyDir == "" {
break
}
path := filepath.Join(keyDir, name)
if _, err := os.Stat(path); err == nil {
if err := os.Chmod(path, 0o600); err != nil {
return fmt.Errorf("restrict %s to root: %w", path, err)
}
}
}
if configPath != "" {
if fi, err := os.Stat(configPath); err == nil && fi.Mode().Perm()&0o077 != 0 {
if err := os.Chmod(configPath, 0o600); err != nil {
return fmt.Errorf("restrict %s to root: %w", configPath, err)
}
log.Printf("[exec] %s set to 0600: it can hold the database DSN", configPath)
}
}
// Files and directories the server creates from now on are group-writable, so
// the executor can write what the server puts in a run directory.
syscall.Umask(0o002)
log.Printf("[exec] agent processes run as uid %d gid %d; the run directories under %s are shared with that group", p.UID, p.GID, tasks)
return nil
}
// runDirMode is the mode of a run directory: group-writable, and setgid so what is
// created in it keeps the executor group.
const runDirMode = 0o775 | os.ModeSetgid
// setDirOwner makes dir root:gid with mode. dir is opened without following a
// symlink and changed through the descriptor, so a planted link is refused and
// never changes another directory.
func setDirOwner(dir string, gid int, mode os.FileMode) error {
f, err := os.OpenFile(dir, os.O_RDONLY|syscall.O_DIRECTORY|syscall.O_NOFOLLOW, 0)
if err != nil {
return err
}
defer f.Close()
if err := f.Chown(0, gid); err != nil {
return err
}
return f.Chmod(mode)
}
// makeRunDir creates the run directory leaf below base. Every directory between
// base and the leaf is root:root 0755, and the leaf alone is shared with the
// executor group. A parent is set before the next level is touched: once it is
// root-only, the executor cannot swap what is below it.
func makeRunDir(base, leaf string, gid int) error {
rel, err := filepath.Rel(base, leaf)
if err != nil || rel == "." || !filepath.IsLocal(rel) {
return fmt.Errorf("%s is not below %s", leaf, base)
}
parts := strings.Split(rel, string(filepath.Separator))
dir := base
for i, part := range parts {
dir = filepath.Join(dir, part)
group, mode := 0, os.FileMode(0o755)
if i == len(parts)-1 {
group, mode = gid, runDirMode
}
if err := os.Mkdir(dir, mode.Perm()); err != nil && !errors.Is(err, fs.ErrExist) {
return err
}
if err := setDirOwner(dir, group, mode); err != nil {
return err
}
}
return nil
}
// shareRunDirs applies the run-directory layout to what is on disk: tasks/ and
// sessions/ become root:root 0755, each task directory too, and each run directory
// (sessions/<id>, tasks/<id>/main, tasks/<id>/i<N>) is shared with the executor
// group with what it holds.
func shareRunDirs(dataDir string, gid int) error {
if err := os.MkdirAll(dataDir, 0o755); err != nil {
return err
}
for _, sub := range []string{"tasks", "sessions"} {
root := filepath.Join(dataDir, sub)
if err := os.Mkdir(root, 0o755); err != nil && !errors.Is(err, fs.ErrExist) {
return err
}
if err := setDirOwner(root, 0, 0o755); err != nil {
return err
}
entries, err := os.ReadDir(root)
if err != nil {
return err
}
for _, e := range entries {
if !e.IsDir() {
continue
}
dir := filepath.Join(root, e.Name())
if sub == "tasks" {
err = shareTaskDir(dir, gid)
} else {
err = shareRunDir(dir, gid)
}
if err != nil {
return err
}
}
}
return nil
}
// shareTaskDir makes a task directory root:root 0755 and shares the run directories
// in it. Its other entries are left as they are: a task whose main agent worked in
// the task directory itself keeps its files there, with the owner and mode they had.
func shareTaskDir(taskDir string, gid int) error {
if err := setDirOwner(taskDir, 0, 0o755); err != nil {
return err
}
entries, err := os.ReadDir(taskDir)
if err != nil {
return err
}
for _, e := range entries {
if !e.IsDir() || !agent.IsRunDirName(e.Name()) {
continue
}
if err := shareRunDir(filepath.Join(taskDir, e.Name()), gid); err != nil {
return err
}
}
return nil
}
// shareRunDir shares one run directory and what it holds with the executor group.
func shareRunDir(leaf string, gid int) error {
if err := setDirOwner(leaf, gid, runDirMode); err != nil {
return err
}
return shareWithExecGroup(leaf, gid)
}
// shareRestoredTaskDir puts the run-directory layout back on a task directory that
// was restored from an archive: the package keeps neither owners nor directory modes.
func shareRestoredTaskDir(p ExecPrivilege, taskDir string) error {
if !p.Enabled {
return nil
}
return shareTaskDir(taskDir, int(p.GID))
}
// shareWithExecGroup gives the executor group the tree under root: the group owns
// each entry and gets read/write (and traverse on directories), and directories set
// the setgid bit so anything created below them keeps the group.
func shareWithExecGroup(root string, gid int) error {
return filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if err := os.Lchown(path, -1, gid); err != nil {
return err
}
if d.Type()&fs.ModeSymlink != 0 {
return nil
}
info, err := d.Info()
if err != nil {
return err
}
mode := info.Mode().Perm() | 0o060
if d.IsDir() {
mode = (info.Mode().Perm() | 0o070) | os.ModeSetgid
}
return os.Chmod(path, mode)
})
}
// InstallBashShim makes the Bash tool, the interactive shell and background tasks
// run as the executor. Norma starts them with exec.Command("bash"), which takes no
// credential, so a symlink named bash to this binary is placed first on PATH. The
// shim (RunExecShimIfRequested) drops to the executor identity and execs the real
// bash, which keeps the PID and the process group that Norma tracks.
func InstallBashShim(p ExecPrivilege) error {
if !p.Enabled {
return nil
}
realBash, err := exec.LookPath("bash")
if err != nil {
return fmt.Errorf("bash is needed for the agent shell: %w", err)
}
self, err := os.Executable()
if err != nil {
return fmt.Errorf("locate the server binary: %w", err)
}
if self, err = filepath.EvalSymlinks(self); err != nil {
return fmt.Errorf("resolve the server binary: %w", err)
}
dir, err := os.MkdirTemp("", "artex-exec-")
if err != nil {
return fmt.Errorf("create the shim directory: %w", err)
}
// Root-owned and traversable: the executor can run the shim, cannot change it.
if err := os.Chmod(dir, 0o755); err != nil {
return err
}
if err := os.Symlink(self, filepath.Join(dir, "bash")); err != nil {
return fmt.Errorf("create the bash shim: %w", err)
}
if err := os.Setenv(envExecBash, realBash); err != nil {
return err
}
if err := os.Setenv(envExecUID, execIDString(p.UID)); err != nil {
return err
}
if err := os.Setenv(envExecGID, execIDString(p.GID)); err != nil {
return err
}
return os.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
}
// RunExecShimIfRequested makes the process a privilege-drop shim when it was started
// as one: as bash through the PATH shim, or as artex __artex-exec-drop for an MCP
// stdio command. It exits or execs the target; it returns only for an ordinary start.
func RunExecShimIfRequested(argv []string) {
if len(argv) == 0 {
return
}
if filepath.Base(argv[0]) == "bash" && os.Getenv(envExecBash) != "" {
runBashShim(argv)
}
if len(argv) >= 2 && argv[1] == execDropArg {
runDropShim(argv[2:])
}
}
func runBashShim(argv []string) {
uid, gid, err := execIDsFromEnv()
if err != nil {
shimFail(err)
}
if err := enterExecutor(uid, gid); err != nil {
shimFail(err)
}
shimExec(os.Getenv(envExecBash), argv)
}
// enterExecutor drops to uid and gid. When this call performs the switch (not in a
// nested shell already running as the executor, whose HOME the agent may have set),
// HOME and XDG_CACHE_HOME move to the executor's home first.
func enterExecutor(uid, gid int) error {
if os.Getuid() != uid || os.Getgid() != gid {
for _, kv := range execHomeEnv() {
k, v, _ := strings.Cut(kv, "=")
if err := os.Setenv(k, v); err != nil {
return err
}
}
}
return dropTo(uid, gid)
}
// runDropShim handles: <uid> <gid> -- <command> <args...>.
func runDropShim(args []string) {
if len(args) < 3 || args[2] != "--" {
shimFail(errors.New("drop shim needs <uid> <gid> -- <command> [args]"))
}
uid, errU := strconv.Atoi(args[0])
gid, errG := strconv.Atoi(args[1])
if errU != nil || errG != nil || len(args) < 4 {
shimFail(errors.New("drop shim: malformed identity or command"))
}
command := args[3]
target := command
if !strings.Contains(command, "/") {
resolved, err := exec.LookPath(command)
if err != nil {
shimFail(fmt.Errorf("command %q: %w", command, err))
}
target = resolved
}
if err := enterExecutor(uid, gid); err != nil {
shimFail(err)
}
shimExec(target, args[3:])
}
func execIDsFromEnv() (int, int, error) {
uid, errU := strconv.Atoi(os.Getenv(envExecUID))
gid, errG := strconv.Atoi(os.Getenv(envExecGID))
if errU != nil || errG != nil {
return 0, 0, errors.New("executor identity missing from the environment")
}
return uid, gid, nil
}
// dropTo switches the calling process to uid and gid, for good: the supplementary
// groups, gid and uid all change, and the result is checked. A process already
// running as the executor (a nested bash) passes straight through.
func dropTo(uid, gid int) error {
if os.Getuid() == uid && os.Getgid() == gid {
return nil
}
if os.Geteuid() != 0 {
return fmt.Errorf("cannot switch to uid %d: the process is not root", uid)
}
if err := syscall.Setgroups([]int{gid}); err != nil {
return fmt.Errorf("setgroups: %w", err)
}
if err := syscall.Setgid(gid); err != nil {
return fmt.Errorf("setgid %d: %w", gid, err)
}
if err := syscall.Setuid(uid); err != nil {
return fmt.Errorf("setuid %d: %w", uid, err)
}
if os.Getuid() != uid || os.Geteuid() != uid || os.Getgid() != gid {
return fmt.Errorf("privilege drop to %d:%d did not take effect", uid, gid)
}
return nil
}
// shimExec replaces the process with target. It returns only on failure, and then
// the shim stops: a command must never run with the server's identity by mistake.
func shimExec(target string, argv []string) {
err := syscall.Exec(target, argv, os.Environ())
shimFail(fmt.Errorf("exec %s: %w", target, err))
}
func shimFail(err error) {
fmt.Fprintf(os.Stderr, "artex: agent process not started: %v\n", err)
os.Exit(126)
}