Files
ARTEX/cmd/artex-exec-wrap/main.go
BaaRai 643e814ad6 security: isolate task execution in per-task sandbox worker and egress proxy
Introduce the sandbox MVP architecture separating panel credentials and
PostgreSQL access from model-controlled tool execution:

- Runner service (cmd/artex-runner, sandbox/) owning /var/run/docker.sock
  behind bearer-token auth (ARTEX_RUNNER_TOKEN) with POST /v1/tasks/{id}/exec,
  POST /v1/tasks/{id}/kill, DELETE /v1/tasks/{id}, and GET /v1/health.
- Strict input and env validation (400 on forbidden secret/DB/cloud env
  patterns or values > 8192 bytes, strict task ID and /workspace workdir).
- Hardened per-task worker containers (Dockerfile.worker, artex-worker:local,
  cmd/artex-exec-wrap): uid/gid 10001, artex-exec-wrap --init PID 1 zombie
  reaper, read-only rootfs, cap-drop ALL, no-new-privileges, pids/mem/cpu
  limits, tmpfs /tmp and /home/exec, only /app/data/tasks/<id>:/workspace:rw,
  only verified internal=true runner-labeled network artex-task-<id>.
- Kernel-backed kill-switch (zero agent-writable state): Kill executes
  artex-exec-wrap --kill-uid 10001 as uid 10001 scanning /proc directly
  (defeating setsid, nohup, nested double-forked trap-TERM daemons, and /tmp
  tampering), verifies zero non-PID-1 uid-10001 processes remain, and falls
  back to force-removing the worker container if any check fails. Dead
  workers/proxies are recreated automatically when startContainer fails.
- Operator-only scope approval (migration 0023_task_scope_operator_approval.sql):
  adds task_scope.approved_by_operator BOOLEAN NOT NULL DEFAULT FALSE, set
  true exclusively by operator API/UI (AddOperatorScope) and operator-selected
  TaskCreateOptions.CompanyIDs (insertTaskCompanies). AddAgentScope and
  AddAutoScope leave it false (coverage-only). taskSandboxRunInfo reads only
  approved, non-expanded rows (and expands company scope only for approved
  company rows); tasks with no approved scope deny all egress.
- Per-task egress proxy (cmd/artex-egress-proxy, Dockerfile.egress-proxy,
  artex-egress-proxy:local): HTTP/HTTPS CONNECT (:3128) and SOCKS5 (:1080),
  deny-by-default allowlist with strict domain suffix enforcement, blocks
  RFC1918/loopback/link-local/IMDS and IPv6 unless in scope CIDRs, DNS
  pinning, and tamper-proof JSONL audit logging to a proxy-only mount
  (/app/data/egress-audit/<id>:/audit:rw) never mounted into the worker.
- Panel integration (agent/sandbox.go, agent/webfetch.go, server/sandbox.go,
  server/sharedbrowser_guard.go, server/assembly.go, server/customtool.go,
  docker-compose.sandbox.yml): ARTEX_SANDBOX defaults to required (fail closed,
  no local fallback), WebFetch and opt-in shared browser inherit the
  operator-approved sandbox.EgressPolicy (with target_gate or explicit proxy
  required for shared browser), custom script tools staged via symlink-confined
  workspace files (avoiding argv E2BIG), Pause/Stop/Delete wired to runner
  Kill/Delete.
- Documented breaking change and hardening details in docs/SANDBOX.md,
  README.md, and CHANGELOG.md.
2026-11-30 19:09:32 +01:00

252 lines
6.4 KiB
Go

