Files
ARTEX/server/execpriv_cache_unix.go
T

170 lines
5.4 KiB
Go

//go:build unix
package server
import (
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"io"
"io/fs"
"log"
"os"
"path/filepath"
"syscall"
)
// Bump the version when recursive permission migration rules change. This state
// is outside task archives and agent-writable workspaces. It records completed
// migrations, not a security audit of arbitrary files agents create afterwards.
const execPermissionCacheDir = ".exec-permissions-v1"
var errExecPermissionTreeChanged = errors.New("directory changed during permission migration")
type execPermissionCache struct {
root *os.Root
dataDir string
uid uint32
reused, migrated int
}
func openExecPermissionCache(dataDir string) (*execPermissionCache, error) {
data, err := os.OpenRoot(dataDir)
if err != nil {
return nil, err
}
defer data.Close()
info, err := data.Stat(".")
if err != nil {
return nil, err
}
st, ok := info.Sys().(*syscall.Stat_t)
if !ok || st.Uid != 0 || info.Mode().Perm()&0o022 != 0 {
// An executor able to replace the cache directory must not supply migration
// records. Keep the original full walk for such deployments; the isolation
// self-test still decides whether the server may start.
log.Printf("[exec] permission migration cache unavailable: data directory is not root-owned and write-protected; using full walk")
return nil, nil
}
if err := data.Mkdir(execPermissionCacheDir, 0o700); err != nil && !errors.Is(err, fs.ErrExist) {
return nil, err
}
// The checked parent is not writable by the executor, so it cannot swap this
// entry between Lstat and OpenRoot. Do not follow an existing cache symlink.
info, err = data.Lstat(execPermissionCacheDir)
if err != nil {
return nil, err
}
st, ok = info.Sys().(*syscall.Stat_t)
if !ok || !info.IsDir() || st.Uid != 0 || info.Mode().Perm() != 0o700 {
return nil, fmt.Errorf("%s must be a root-owned 0700 directory", execPermissionCacheDir)
}
root, err := data.OpenRoot(execPermissionCacheDir)
if err != nil {
return nil, err
}
return &execPermissionCache{root: root, dataDir: dataDir}, nil
}
// share checks only the directory itself on a warm start. Changed/replaced roots,
// a changed executor identity, missing/invalid records or a new policy version take
// the original no-follow recursive path. Direct additions/removals invalidate the
// directory mtime too. Restores bypass the cache entirely.
func (c *execPermissionCache) share(path string, gid int, migrate func() error) error {
if c == nil {
err := migrate()
if errors.Is(err, errExecPermissionTreeChanged) {
return nil // No completion record: retain the original best-effort walk.
}
return err
}
before, signature, err := execPermissionSignature(path)
if err != nil {
return err
}
if signature == "" { // Files and links immediately inside old task roots.
return migrate()
}
rel, err := filepath.Rel(c.dataDir, path)
if err != nil || !filepath.IsLocal(rel) {
return fmt.Errorf("permission migration path %s is outside %s", path, c.dataDir)
}
name := fmt.Sprintf("%x", sha256.Sum256([]byte(rel)))
if c.matches(name, fmt.Sprintf("%d %d\n%s", c.uid, gid, signature)) {
c.reused++
return nil
}
// Remove an obsolete record before starting: a failed or interrupted pass
// must never leave a completion record that could become valid again.
if err := c.root.Remove(name); err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
if err := migrate(); err != nil {
if errors.Is(err, errExecPermissionTreeChanged) {
return nil // An incomplete walk must not leave a completion record.
}
return err
}
after, signature, err := execPermissionSignature(path)
if err != nil {
return err
}
if signature == "" || !os.SameFile(before, after) {
return fmt.Errorf("permission migration directory changed: %s", path)
}
if !before.ModTime().Equal(after.ModTime()) {
// The walk may have missed entries added after ReadDir. Do not certify
// that newer directory snapshot; retry on the next start instead.
return nil
}
// Publish only a complete record, never write through a pre-existing name.
tmp := ".tmp-" + rand.Text()
f, err := c.root.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return err
}
defer c.root.Remove(tmp)
_, writeErr := io.WriteString(f, fmt.Sprintf("%d %d\n%s", c.uid, gid, signature))
syncErr := f.Sync()
closeErr := f.Close()
if err := errors.Join(writeErr, syncErr, closeErr); err != nil {
return err
}
if err := c.root.Rename(tmp, name); err != nil {
return err
}
c.migrated++
return nil
}
func execPermissionSignature(path string) (os.FileInfo, string, error) {
info, err := os.Lstat(path)
if err != nil || !info.IsDir() {
return info, "", err
}
st, ok := info.Sys().(*syscall.Stat_t)
if !ok {
return info, "", fmt.Errorf("no ownership information for %s", path)
}
return info, fmt.Sprintf("%d %d %d %d %o %d\n", st.Dev, st.Ino, st.Uid, st.Gid, info.Mode(), info.ModTime().UnixNano()), nil
}
func (c *execPermissionCache) matches(name, signature string) bool {
f, err := c.root.OpenFile(name, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0)
if err != nil {
return false
}
defer f.Close()
info, err := f.Stat()
if err != nil || !info.Mode().IsRegular() || info.Mode().Perm() != 0o600 {
return false
}
st, ok := info.Sys().(*syscall.Stat_t)
if !ok || st.Uid != 0 || st.Nlink != 1 {
return false
}
b, err := io.ReadAll(io.LimitReader(f, 512))
return err == nil && string(b) == signature
}