73 lines
1.8 KiB
Go
73 lines
1.8 KiB
Go
//go:build linux
|
|
|
|
package isolation
|
|
|
|
import (
|
|
"context"
|
|
"os/exec"
|
|
"os/user"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
)
|
|
|
|
func runScheduledIdentity(ctx context.Context, identity, binary string, args []string, cwd string, env map[string]string) (ScheduleOutput, error) {
|
|
account, e := user.Lookup(identity)
|
|
if e != nil {
|
|
return ScheduleOutput{}, e
|
|
}
|
|
uid, e := strconv.ParseUint(account.Uid, 10, 32)
|
|
if e != nil || uid == 0 {
|
|
return ScheduleOutput{}, syscall.EPERM
|
|
}
|
|
gid, e := strconv.ParseUint(account.Gid, 10, 32)
|
|
if e != nil || gid == 0 {
|
|
return ScheduleOutput{}, syscall.EPERM
|
|
}
|
|
cmd := exec.CommandContext(ctx, binary, args...)
|
|
cmd.Dir = cwd
|
|
cmd.Env = []string{"PATH=" + filepath.Dir(binary) + ":/usr/bin:/bin", "HOME=/nonexistent", "LANG=C.UTF-8"}
|
|
for k, v := range env {
|
|
cmd.Env = append(cmd.Env, k+"="+v)
|
|
}
|
|
cmd.SysProcAttr = &syscall.SysProcAttr{Credential: &syscall.Credential{Uid: uint32(uid), Gid: uint32(gid), Groups: []uint32{uint32(gid)}}, Setpgid: true, Pdeathsig: syscall.SIGKILL}
|
|
cmd.Cancel = func() error {
|
|
if cmd.Process != nil {
|
|
return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
|
|
}
|
|
return nil
|
|
}
|
|
cmd.WaitDelay = 3 * time.Second
|
|
buffer := &scheduleBuffer{}
|
|
cmd.Stdout = buffer
|
|
cmd.Stderr = buffer
|
|
e = cmd.Run()
|
|
out := ScheduleOutput{Output: strings.ToValidUTF8(string(buffer.data), "�"), Truncated: buffer.truncated}
|
|
if e != nil {
|
|
out.ExitCode = 1
|
|
if exit, ok := e.(*exec.ExitError); ok {
|
|
out.ExitCode = exit.ExitCode()
|
|
} else {
|
|
return out, e
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
type scheduleBuffer struct {
|
|
data []byte
|
|
truncated bool
|
|
}
|
|
|
|
func (b *scheduleBuffer) Write(p []byte) (int, error) {
|
|
n := len(p)
|
|
if len(b.data)+n > 65536 {
|
|
b.truncated = true
|
|
p = p[:max(0, 65536-len(b.data))]
|
|
}
|
|
b.data = append(b.data, p...)
|
|
return n, nil
|
|
}
|