//go:build linux package isolation import ( "context" "encoding/json" "fmt" "os" "os/exec" "os/user" "path/filepath" "sea-vhost/internal/hosting" "strconv" "strings" "syscall" ) // PID files are written by the unprivileged FPM master. Never send a root // signal to a PID taken from that file: a host could substitute another PID. func signalPHPAsIdentity(ctx context.Context, config, signal string, pid int) error { identity := "" name := strings.TrimSuffix(filepath.Base(config), ".conf") if phpSiteNamePattern.MatchString(name) { identity = strings.Split(name, "_")[0] } else if config == filepath.Join(pmaStateRoot, "php-fpm.conf") { identity = pmaIdentity } if identity == "" || pid < 2 || (signal != "0" && signal != "TERM") { return fmt.Errorf("invalid PHP signal identity") } out, e := runScheduledIdentity(ctx, identity, "/bin/kill", []string{"-" + signal, strconv.Itoa(pid)}, "/", nil) if e != nil { return e } if out.ExitCode != 0 { return fmt.Errorf("PHP process unavailable to its identity") } return nil } // startPHPAsIdentity changes credentials in the forked child before exec. // Linux clears the child's ambient capabilities when its UID changes from // root, so the PHP-FPM master and every worker run without agent privileges. func startPHPAsIdentity(ctx context.Context, binary, config, identity string) error { return runPHPAsIdentity(ctx, binary, identity, "--fpm-config", config) } func testPHPAsIdentity(ctx context.Context, binary, config, identity string) error { return runPHPAsIdentity(ctx, binary, identity, "-t", "--fpm-config", config) } func runPHPAsIdentity(ctx context.Context, binary, identity string, args ...string) error { account, err := user.Lookup(identity) if err != nil { return fmt.Errorf("lookup PHP identity: %w", err) } uid, err := strconv.ParseUint(account.Uid, 10, 32) if err != nil || uid == 0 { return fmt.Errorf("invalid PHP identity uid") } gid, err := strconv.ParseUint(account.Gid, 10, 32) if err != nil || gid == 0 { return fmt.Errorf("invalid PHP identity gid") } command := exec.CommandContext(ctx, binary, args...) command.Env = []string{"PATH=/usr/sbin:/usr/bin:/sbin:/bin", "LANG=C"} if len(args) > 0 { key := strings.TrimSuffix(filepath.Base(args[len(args)-1]), ".conf") if phpSiteNamePattern.MatchString(key) { if raw, e := os.ReadFile(filepath.Join(startupStateRoot, key+".json")); e == nil { var state hosting.RunnerConfig if json.Unmarshal(raw, &state) == nil && state.UID == uint32(uid) { for name, value := range state.Environment { command.Env = append(command.Env, name+"="+value) } } } } } command.SysProcAttr = &syscall.SysProcAttr{Credential: &syscall.Credential{ Uid: uint32(uid), Gid: uint32(gid), Groups: []uint32{uint32(gid)}, }} output, err := command.CombinedOutput() if err != nil { return fmt.Errorf("run PHP-FPM as isolated identity: %w: %s", err, strings.TrimSpace(string(output))) } return nil }