//go:build unix
// Command artex-exec-wrap serves three roles inside artex-worker containers:
// 1. `--init`: runs as PID 1 inside the worker container, reaping all orphaned
// children (including setsid/nohup/double-fork descendants) on SIGCHLD until
// SIGTERM/SIGINT.
// 2. `--kill-uid <uid>`: executed as uid 10001 by artex-runner on Kill() (keeps --cap-drop ALL intact without CAP_KILL); scans /proc
// directly (trusting zero agent-writable state), sends SIGTERM then SIGKILL to
// every process owned by <uid> other than PID 1 and the killer itself, and
// exits 0 only when verified zero matching processes remain.
// 3. `<timeout_ms> -- <argv...>`: executes argv directly (zero shell
// interpolation) in its own process group, enforcing timeout_ms (SIGTERM ->
// 5s -> SIGKILL, exit 124).
package main
import (
"errors"
"fmt"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
)
func main() {
os.Exit(run())
}
func run() int {
if len(os.Args) == 2 && os.Args[1] == "--init" {
return runInit()
}
if len(os.Args) == 3 && os.Args[1] == "--kill-uid" {
uid, err := strconv.Atoi(strings.TrimSpace(os.Args[2]))
if err != nil || uid <= 0 {
fmt.Fprintln(os.Stderr, "usage: artex-exec-wrap --kill-uid <uid>")
return 2
}
return killUID(uid)
}
if len(os.Args) < 4 || os.Args[2] != "--" {
fmt.Fprintln(os.Stderr, "usage: artex-exec-wrap <timeout_ms> -- <argv...>")
return 2
}
timeoutMS, err := strconv.Atoi(os.Args[1])
if err != nil || timeoutMS <= 0 {
timeoutMS = 600000
}
argv := os.Args[3:]
cmd := exec.Command(argv[0], argv[1:]...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if err := cmd.Start(); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
return 127
}
pgid := cmd.Process.Pid
waitCh := make(chan error, 1)
go func() { waitCh <- cmd.Wait() }()
sigCh := make(chan os.Signal, 2)
signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT)
defer signal.Stop(sigCh)
timer := time.NewTimer(time.Duration(timeoutMS) * time.Millisecond)
defer timer.Stop()
select {
case err := <-waitCh:
return exitCodeFrom(err)
case <-timer.C:
terminateGroup(pgid, waitCh, 5*time.Second)
return 124
case <-sigCh:
terminateGroup(pgid, waitCh, 5*time.Second)
return 143
}
}
// runInit runs as PID 1 inside the worker container, reaping any orphaned
// children via Wait4(-1, WNOHANG) so zombies never accumulate or block Kill().
func runInit() int {
chldCh := make(chan os.Signal, 16)
termCh := make(chan os.Signal, 2)
signal.Notify(chldCh, syscall.SIGCHLD)
signal.Notify(termCh, syscall.SIGTERM, syscall.SIGINT)
defer signal.Stop(chldCh)
defer signal.Stop(termCh)
reap := func() {
for {
var ws syscall.WaitStatus
pid, err := syscall.Wait4(-1, &ws, syscall.WNOHANG, nil)
if pid <= 0 || err != nil {
break
}
}
}
ticker := time.NewTicker(250 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-chldCh:
reap()
case <-ticker.C:
reap()
case <-termCh:
reap()
return 0
}
}
}
func terminateGroup(pgid int, waitCh <-chan error, grace time.Duration) {
_ = syscall.Kill(-pgid, syscall.SIGTERM)
select {
case <-waitCh:
return
case <-time.After(grace):
_ = syscall.Kill(-pgid, syscall.SIGKILL)
<-waitCh
}
}
// killUID scans /proc directly (never reading any agent-writable state) and
// terminates every non-zombie process belonging to targetUID except PID 1 and
// os.Getpid(). Sends SIGTERM, polls up to 2s, then loops SIGKILL until verified
// zero matching processes remain (exits 1 if any survive).
func killUID(targetUID int) int {
self := os.Getpid()
selfPGID := syscall.Getpgrp()
pids := findProcessesByUID(targetUID, self)
if len(pids) == 0 {
return 0
}
for _, pid := range pids {
if pgid, err := syscall.Getpgid(pid); err == nil && pgid > 1 && pgid != selfPGID {
_ = syscall.Kill(-pgid, syscall.SIGTERM)
}
_ = syscall.Kill(pid, syscall.SIGTERM)
}
// Poll up to 2s so cooperative processes exit cleanly while hostile trap '' TERM
// daemons still get SIGKILLed and verified dead well within the 5s SLA.
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if len(findProcessesByUID(targetUID, self)) == 0 {
return 0
}
time.Sleep(25 * time.Millisecond)
}
// Escalate to SIGKILL in rounds to defeat fork/respawn loops.
for round := 0; round < 20; round++ {
rem := findProcessesByUID(targetUID, self)
if len(rem) == 0 {
return 0
}
for _, pid := range rem {
if pgid, err := syscall.Getpgid(pid); err == nil && pgid > 1 && pgid != selfPGID {
_ = syscall.Kill(-pgid, syscall.SIGKILL)
}
_ = syscall.Kill(pid, syscall.SIGKILL)
}
time.Sleep(30 * time.Millisecond)
}
if rem := findProcessesByUID(targetUID, self); len(rem) > 0 {
fmt.Fprintf(os.Stderr, "kill-uid %d: surviving pids=%v\n", targetUID, rem)
return 1
}
return 0
}
// findProcessesByUID returns all non-zombie PIDs (excluding PID 1 and excludePID)
// whose /proc/<pid>/status Uid line contains targetUID.
func findProcessesByUID(targetUID, excludePID int) []int {
entries, err := os.ReadDir("/proc")
if err != nil {
return nil
}
var out []int
for _, e := range entries {
if !e.IsDir() {
continue
}
name := e.Name()
if len(name) == 0 || name[0] < '0' || name[0] > '9' {
continue
}
pid, err := strconv.Atoi(name)
if err != nil || pid <= 1 || pid == excludePID {
continue
}
statRaw, err := os.ReadFile(filepath.Join("/proc", name, "stat"))
if err != nil {
continue
}
s := string(statRaw)
rparen := strings.LastIndexByte(s, ')')
if rparen < 0 || rparen+2 >= len(s) {
continue
}
fields := strings.Fields(s[rparen+2:])
if len(fields) == 0 || fields[0] == "Z" || fields[0] == "X" {
continue
}
statusRaw, err := os.ReadFile(filepath.Join("/proc", name, "status"))
if err != nil {
continue
}
matched := false
for _, line := range strings.Split(string(statusRaw), "\n") {
if strings.HasPrefix(line, "Uid:") {
for _, uf := range strings.Fields(line[4:]) {
if u, err := strconv.Atoi(uf); err == nil && u == targetUID {
matched = true
break
}
}
break
}
}
if matched {
out = append(out, pid)
}
}
return out
}
func exitCodeFrom(err error) int {
if err == nil {
return 0
}
var ee *exec.ExitError
if errors.As(err, &ee) {
return ee.ExitCode()
}
return 1
}