//go:build !linux package main // adpanel:fs-toctou - non-Linux stubs for the fd-based path containment // helpers (see pathsafe.go). openat2/RESOLVE_BENEATH and the *at() family are // Linux-only; these builds fall back to the pre-existing validate-then-open // path (EvalSymlinks + ensureResolvedUnder) so behavior is never worse than // the by-name handlers they replace. import ( "errors" "fmt" "io/fs" "os" "path/filepath" "strings" "sync/atomic" ) var ( safePathOpenat2Calls atomic.Int64 // always zero on non-Linux builds safePathFallbackCalls atomic.Int64 ) var safePathForceFallback atomic.Bool // safeRoot pins the server scope root path for one request. On non-Linux // builds there is no dirfd, so only the path is carried for validation. type safeRoot struct { file *os.File path string } func safeOpenRoot(rootPath string) (*safeRoot, error) { c := filepath.Clean(rootPath) f, err := os.Open(c) if err != nil { return nil, err } st, err := f.Stat() if err != nil { f.Close() return nil, err } if !st.IsDir() { f.Close() return nil, fmt.Errorf("safe-open-root: %s: not a directory", c) } return &safeRoot{file: f, path: c}, nil } func (sr *safeRoot) Close() error { if sr == nil || sr.file == nil { return nil } return sr.file.Close() } func safeRelUnderRoot(rel string) (string, error) { if rel == "" { return "", fmt.Errorf("empty relative path") } c := filepath.Clean(rel) if filepath.IsAbs(c) || c == ".." || len(c) >= 3 && c[:3] == ".."+string(os.PathSeparator) { return "", fmt.Errorf("invalid relative path %q", rel) } return c, nil } func validSafeChildName(name string) bool { return name != "" && name != "." && name != ".." && !strings.ContainsRune(name, '/') } func safeOpenAt(root *safeRoot, rel string, openFlags int, perm os.FileMode) (*os.File, error) { cleanRel, err := safeRelUnderRoot(rel) if err != nil { return nil, err } safePathFallbackCalls.Add(1) return safeOpenAtLegacy(root, cleanRel, openFlags, perm) } func safeOpenDirAt(root *safeRoot, rel string) (*os.File, error) { return safeOpenAt(root, rel, os.O_RDONLY, 0) } 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 { 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 (path-validated) root and refuses // anything that is not a regular file before the caller can read from it. // There is no portable O_NONBLOCK on non-Linux builds, so unlike the Linux // implementation the regular-file gate runs after the open; the daemon ships // on Linux nodes, where pathsafe.go also de-wedges the open itself. 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, 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)) } return f, st, nil } // safeWriteAt writes data to rel beneath the (path-validated) root. Like the // non-Linux safeOpenRegularAt there is no portable O_NONBLOCK here, so only // the regular-file gate runs after the open: a non-regular target (a planted // FIFO, device or socket) is rejected with errSafeNotRegular instead of being // written through, but the open itself can still wedge on a FIFO on non-Linux // builds (the daemon ships on Linux nodes, where pathsafe.go de-wedges it). func safeWriteAt(root *safeRoot, rel string, openFlags int, perm os.FileMode, data []byte) error { f, err := safeOpenAt(root, rel, openFlags, perm) if err != nil { 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)) } _, werr := f.Write(data) cerr := f.Close() if werr != nil { return werr } return cerr } // safeOpenWriteAt opens rel beneath the (path-validated) root with the // caller's write flags and returns it after the regular-file gate. Like the // non-Linux safeOpenRegularAt there is no portable O_NONBLOCK here, so only // the gate runs after the open: a non-regular target (a planted FIFO, device // or socket) is rejected with errSafeNotRegular instead of being written // through, but the open itself can still wedge on a FIFO on non-Linux builds // (the daemon ships on Linux nodes, where pathsafe.go de-wedges it). func safeOpenWriteAt(root *safeRoot, rel string, openFlags int, perm os.FileMode) (*os.File, error) { f, err := safeOpenAt(root, rel, openFlags, 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)) } return f, nil } // The listing readers live in main.go (readDirEntriesBounded): both platform // builds share that bounded implementation, which produces the name-sorted // order the former safeReadDirSorted here provided. func safeStatAt(dir *os.File, name string) (fs.FileInfo, error) { if !validSafeChildName(name) { return nil, fmt.Errorf("invalid child name %q", name) } return os.Lstat(filepath.Join(dir.Name(), name)) } // safeRemoveAt removes name relative to the pinned parent fd - the non-Linux // mirror of the linux safeRemoveAt contract: os.Remove already performs the // unlink-first, rmdir-on-EISDIR sequence, and 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) } return os.Remove(filepath.Join(parent.Name(), name)) } func safeDeleteUnderRoot(root *safeRoot, rel string, isDir bool) error { cleanRel, err := safeRelUnderRoot(rel) if err != nil { return err } // rel == "." (the server root itself) is REFUSED, matching the linux // pathsafe.go contract: removing the root would delete the whole server // directory, which is reserved for the dedicated admin server-delete / // reinstall flows, never the files API. if cleanRel == "." { return fmt.Errorf("refusing to delete server root") } abs := filepath.Join(root.path, cleanRel) if err := ensureResolvedUnder(root.path, abs); err != nil { return err } if isDir { return os.RemoveAll(abs) } return os.Remove(abs) } 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") } oldAbs := filepath.Join(root.path, cleanRel) newAbs := filepath.Join(filepath.Dir(oldAbs), newName) if err := ensureResolvedUnder(root.path, oldAbs); err != nil { return err } if err := ensureResolvedUnder(root.path, filepath.Dir(newAbs)); err != nil { return err } return os.Rename(oldAbs, newAbs) } // 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 // non-Linux mirror of the linux RENAME_NOREPLACE contract (see pathsafe.go). // There is no renameat2 here, so the refusal is an explicit destination // lstat followed by os.Rename; like the linux fallback this leaves a small // residual TOCTOU window (a destination created between the two calls can // still be replaced), and the rename itself stays beneath the validated // root 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 { if requireAtomic { return errors.New("atomic no-replace rename is unavailable") } 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; the destination lstat below would false-positive // EEXIST on the source itself, so short-circuit first - the mirror of // the linux pathsafe.go short-circuit. if newName == filepath.Base(cleanRel) { return nil } oldAbs := filepath.Join(root.path, cleanRel) newAbs := filepath.Join(filepath.Dir(oldAbs), newName) if err := ensureResolvedUnder(root.path, oldAbs); err != nil { return err } if err := ensureResolvedUnder(root.path, filepath.Dir(newAbs)); err != nil { return err } if _, statErr := os.Lstat(newAbs); statErr == nil { return fmt.Errorf("%w: %s", errSafeDestExists, newName) } else if !os.IsNotExist(statErr) { return statErr } return os.Rename(oldAbs, newAbs) } // safeRenameFileAcrossDirs renames oldName (a child of oldDir) to newName (a // child of newDir) - the non-Linux mirror of the linux renameat(2) contract: // both parents were already validated beneath the root when they were opened, // and os.Rename between them behaves like the by-name move it replaces. 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) } return os.Rename(filepath.Join(oldDir.Name(), oldName), filepath.Join(newDir.Name(), newName)) } // safeRenameFileAcrossDirsNoReplace renames oldName (a child of oldDir) to // newName (a child of newDir), REFUSING to replace an existing destination - // the non-Linux mirror of the linux RENAME_NOREPLACE contract (see // pathsafe.go), serving the extract no-clobber mode // (adpanel:extract-no-clobber). There is no renameat2 here, so the refusal is // an explicit destination lstat followed by os.Rename; like the linux // fallback this leaves a small residual TOCTOU window (a destination created // between the two calls can still be replaced), and the rename itself stays // between the two (already path-validated) parents either way. 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) } newAbs := filepath.Join(newDir.Name(), newName) if _, statErr := os.Lstat(newAbs); statErr == nil { return fmt.Errorf("%w: %s", errSafeDestExists, newName) } else if !os.IsNotExist(statErr) { return statErr } return os.Rename(filepath.Join(oldDir.Name(), oldName), newAbs) } func swapStagedRestore(stagingDir, serverDir string) error { return fmt.Errorf("atomic backup restore is not supported on this platform") } 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) info, err := os.Lstat(path) if err != nil { return nil, nil, err } if !info.IsDir() && !info.Mode().IsRegular() { return nil, nil, fmt.Errorf("not a regular file or directory: %s", path) } file, err := os.OpenFile(path, os.O_RDONLY|openNoFollow, 0) if err != nil { return nil, nil, err } opened, err := file.Stat() if err != nil || !os.SameFile(info, opened) { file.Close() return nil, nil, fmt.Errorf("could not verify opened path %s", path) } return file, opened, nil } func safeChmodPinnedFile(file *os.File, mode os.FileMode) error { return file.Chmod(mode.Perm()) } func safeOpenPinnedDirReader(directory *os.File) (*os.File, error) { return directory, nil } // createExtractScratchDirAt creates a unique scratch directory (os.MkdirTemp // semantics: mode 0700, "*" in pattern replaced by a random suffix, EEXIST // retried) beneath the (path-validated) root at parentRel. 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 } absParent := filepath.Join(root.path, cleanRel) if err := ensureResolvedUnder(root.path, absParent); err != nil { return "", err } var lastErr error for i := 0; i < 16; i++ { name := strings.Replace(pattern, "*", randomHex(8), 1) abs := filepath.Join(absParent, name) err := os.Mkdir(abs, 0o700) if err == nil { return abs, nil } if os.IsExist(err) { lastErr = err continue } return "", err } return "", lastErr } // 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") // 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 |= 0o4000 } if perm&os.ModeSetgid != 0 { m |= 0o2000 } if perm&os.ModeSticky != 0 { m |= 0o1000 } return m } // ensureDirUnderRoot creates rel and any missing parents beneath the pinned // root - the non-Linux equivalent of os.MkdirAll(filepath.Join(root.path, // rel), perm). There is no *at() family here, so the legacy walk below is the // only implementation; it verifies the deepest existing ancestor without // skipping ENOENT (the gap in the audited EvalSymlinks-then-MkdirAll // pattern) and never walks creation through a component that leaves the // root. 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 } safePathFallbackCalls.Add(1) return ensureDirUnderRootLegacy(root, cleanRel, perm) } // ensureDirUnderRootLegacy resolves the deepest already-existing ancestor of // rel and verifies it beneath the root WITHOUT skipping ENOENT, 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 non-Linux mirror of the fd-based temp-file // allocator in pathsafe.go (see there for the full doc): a unique // O_CREAT|O_EXCL temp file inside the destination directory, shared by the // URL-fetch and multipart-stream upload routes for their rename commits. 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, 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 (path-validated) server scope root with the // ".archive-*.tmp" name pattern the archive walk excludes by. The mode is // 0644 so the process umask still applies at creation - 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, 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") }