Files
Kelx/pathsafe.go
2026-11-30 16:32:37 +00:00

977 lines
36 KiB
Go

//go:build linux
package main
// adpanel:fs-toctou - structural containment for the files API.
//
// The /v1/fs/* and /v1/servers/:name/files/* handlers used to validate a path
// (Lstat + ensureResolvedUnder) and then open the same string by name. Those
// are two independent walks of the path: a tenant process can swap an
// intermediate directory for a cross-server symlink between the check and the
// open and win the race to read/write/delete outside its server root as the
// daemon user (O_NOFOLLOW only protects the final path component).
//
// The helpers below pin the per-server root with a directory fd once per
// request and perform every subsequent open/stat/delete/rename RELATIVE to
// that fd via openat2(RESOLVE_BENEATH), so every path component - symlinks
// included - is constrained beneath the root by the kernel at open time.
// In-root symlinks keep working (they resolve beneath the dirfd); escapes
// fail before any byte moves. ensureResolvedUnder pre-checks in the handlers
// remain for friendly error messages but are no longer the boundary.
//
// On kernels without openat2 (< 5.6), when the syscall is seccomp-blocked, or
// when RESOLVE_BENEATH rejects an absolute in-root symlink (EAGAIN) that the
// legacy ensureResolvedUnder path would have accepted, the helpers fall back
// to the pre-existing validate-then-open-by-name path - identical to the old
// behavior, never worse.
import (
"bufio"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"sync/atomic"
"syscall"
"time"
"golang.org/x/sys/unix"
)
// safePathOpenat2Calls / safePathFallbackCalls count how many safeOpenAt
// calls resolved through openat2 versus the legacy validation path. They
// exist so tests can prove the kernel-enforced path is exercised.
var (
safePathOpenat2Calls atomic.Int64
safePathFallbackCalls atomic.Int64
)
// safePathForceFallback forces the legacy validate-then-open path (tests).
var safePathForceFallback atomic.Bool
// errSafeScopeEscape is wrapped by helpers that refuse to traverse or create
// through a path component leaving the pinned root (a planted intermediate
// symlink or traversal). Callers map it onto their existing user-facing
// messages with errors.Is; the refusal itself is the boundary.
var errSafeScopeEscape = errors.New("symlink escape blocked")
// safeRoot is a server scope root pinned by directory fd for the lifetime of
// one request. Every files-API operation for the request is resolved relative
// to this fd, so intermediate components cannot be swapped out from under the
// validated path between the check and the open.
type safeRoot struct {
file *os.File
path string // cleaned absolute root path, used by the legacy validation path
}
// safeOpenRoot pins rootPath with an O_RDONLY|O_DIRECTORY fd.
func safeOpenRoot(rootPath string) (*safeRoot, error) {
c := filepath.Clean(rootPath)
fd, err := unix.Open(c, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
if err != nil {
return nil, &os.PathError{Op: "safe-open-root", Path: c, Err: err}
}
return &safeRoot{file: os.NewFile(uintptr(fd), c), path: c}, nil
}
// Close releases the pinned root fd.
func (sr *safeRoot) Close() error {
if sr == nil || sr.file == nil {
return nil
}
return sr.file.Close()
}
// safeRelUnderRoot validates that rel is a usable relative path for openat(2)
// and returns it cleaned. "." is allowed and addresses the root itself.
func safeRelUnderRoot(rel string) (string, error) {
if rel == "" {
return "", fmt.Errorf("empty relative path")
}
c := filepath.Clean(rel)
if filepath.IsAbs(c) || c == ".." || strings.HasPrefix(c, ".."+string(os.PathSeparator)) {
return "", fmt.Errorf("invalid relative path %q", rel)
}
return c, nil
}
// validSafeChildName reports whether name is a single path component suitable
// for the raw *at() helpers (unlinkat/renameat/fstatat).
func validSafeChildName(name string) bool {
return name != "" && name != "." && name != ".." && !strings.ContainsRune(name, '/')
}
// safeOpenAt opens rel beneath the pinned root. openFlags uses the standard
// os.O_* / syscall.O_* bits (numerically identical to the unix package values
// on Linux) and is passed straight through to openat2, so O_NOFOLLOW keeps
// protecting the final component exactly like the by-name openers it replaces.
func safeOpenAt(root *safeRoot, rel string, openFlags int, perm os.FileMode) (*os.File, error) {
cleanRel, err := safeRelUnderRoot(rel)
if err != nil {
return nil, err
}
if !safePathForceFallback.Load() {
f, openErr := safeOpenAtOpenat2(root, cleanRel, openFlags, perm)
if openErr == nil {
return f, nil
}
if !safePathFallbackEligible(openErr) {
return nil, openErr
}
}
safePathFallbackCalls.Add(1)
return safeOpenAtLegacy(root, cleanRel, openFlags, perm)
}
// safeOpenDirAt opens rel as a directory beneath the pinned root.
func safeOpenDirAt(root *safeRoot, rel string) (*os.File, error) {
return safeOpenAt(root, rel, os.O_RDONLY|unix.O_DIRECTORY, 0)
}
// safeOpenAtOpenat2 is the kernel-enforced path: openat2(2) with
// RESOLVE_BENEATH resolves every component beneath the root's dirfd.
func safeOpenAtOpenat2(root *safeRoot, rel string, openFlags int, perm os.FileMode) (*os.File, error) {
how := unix.OpenHow{
Flags: uint64(openFlags) | unix.O_CLOEXEC,
Resolve: unix.RESOLVE_BENEATH,
}
// Like open(2), the mode is only meaningful with O_CREAT; passing it
// unconditionally would risk EINVAL on strict kernels.
if openFlags&os.O_CREATE != 0 {
how.Mode = uint64(perm.Perm())
}
fd, err := unix.Openat2(int(root.file.Fd()), rel, &how)
safePathOpenat2Calls.Add(1)
if err != nil {
return nil, &os.PathError{Op: "openat2", Path: filepath.Join(root.path, rel), Err: err}
}
return os.NewFile(uintptr(fd), filepath.Join(root.path, rel)), nil
}
// safePathFallbackEligible reports whether an openat2 failure should be
// retried through the legacy validation path: unsupported syscall (ENOSYS),
// rejected flag/resolve combination (EINVAL), a detected escape or absolute
// symlink (EAGAIN/EXDEV under RESOLVE_BENEATH), or a seccomp-blocked call
// (EPERM). Ordinary per-path failures (ENOENT, ELOOP, EISDIR, ...) are
// returned as-is so handler error shapes stay byte-identical.
func safePathFallbackEligible(err error) bool {
return errors.Is(err, unix.ENOSYS) ||
errors.Is(err, unix.EINVAL) ||
errors.Is(err, unix.EAGAIN) ||
errors.Is(err, unix.EXDEV) ||
errors.Is(err, unix.EPERM)
}
// safeOpenAtLegacy is the pre-existing validation path (EvalSymlinks +
// ensureResolvedUnder followed by a by-name open), kept for kernels without
// openat2 and for absolute in-root symlinks that RESOLVE_BENEATH rejects.
func safeOpenAtLegacy(root *safeRoot, rel string, openFlags int, perm os.FileMode) (*os.File, error) {
abs := filepath.Join(root.path, rel)
if openFlags&os.O_CREATE != 0 {
// The final component may not exist yet, so validate the parent chain
// exactly like the legacy write paths did; O_NOFOLLOW (when requested)
// still protects the final component.
if err := ensureResolvedUnder(root.path, filepath.Dir(abs)); err != nil {
return nil, err
}
} else if err := ensureResolvedUnder(root.path, abs); err != nil {
return nil, err
}
return os.OpenFile(abs, openFlags, perm)
}
// errSafeNotRegular is returned by safeOpenRegularAt when the opened inode is
// not a regular file (a FIFO, device or socket planted in the server root).
// Callers map it onto their existing "not a regular file" responses with
// errors.Is; the refusal is the boundary.
var errSafeNotRegular = errors.New("not a regular file")
// safeOpenRegularAt opens rel beneath the pinned root and guarantees the
// returned fd refers to a regular file before any I/O happens on it - the
// read/download counterpart of safeOpenAt. O_NONBLOCK is added to the open
// flags so a FIFO planted in the server root cannot wedge the caller inside
// open(2) (O_RDONLY on a FIFO otherwise blocks until a writer appears); the
// fd is then fstat'ed and anything that is not a regular file is rejected
// with errSafeNotRegular, and O_NONBLOCK is cleared before returning so I/O
// on the regular file keeps its normal blocking semantics. The explicit
// unix.SetNonblock(fd, false) is the sole clearing mechanism on BOTH the
// openat2 and legacy paths - os.NewFile fds must not be relied on to reset
// the flag via Fd() on current Go. The flag rides through safeOpenAt, so
// the legacy fallback path gets the same O_NONBLOCK open + fstat re-check.
func safeOpenRegularAt(root *safeRoot, rel string, openFlags int, perm os.FileMode) (*os.File, os.FileInfo, error) {
cleanRel, err := safeRelUnderRoot(rel)
if err != nil {
return nil, nil, err
}
f, err := safeOpenAt(root, cleanRel, openFlags|unix.O_NONBLOCK, perm)
if err != nil {
return nil, nil, err
}
st, err := f.Stat()
if err != nil {
f.Close()
return nil, nil, err
}
if !st.Mode().IsRegular() {
f.Close()
return nil, nil, fmt.Errorf("%w: %s", errSafeNotRegular, filepath.Join(root.path, rel))
}
if err := unix.SetNonblock(int(f.Fd()), false); err != nil {
f.Close()
return nil, nil, err
}
return f, st, nil
}
// safeWriteAt writes data to rel beneath the pinned root without following a
// symlink in the final component - the fd-based equivalent of
// openWriteNoFollowMode/writeFileNoFollow. Callers choose the exact flag set
// (create / create-exclusive / update) to preserve handleFSWrite's modes.
// Like safeOpenRegularAt, the open rides with O_NONBLOCK and the opened fd is
// fstat'ed so a FIFO planted at the target cannot wedge the write inside
// open(2): non-regular targets are rejected with errSafeNotRegular (callers
// map it onto their existing write-failure shapes) and O_NONBLOCK is cleared
// so regular-file writes keep their blocking semantics.
func safeWriteAt(root *safeRoot, rel string, openFlags int, perm os.FileMode, data []byte) error {
f, err := safeOpenAt(root, rel, openFlags|unix.O_NONBLOCK, perm)
if err != nil {
if errors.Is(err, syscall.ELOOP) {
return fmt.Errorf("refusing to write through symlink: %s", filepath.Join(root.path, rel))
}
return err
}
st, statErr := f.Stat()
if statErr != nil {
f.Close()
return statErr
}
if !st.Mode().IsRegular() {
f.Close()
return fmt.Errorf("%w: %s", errSafeNotRegular, filepath.Join(root.path, rel))
}
if err := unix.SetNonblock(int(f.Fd()), false); err != nil {
f.Close()
return err
}
_, werr := f.Write(data)
cerr := f.Close()
if werr != nil {
return werr
}
return cerr
}
// safeOpenWriteAt opens rel beneath the pinned root with the caller's write
// flags and the same FIFO-wedge discipline as safeOpenRegularAt: O_NONBLOCK so
// a FIFO planted at the target cannot wedge open(2) (O_WRONLY on a FIFO
// otherwise blocks until a reader appears), an fstat gate rejecting
// non-regular targets with errSafeNotRegular, and O_NONBLOCK cleared before
// returning so streamed writes keep their blocking semantics. O_NOFOLLOW (when
// requested) keeps protecting the final component through safeOpenAt. It is
// the streaming counterpart of safeWriteAt for extractors that io.Copy into
// the opened fd.
func safeOpenWriteAt(root *safeRoot, rel string, openFlags int, perm os.FileMode) (*os.File, error) {
f, err := safeOpenAt(root, rel, openFlags|unix.O_NONBLOCK, perm)
if err != nil {
return nil, err
}
st, statErr := f.Stat()
if statErr != nil {
f.Close()
return nil, statErr
}
if !st.Mode().IsRegular() {
f.Close()
return nil, fmt.Errorf("%w: %s", errSafeNotRegular, filepath.Join(root.path, rel))
}
if err := unix.SetNonblock(int(f.Fd()), false); err != nil {
f.Close()
return nil, err
}
return f, nil
}
// readDirEntriesBounded in main.go is the listing reader the /v1/fs/list and
// files-list handlers use; it produces the name-sorted order this helper's
// full ReadDir used to, with the entry count bounded.
// statFileInfo adapts a unix.Stat_t obtained via fstatat to os.FileInfo so
// callers can treat it exactly like the os.Lstat results they replace.
type statFileInfo struct {
name string
st unix.Stat_t
}
func (s statFileInfo) Name() string { return s.name }
func (s statFileInfo) Size() int64 { return int64(s.st.Size) }
func (s statFileInfo) Mode() os.FileMode { return fileModeFromUnixMode(s.st.Mode) }
func (s statFileInfo) ModTime() time.Time { return time.Unix(s.st.Mtim.Sec, s.st.Mtim.Nsec) }
func (s statFileInfo) IsDir() bool { return s.st.Mode&unix.S_IFMT == unix.S_IFDIR }
func (s statFileInfo) Sys() any { return &s.st }
// fileModeFromUnixMode mirrors os.fileModeFromSys for a raw unix mode word.
func fileModeFromUnixMode(m uint32) os.FileMode {
fm := os.FileMode(m & 0o777)
switch m & unix.S_IFMT {
case unix.S_IFBLK:
fm |= os.ModeDevice
case unix.S_IFCHR:
fm |= os.ModeDevice | os.ModeCharDevice
case unix.S_IFDIR:
fm |= os.ModeDir
case unix.S_IFIFO:
fm |= os.ModeNamedPipe
case unix.S_IFLNK:
fm |= os.ModeSymlink
case unix.S_IFSOCK:
fm |= os.ModeSocket
}
if m&unix.S_ISGID != 0 {
fm |= os.ModeSetgid
}
if m&unix.S_ISUID != 0 {
fm |= os.ModeSetuid
}
if m&unix.S_ISVTX != 0 {
fm |= os.ModeSticky
}
return fm
}
// safeStatAt is the fd-based equivalent of os.Lstat for a child of a pinned
// directory fd: AT_SYMLINK_NOFOLLOW means the final component is never
// followed, and the walk to it never leaves the pinned tree.
func safeStatAt(dir *os.File, name string) (fs.FileInfo, error) {
if !validSafeChildName(name) {
return nil, fmt.Errorf("invalid child name %q", name)
}
var st unix.Stat_t
if err := unix.Fstatat(int(dir.Fd()), name, &st, unix.AT_SYMLINK_NOFOLLOW); err != nil {
return nil, &os.PathError{Op: "fstatat", Path: filepath.Join(dir.Name(), name), Err: err}
}
return statFileInfo{name: name, st: st}, nil
}
// safeRemoveAt removes name relative to the pinned parent fd - the fd-based
// equivalent of os.Remove: unlink first, rmdir on EISDIR. A missing target
// surfaces as ENOENT for the caller to shape.
func safeRemoveAt(parent *os.File, name string) error {
if !validSafeChildName(name) {
return fmt.Errorf("invalid child name %q", name)
}
if err := unix.Unlinkat(int(parent.Fd()), name, 0); err != nil {
if errors.Is(err, unix.EISDIR) {
return unix.Unlinkat(int(parent.Fd()), name, unix.AT_REMOVEDIR)
}
return err
}
return nil
}
// safeDeleteUnderRoot removes the file or tree at rel beneath the pinned root
// - the fd-based equivalent of os.Remove (isDir=false) or os.RemoveAll
// (isDir=true). rel == "." (the server root itself) is REFUSED: removing the
// root would delete the whole server directory, which is reserved for the
// dedicated admin server-delete/reinstall flows, never the files API. The
// /v1/fs handlers refuse it earlier with a friendly 400; this is the boundary
// behind them, so no current or future caller can turn this helper into a
// whole-server destroy.
func safeDeleteUnderRoot(root *safeRoot, rel string, isDir bool) error {
cleanRel, err := safeRelUnderRoot(rel)
if err != nil {
return err
}
if cleanRel == "." {
return fmt.Errorf("refusing to delete server root")
}
parentFd, err := safeOpenDirAt(root, filepath.Dir(cleanRel))
if err != nil {
return err
}
defer parentFd.Close()
return removeUnderPinned(parentFd, filepath.Base(cleanRel), isDir)
}
// removeUnderPinned removes name beneath an already-pinned parent fd. Trees
// are walked with fds opened O_NOFOLLOW from the pinned parent, so a symlink
// planted anywhere inside the tree is removed as a link and never traversed -
// matching os.RemoveAll semantics without its by-name re-walks.
func removeUnderPinned(parentFd *os.File, name string, isDir bool) error {
if isDir {
return safeRemoveAllAtFd(int(parentFd.Fd()), name)
}
return safeRemoveAt(parentFd, name)
}
// safeRemoveAllAtFd removes name (file, symlink or directory tree) relative to
// the raw parent fd, mirroring os.RemoveAll: a missing target is success.
func safeRemoveAllAtFd(dirFd int, name string) error {
if !validSafeChildName(name) {
return fmt.Errorf("invalid child name %q", name)
}
var st unix.Stat_t
if err := unix.Fstatat(dirFd, name, &st, unix.AT_SYMLINK_NOFOLLOW); err != nil {
if errors.Is(err, unix.ENOENT) {
return nil // os.RemoveAll ignores missing targets
}
return err
}
if st.Mode&unix.S_IFMT == unix.S_IFDIR {
childFd, err := unix.Openat(dirFd, name, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
if err == nil {
rmErr := safeRemoveChildrenFd(childFd)
unix.Close(childFd)
if rmErr != nil {
return rmErr
}
return unix.Unlinkat(dirFd, name, unix.AT_REMOVEDIR)
}
if !errors.Is(err, unix.ELOOP) && !errors.Is(err, unix.ENOTDIR) {
return err
}
// The child turned into a symlink (or non-directory) between the
// Fstatat and the open: unlink the link itself, exactly like
// os.RemoveAll would.
}
return unix.Unlinkat(dirFd, name, 0)
}
// safeRemoveChildrenFd removes every entry of the pinned directory fd.
func safeRemoveChildrenFd(dirFd int) error {
buf := make([]byte, 32*1024)
for {
n, err := syscall.ReadDirent(dirFd, buf)
if err != nil {
return err
}
if n == 0 {
return nil
}
_, _, names := unix.ParseDirent(buf[:n], -1, nil) // skips "." and ".."
for _, name := range names {
if err := safeRemoveAllAtFd(dirFd, name); err != nil {
return err
}
}
}
}
// safeRenameUnderRoot renames oldRel to newName within oldRel's parent
// directory, both sides pinned to the same dirfd (fd-based equivalent of
// os.Rename for same-parent renames, which is the only rename the files API
// performs). newName must be a single path component.
func safeRenameUnderRoot(root *safeRoot, oldRel, newName string) error {
cleanRel, err := safeRelUnderRoot(oldRel)
if err != nil {
return err
}
if cleanRel == "." {
return fmt.Errorf("cannot rename the server root")
}
if !validSafeChildName(newName) {
return fmt.Errorf("invalid rename target %q", newName)
}
parentFd, err := safeOpenDirAt(root, filepath.Dir(cleanRel))
if err != nil {
return err
}
defer parentFd.Close()
return unix.Renameat2(int(parentFd.Fd()), filepath.Base(cleanRel), int(parentFd.Fd()), newName, 0)
}
// errSafeDestExists is returned by safeRenameNoReplaceUnderRoot when the
// destination name already exists. Callers map it onto their user-facing
// "conflict" responses with errors.Is; the refusal is the boundary.
var errSafeDestExists = errors.New("destination already exists")
// safeRenameNoReplaceUnderRoot renames oldRel to newName within oldRel's
// parent directory, REFUSING to replace an existing destination - the
// /v1/fs/rename counterpart of safeRenameUnderRoot (which keeps plain
// overwrite semantics for the internal temp-file finalization flows that
// legitimately replace their own targets). RENAME_NOREPLACE makes the
// existence check and the move one atomic syscall; on kernels without the
// renameat2 flags (ENOSYS) or filesystems that reject them
// (EINVAL/EOPNOTSUPP) it falls back to an explicit destination-lstat check
// followed by a plain rename. That fallback leaves a small residual TOCTOU
// window (a destination created between the lstat and the rename is still
// replaced) - accepted, because the panel pre-checks the destination and
// the rename itself stays contained beneath the pinned dirfd either way.
func safeRenameNoReplaceUnderRoot(root *safeRoot, oldRel, newName string) error {
return renameNoReplaceUnderRoot(root, oldRel, newName, false)
}
func renameNoReplaceUnderRoot(root *safeRoot, oldRel, newName string, requireAtomic bool) error {
cleanRel, err := safeRelUnderRoot(oldRel)
if err != nil {
return err
}
if cleanRel == "." {
return fmt.Errorf("cannot rename the server root")
}
if !validSafeChildName(newName) {
return fmt.Errorf("invalid rename target %q", newName)
}
// A self-rename (newName == the source's own basename) is a POSIX
// rename(x,x) no-op; RENAME_NOREPLACE would false-positive EEXIST on the
// source itself, so short-circuit before the syscall. Same file, same
// dir: nothing else in this function needs the syscall to have run.
if newName == filepath.Base(cleanRel) {
return nil
}
parentFd, err := safeOpenDirAt(root, filepath.Dir(cleanRel))
if err != nil {
return err
}
defer parentFd.Close()
oldName := filepath.Base(cleanRel)
if err := unix.Renameat2(int(parentFd.Fd()), oldName, int(parentFd.Fd()), newName, unix.RENAME_NOREPLACE); err != nil {
if errors.Is(err, unix.EEXIST) {
return fmt.Errorf("%w: %s", errSafeDestExists, newName)
}
if !requireAtomic && (errors.Is(err, unix.ENOSYS) || errors.Is(err, unix.EINVAL) || errors.Is(err, unix.EOPNOTSUPP)) {
return renameNoReplaceFallback(parentFd, oldName, newName)
}
return err
}
return nil
}
// safeRenameFileAcrossDirsNoReplace renames oldName (a child of oldDir) to
// newName (a child of newDir) with both parent fds already pinned, REFUSING to
// replace an existing destination - the cross-directory counterpart of
// safeRenameNoReplaceUnderRoot, serving the extract no-clobber mode
// (adpanel:extract-no-clobber): external-tool extraction can only touch the
// destination at the post-extraction move, so the refusal has to happen at
// that rename. RENAME_NOREPLACE makes the existence check and the move one
// atomic syscall (a symlink at the destination is replaced by nothing: the
// rename does not follow it); on kernels without the renameat2 flags (ENOSYS)
// or filesystems that reject them (EINVAL/EOPNOTSUPP) it falls back to an
// explicit destination-fstatat check followed by a plain renameat. That
// fallback leaves a small residual TOCTOU window (a destination created
// between the check and the rename is still replaced) - accepted, mirroring
// renameNoReplaceFallback: the move itself stays contained beneath the pinned
// dirfds either way. A missing source surfaces as the raw ENOENT.
func safeRenameFileAcrossDirsNoReplace(oldDir, newDir *os.File, oldName, newName string) error {
if !validSafeChildName(oldName) {
return fmt.Errorf("invalid rename source %q", oldName)
}
if !validSafeChildName(newName) {
return fmt.Errorf("invalid rename target %q", newName)
}
if err := unix.Renameat2(int(oldDir.Fd()), oldName, int(newDir.Fd()), newName, unix.RENAME_NOREPLACE); err != nil {
if errors.Is(err, unix.EEXIST) {
return fmt.Errorf("%w: %s", errSafeDestExists, newName)
}
if errors.Is(err, unix.ENOSYS) || errors.Is(err, unix.EINVAL) || errors.Is(err, unix.EOPNOTSUPP) {
if _, statErr := safeStatAt(newDir, newName); statErr == nil {
return fmt.Errorf("%w: %s", errSafeDestExists, newName)
} else if !errors.Is(statErr, unix.ENOENT) {
return statErr
}
return unix.Renameat(int(oldDir.Fd()), oldName, int(newDir.Fd()), newName)
}
return err
}
return nil
}
// renameNoReplaceFallback backs safeRenameNoReplaceUnderRoot on
// kernels/filesystems without renameat2 flag support: lstat the destination,
// then plain-rename. Not atomic (the documented residual TOCTOU). A missing
// source surfaces as the raw ENOENT for the handler to shape (404).
func renameNoReplaceFallback(parentFd *os.File, oldName, newName string) error {
if _, statErr := safeStatAt(parentFd, newName); statErr == nil {
return fmt.Errorf("%w: %s", errSafeDestExists, newName)
} else if !errors.Is(statErr, unix.ENOENT) {
return statErr
}
return unix.Renameat2(int(parentFd.Fd()), oldName, int(parentFd.Fd()), newName, 0)
}
// safeRenameFileAcrossDirs renames oldName (a child of oldDir) to newName (a
// child of newDir) with both parent fds already pinned. renameat(2) resolves
// both sides relative to the dirfds, so no by-name walk happens between the
// callers' checks and the move: a swap of either parent path cannot redirect
// the rename outside the pinned tree, which the extract-move path's
// "os.Rename by absolute name" left open.
func safeRenameFileAcrossDirs(oldDir, newDir *os.File, oldName, newName string) error {
if !validSafeChildName(oldName) {
return fmt.Errorf("invalid rename source %q", oldName)
}
if !validSafeChildName(newName) {
return fmt.Errorf("invalid rename target %q", newName)
}
if err := unix.Renameat(int(oldDir.Fd()), oldName, int(newDir.Fd()), newName); err != nil {
return &os.PathError{Op: "renameat", Path: filepath.Join(oldDir.Name(), oldName), Err: err}
}
return nil
}
// adpanel:restore-commit — no fallback may unlink any part of the live tree.
func swapStagedRestore(stagingDir, serverDir string) error {
parentPath := filepath.Dir(serverDir)
if parentPath != filepath.Dir(stagingDir) {
return errors.New("staged restore must be a sibling of the server directory")
}
parent, err := safeOpenRoot(parentPath)
if err != nil {
return err
}
defer parent.Close()
serverName, stageName := filepath.Base(serverDir), filepath.Base(stagingDir)
current, currentInfo, err := safeOpenChildNoFollow(parent.file, serverName)
if err != nil {
return err
}
defer current.Close()
staged, stagedInfo, err := safeOpenChildNoFollow(parent.file, stageName)
if err != nil {
return err
}
defer staged.Close()
if !currentInfo.IsDir() || !stagedInfo.IsDir() || os.SameFile(currentInfo, stagedInfo) {
return errors.New("staged restore and server data must be distinct directories")
}
if err := rejectRestoreMounts(serverDir); err != nil {
return err
}
stageDirectory, err := safeOpenPinnedDirReader(staged)
if err != nil {
return err
}
defer stageDirectory.Close()
var currentStat, stagedStat unix.Stat_t
if err := unix.Fstat(int(current.Fd()), &currentStat); err != nil {
return err
}
if err := unix.Fstat(int(staged.Fd()), &stagedStat); err != nil {
return err
}
if currentStat.Uid != stagedStat.Uid || currentStat.Gid != stagedStat.Gid {
if err := stageDirectory.Chown(int(currentStat.Uid), int(currentStat.Gid)); err != nil {
return err
}
}
if err := stageDirectory.Chmod(currentInfo.Mode()); err != nil {
return err
}
parentFD := int(parent.file.Fd())
return unix.Renameat2(parentFD, stageName, parentFD, serverName, unix.RENAME_EXCHANGE)
}
// Refuse nested and same-device bind mounts before cleaning the previous tree.
func rejectRestoreMounts(serverDir string) error {
root, err := filepath.EvalSymlinks(serverDir)
if err != nil {
return err
}
mounts, err := os.Open("/proc/self/mountinfo")
if err != nil {
return err
}
defer mounts.Close()
unescape := strings.NewReplacer(`\040`, " ", `\011`, "\t", `\012`, "\n", `\134`, `\`)
scanner := bufio.NewScanner(mounts)
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) < 6 {
return errors.New("could not verify mounts for backup restore")
}
mountPath := unescape.Replace(fields[4])
if mountPath == root || strings.HasPrefix(mountPath, root+string(os.PathSeparator)) {
return fmt.Errorf("server directory contains mount %s", mountPath)
}
}
return scanner.Err()
}
func safeOpenChildNoFollow(parent *os.File, name string) (*os.File, os.FileInfo, error) {
if !validSafeChildName(name) {
return nil, nil, fmt.Errorf("invalid child name %q", name)
}
path := filepath.Join(parent.Name(), name)
fd, err := unix.Openat(int(parent.Fd()), name, unix.O_PATH|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
if err != nil {
return nil, nil, &os.PathError{Op: "openat", Path: path, Err: err}
}
file := os.NewFile(uintptr(fd), path)
info, err := file.Stat()
if err == nil && !info.IsDir() && !info.Mode().IsRegular() {
err = fmt.Errorf("not a regular file or directory: %s", path)
}
if err != nil {
file.Close()
return nil, nil, err
}
return file, info, nil
}
func safeChmodPinnedFile(file *os.File, mode os.FileMode) error {
fd := int(file.Fd())
err := unix.Fchmodat(fd, "", uint32(mode.Perm()), unix.AT_EMPTY_PATH)
if errors.Is(err, unix.EOPNOTSUPP) || errors.Is(err, unix.EINVAL) || errors.Is(err, unix.EPERM) {
// Older kernels may lack fchmodat2; procfs still addresses the pinned inode.
return os.Chmod(fmt.Sprintf("/proc/self/fd/%d", fd), mode.Perm())
}
if err != nil {
return &os.PathError{Op: "fchmodat", Path: file.Name(), Err: err}
}
return nil
}
func safeOpenPinnedDirReader(directory *os.File) (*os.File, error) {
fd, err := unix.Openat(int(directory.Fd()), ".", unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
if err != nil {
return nil, err
}
return os.NewFile(uintptr(fd), directory.Name()), nil
}
// createExtractScratchDirAt creates a unique scratch directory (os.MkdirTemp
// semantics: mode 0700, "*" in pattern replaced by a random suffix, EEXIST
// retried) beneath the pinned root at parentRel via mkdirat on the pinned
// parent, so the extract scratch cannot be raced into a directory outside the
// scope the way the by-name MkdirTemp it replaces could. It returns the
// absolute path for the external tool's argv.
func createExtractScratchDirAt(root *safeRoot, parentRel, pattern string) (string, error) {
cleanRel, err := safeRelUnderRoot(parentRel)
if err != nil {
return "", err
}
parentFd, err := safeOpenDirAt(root, cleanRel)
if err != nil {
return "", err
}
defer parentFd.Close()
var lastErr error
for i := 0; i < 16; i++ {
name := strings.Replace(pattern, "*", randomHex(8), 1)
err := unix.Mkdirat(int(parentFd.Fd()), name, 0o700)
if err == nil {
return filepath.Join(root.path, cleanRel, name), nil
}
if errors.Is(err, unix.EEXIST) {
lastErr = err
continue
}
return "", &os.PathError{Op: "mkdirat", Path: filepath.Join(root.path, cleanRel, name), Err: err}
}
return "", &os.PathError{Op: "mkdirat", Path: filepath.Join(root.path, cleanRel, pattern), Err: lastErr}
}
// safeMkdirMode converts an os.FileMode into the raw mkdir mode word:
// permission bits plus setuid/setgid/sticky, exactly what syscallMode feeds
// mkdir(2) for the os.Mkdir/os.MkdirAll calls the ensureDirUnderRoot helpers
// replace. Callers that pass already-sanitized modes (the extract paths) are
// unaffected; the backup copy walk relies on this to preserve directory
// setgid bits the way os.MkdirAll(destPath, linfo.Mode()) did.
func safeMkdirMode(perm os.FileMode) uint32 {
m := uint32(perm.Perm())
if perm&os.ModeSetuid != 0 {
m |= unix.S_ISUID
}
if perm&os.ModeSetgid != 0 {
m |= unix.S_ISGID
}
if perm&os.ModeSticky != 0 {
m |= unix.S_ISVTX
}
return m
}
// ensureDirUnderRoot creates rel and any missing parents beneath the pinned
// root - the fd-based equivalent of os.MkdirAll(filepath.Join(root.path, rel),
// perm). Unlike MkdirAll, which re-walks existing components by name and
// follows any symlink planted along the way, every component here is opened
// relative to the pinned root with openat2(RESOLVE_BENEATH) and missing
// components are created with mkdirat(2) on the already-verified parent fd,
// so a planted intermediate symlink cannot redirect the creation outside the
// root when the target does not exist yet (the gap in the audited
// "EvalSymlinks-then-MkdirAll, skip the guard on ENOENT" pattern). In-root
// symlinks keep resolving with the same semantics as safeOpenAt. rel == "."
// is a no-op: the pinned root itself always exists.
func ensureDirUnderRoot(root *safeRoot, rel string, perm os.FileMode) error {
cleanRel, err := safeRelUnderRoot(rel)
if err != nil {
return err
}
if cleanRel == "." {
return nil
}
if !safePathForceFallback.Load() {
walkErr := ensureDirUnderRootOpenat(root, cleanRel, perm)
if walkErr == nil {
return nil
}
if !safePathFallbackEligible(walkErr) {
return walkErr
}
}
safePathFallbackCalls.Add(1)
return ensureDirUnderRootLegacy(root, cleanRel, perm)
}
// openSafeDirComponentOpenat opens one path component as a directory beneath
// the given fd, resolving in-root symlinks but refusing (EAGAIN) anything
// that would resolve outside it.
func openSafeDirComponentOpenat(dirFd int, name string) (int, error) {
how := unix.OpenHow{
Flags: uint64(unix.O_RDONLY | unix.O_DIRECTORY | unix.O_CLOEXEC),
Resolve: unix.RESOLVE_BENEATH,
}
return unix.Openat2(dirFd, name, &how)
}
// ensureDirUnderRootOpenat walks rel component-by-component beneath the
// pinned root: existing components are opened with RESOLVE_BENEATH (in-root
// symlinks resolve, escapes are refused by the kernel) and missing ones are
// created with mkdirat(2) on the verified parent fd, so the walk can never
// descend through a symlink that leaves the root.
func ensureDirUnderRootOpenat(root *safeRoot, rel string, perm os.FileMode) error {
curFd := int(root.file.Fd())
owned := false // curFd starts as the root's fd; only close what we opened
advance := func(childFd int) {
if owned {
unix.Close(curFd)
}
curFd, owned = childFd, true
}
defer func() {
if owned {
unix.Close(curFd)
}
}()
for _, part := range strings.Split(rel, string(os.PathSeparator)) {
if !validSafeChildName(part) {
return fmt.Errorf("%w: invalid component %q", errSafeScopeEscape, part)
}
childFd, err := openSafeDirComponentOpenat(curFd, part)
if err == nil {
advance(childFd)
continue
}
if !errors.Is(err, unix.ENOENT) {
// EAGAIN (the component resolves outside the root via a
// symlink) is retried through the legacy path by the caller so
// in-root absolute symlinks keep working; ENOTDIR, ELOOP, ...
// surface as-is, like the MkdirAll errors they replace.
return err
}
if err := unix.Mkdirat(curFd, part, safeMkdirMode(perm)); err != nil && !errors.Is(err, unix.EEXIST) {
return err
}
childFd, err = openSafeDirComponentOpenat(curFd, part)
if err != nil {
return err
}
advance(childFd)
}
return nil
}
// ensureDirUnderRootLegacy is the pre-openat2 fallback (and the non-Linux
// implementation): it resolves the deepest already-existing ancestor of rel
// and verifies it beneath the root WITHOUT skipping ENOENT - the gap in the
// audited EvalSymlinks-then-MkdirAll pattern - then creates the missing tail
// one os.Mkdir at a time, re-verifying every component it creates or finds.
func ensureDirUnderRootLegacy(root *safeRoot, rel string, perm os.FileMode) error {
abs := filepath.Join(root.path, rel)
deepest := abs
for {
resolved, err := filepath.EvalSymlinks(deepest)
if err == nil {
if !isUnder(root.path, resolved) && root.path != resolved {
return fmt.Errorf("%w: %s", errSafeScopeEscape, rel)
}
break
}
if !errors.Is(err, fs.ErrNotExist) {
return err
}
parent := filepath.Dir(deepest)
if parent == deepest {
return err
}
deepest = parent
}
tail, err := filepath.Rel(deepest, abs)
if err != nil {
return err
}
cur := deepest
for _, part := range strings.Split(tail, string(os.PathSeparator)) {
if part == "" || part == "." {
continue
}
cur = filepath.Join(cur, part)
if err := os.Mkdir(cur, perm); err != nil && !os.IsExist(err) {
return err
}
resolved, err := filepath.EvalSymlinks(cur)
if err != nil {
return err
}
if !isUnder(root.path, resolved) && root.path != resolved {
return fmt.Errorf("%w: %s", errSafeScopeEscape, rel)
}
cur = resolved
}
return nil
}
// openUploadTempFileAt is the fd-based version of openURLUploadTempFile:
// a unique O_CREAT|O_EXCL temp file created relative to the pinned server
// scope root, so no by-name walk can be raced into another server's
// directory and no existing file can be clobbered. It is the shared staging
// primitive of every streaming upload route (URL fetch and multipart
// stream): bytes land in the temp file and reach the target only through a
// same-directory rename commit. It returns the open file and the temp path
// RELATIVE to the scope root.
func openUploadTempFileAt(root *safeRoot, dirRel, filename string) (*os.File, string, error) {
prefix := "." + sanitizeUploadFilenameForURL(filename)
if prefix == "." {
prefix = ".download"
}
for i := 0; i < 16; i++ {
tmpRel := filepath.Join(dirRel, fmt.Sprintf("%s.%s.urlupload.tmp", prefix, randomHex(8)))
f, err := safeOpenAt(root, tmpRel, os.O_CREATE|os.O_EXCL|os.O_WRONLY|syscall.O_NOFOLLOW, 0o644)
if err == nil {
return f, tmpRel, nil
}
if os.IsExist(err) {
continue
}
return nil, "", err
}
return nil, "", fmt.Errorf("could not allocate temp file")
}
// openArchiveTempFileAt creates the files/archive endpoint's unique in-flight
// temp file relative to the pinned server scope root (O_CREAT|O_EXCL, so no
// by-name walk can be raced and no existing file can be clobbered) with the
// ".archive-*.tmp" name pattern the archive walk excludes by. The mode is
// 0644 so the process umask still applies at creation, exactly like the
// os.OpenFile-based creation this replaces - an unconditional Chmod(0o644)
// would force world-readable archives on umask-077 hosts. It returns the
// open file and the temp path RELATIVE to the scope root.
func openArchiveTempFileAt(root *safeRoot, dirRel string) (*os.File, string, error) {
for i := 0; i < 16; i++ {
tmpRel := filepath.Join(dirRel, strings.Replace(archiveTempPattern, "*", randomHex(8), 1))
f, err := safeOpenAt(root, tmpRel, os.O_CREATE|os.O_EXCL|os.O_WRONLY|syscall.O_NOFOLLOW, 0o644)
if err == nil {
return f, tmpRel, nil
}
if os.IsExist(err) {
continue
}
return nil, "", err
}
return nil, "", fmt.Errorf("could not allocate temp file")
}