ARTEX/server/killswitch_unix.go
BaaRai c721a4b8e5 fix(server): keep the linux subreaper call out of the unix build
The v0.7.1 release failed in its darwin binaries job: killswitch_unix.go is
built for every unix target but calls syscall.SYS_PRCTL, which only exists on
Linux. The Linux CI never compiled another GOOS, so the tag passed CI and broke
the release build after the push.

Move the prctl call to killswitch_prctl_linux.go, keep a no-op for the other
unix targets, and add a cross-compile step to the go job so darwin and windows
break in CI instead of in the release.
2026-12-01 04:08:32 +01:00

213 lines
5.4 KiB
Go

//go:build unix
package server
import (
"errors"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"time"
)
type procEntry struct {
pid int
ppid int
pgrp int
stat string
uids []int
}
func readProcTable() []procEntry {
entries, err := os.ReadDir("/proc")
if err != nil {
return nil
}
out := make([]procEntry, 0, len(entries))
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 {
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) < 3 {
continue
}
ppid, err1 := strconv.Atoi(fields[1])
pgrp, err2 := strconv.Atoi(fields[2])
if err1 != nil || err2 != nil {
continue
}
pe := procEntry{pid: pid, ppid: ppid, pgrp: pgrp, stat: fields[0]}
if statusRaw, err := os.ReadFile(filepath.Join("/proc", name, "status")); err == nil {
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 {
pe.uids = append(pe.uids, u)
}
}
break
}
}
}
out = append(out, pe)
}
return out
}
func (p procEntry) isZombie() bool {
return p.stat == "Z" || p.stat == "X"
}
func (p procEntry) hasUID(uid int) bool {
for _, u := range p.uids {
if u == uid {
return true
}
}
return false
}
// reapDirectChildren is intentionally a no-op because Go's os/exec owns
// Wait4 on direct children; process liveness checks ignore Z/X zombie states.
func reapDirectChildren() {}
// findLocalTaskPIDs scans /proc without trusting any agent-writable state.
// When priv.Enabled (isolated executor UID), every non-zombie process owning
// priv.UID is returned (cannot be escaped via setsid, nohup, env -i, or double-fork).
// When !priv.Enabled (dev/test mode with PR_SET_CHILD_SUBREAPER), every descendant
// of os.Getpid() whose process group differs from os.Getpgrp() (covering Norma's
// Setpgid shells, setsid/nohup children, and reparented double-fork daemons) is returned.
func findLocalTaskPIDs(taskDir string, priv ExecPrivilege) []int {
self := os.Getpid()
selfPGID := syscall.Getpgrp()
procs := readProcTable()
if len(procs) == 0 {
return nil
}
if priv.Enabled && priv.UID > 0 {
var matched []int
for _, p := range procs {
if p.pid == self || p.isZombie() {
continue
}
if p.hasUID(int(priv.UID)) {
matched = append(matched, p.pid)
}
}
return matched
}
children := make(map[int][]procEntry, len(procs))
for _, p := range procs {
children[p.ppid] = append(children[p.ppid], p)
}
cleanTaskDir := ""
if strings.TrimSpace(taskDir) != "" {
if abs, err := filepath.Abs(taskDir); err == nil {
cleanTaskDir = abs
}
}
var matched []int
seen := map[int]bool{}
var walk func(parent int, inheritedMatch bool)
walk = func(parent int, inheritedMatch bool) {
for _, ch := range children[parent] {
if ch.pid == self || seen[ch.pid] {
continue
}
seen[ch.pid] = true
inTask := inheritedMatch || ch.pgrp != selfPGID
if !inTask && cleanTaskDir != "" {
if cwd, err := os.Readlink(filepath.Join("/proc", strconv.Itoa(ch.pid), "cwd")); err == nil {
if cwd == cleanTaskDir || strings.HasPrefix(cwd, cleanTaskDir+string(filepath.Separator)) {
inTask = true
}
}
}
if inTask && !ch.isZombie() {
matched = append(matched, ch.pid)
}
walk(ch.pid, inTask)
}
}
walk(self, false)
return matched
}
// KillLocalTaskProcesses terminates all live local processes belonging to a task
// (including setsid, nohup, and nested double-fork daemons) using /proc directly
// without trusting any agent-writable state. Sends SIGTERM, polls up to 2s, then
// loops SIGKILL until none remain (well within the 5s pause SLA).
func KillLocalTaskProcesses(taskDir string, priv ExecPrivilege) error {
if runtime.GOOS != "linux" {
return nil
}
selfPGID := syscall.Getpgrp()
// Sweep once immediately, and if nothing matched yet, wait briefly for
// cancelExec to trigger child reparenting before declaring clean.
pids := findLocalTaskPIDs(taskDir, priv)
if len(pids) == 0 {
time.Sleep(40 * time.Millisecond)
pids = findLocalTaskPIDs(taskDir, priv)
if len(pids) == 0 {
return nil
}
}
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)
}
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
reapDirectChildren()
if len(findLocalTaskPIDs(taskDir, priv)) == 0 {
return nil
}
time.Sleep(25 * time.Millisecond)
}
for round := 0; round < 15; round++ {
rem := findLocalTaskPIDs(taskDir, priv)
if len(rem) == 0 {
return nil
}
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)
reapDirectChildren()
}
if rem := findLocalTaskPIDs(taskDir, priv); len(rem) > 0 {
return errors.New("some local task processes survived SIGKILL")
}
return nil
}