wastebin-mcp-go/internal/wastebin/open.go
xlion-bot-renovate[bot] eaf8788a07
chore(deps): update dependency go to v1.27.1 (#251)
* chore(deps): update dependency go to v1.27.1

* Fixed lints; `just verify` passes.

Co-authored-by: xlionjuan <[email protected]>

* Re-enabled exhaustruct_v5; just verify passes.

Co-authored-by: xlionjuan <[email protected]>

* Fixed lint config; verify passes.

Co-authored-by: xlionjuan <[email protected]>

* Explicit DisableBuiltinBlocklist; verify passes 0 issues.

Co-authored-by: xlionjuan <[email protected]>

---------

Co-authored-by: xlion-bot-renovate[bot] <218815870+xlion-bot-renovate[bot]@users.noreply.github.com>
Co-authored-by: opencode-agent[bot] <opencode-agent[bot]@users.noreply.github.com>
Co-authored-by: xlionjuan <[email protected]>
2026-09-06 23:13:47 +08:00

197 lines
6.2 KiB
Go

package wastebin
import (
"os"
"path/filepath"
"strings"
"golang.org/x/sys/unix"
)
// Sentinel errors are defined in errors.go.
// openFileResolved opens a file with symlink-safe semantics:
// - When allowed paths are configured, uses openat(2) with O_NOFOLLOW from each
// candidate root directory's pinned fd, so that a post-validation symlink swap
// can only cause the open to fail (ELOOP) rather than follow a symlink to a
// blocked path.
// - When no allowed paths are configured, walks every path component from the
// root directory / using openat(2) with O_NOFOLLOW, providing the same level
// of protection against intermediate symlink swaps.
func openFileResolved(resolvedPath string, allowedPaths []string) (*os.File, error) {
if len(allowedPaths) > 0 {
return openFileFromRoot(resolvedPath, allowedPaths)
}
// Walk from / with openat+O_NOFOLLOW so that no component — intermediate
// or final — can be a symlink. This is equivalent to treating "/" as
// the implicit allowed root.
return openFileFromRoot(resolvedPath, []string{"/"})
}
// openFileFromRoot opens resolvedPath after verifying it is under one of the
// allowed roots. Instead of opening the root path directly (which would be
// subject to a TOCTOU race if an intermediate parent directory is swapped to
// a symlink), it opens / with O_NOFOLLOW and walks every path component via
// openat(2) with O_NOFOLLOW. This guarantees that no component — including
// the root path's parents — can be a symlink at open time.
func openFileFromRoot(resolvedPath string, allowedPaths []string) (*os.File, error) {
_, _, ok := findAllowedRoot(resolvedPath, allowedPaths)
if !ok {
return nil, errPathNotAllowed
}
// Open / as the trusted starting point. O_NOFOLLOW on "/" is defensive
// (the root directory cannot be a symlink on Linux).
root, err := os.OpenFile("/", os.O_RDONLY|unix.O_NOFOLLOW, 0)
if err != nil {
return nil, err
}
defer root.Close() //nolint:errcheck // Read-only directory; close error non-critical
// Walk every component from / to the resolved path with openat+O_NOFOLLOW.
// Any intermediate symlink swap causes ELOOP instead of following.
relFromRoot := strings.TrimPrefix(resolvedPath, "/")
return openRelNoFollow(root, relFromRoot)
}
// findAllowedRoot finds the first allowed path that contains resolvedPath and
// returns that root along with the relative path from it. Both inputs and
// outputs are cleaned, absolute paths.
func findAllowedRoot(resolvedPath string, allowedPaths []string) (string, string, bool) {
cleaned := filepath.Clean(resolvedPath)
for _, allowed := range allowedPaths {
cleanAllowed := filepath.Clean(allowed)
if isContainedPath(cleanAllowed, cleaned) {
rel, err := filepath.Rel(cleanAllowed, cleaned)
if err != nil {
return "", "", false
}
return cleanAllowed, rel, true
}
}
return "", "", false
}
// openRelNoFollow walks every component of relPath from the directory fd dir
// using openat(2) with O_RDONLY|O_NOFOLLOW|O_CLOEXEC. Intermediate components
// are verified to be directories; the final component is returned as an
// *os.File after being verified as a regular file. If any component is a
// symlink (or is replaced by one concurrently) the call fails with ELOOP
// instead of following it.
//
// The final component is opened with O_NONBLOCK so that FIFO file paths
// (which block on O_RDONLY until a writer appears) fail immediately and are
// rejected before any read can begin.
//
//nolint:gocognit // openat walk with per-component validation and careful fd unwind
func openRelNoFollow(dir *os.File, relPath string) (*os.File, error) {
parts := splitPath(relPath)
if len(parts) == 0 {
return nil, errOpenEmptyPath
}
firstFd := int(dir.Fd())
parentFd := firstFd
for i, part := range parts {
isLast := i == len(parts)-1
flags := unix.O_RDONLY | unix.O_NOFOLLOW | unix.O_CLOEXEC
if isLast {
flags |= unix.O_NONBLOCK
}
fd, err := unix.Openat(parentFd, part, flags, 0)
if err != nil {
if parentFd != firstFd {
_ = unix.Close(parentFd) //nolint:errcheck // Best-effort close during error unwind
}
return nil, err
}
if isLast {
if parentFd != firstFd {
_ = unix.Close(parentFd) //nolint:errcheck // Best-effort close; fd copied into os.File
}
return validateRegularFile(fd, filepath.Join(dir.Name(), relPath))
}
// Verify intermediate component is a directory.
var stat unix.Stat_t
fstatErr := unix.Fstat(fd, &stat)
if fstatErr != nil {
_ = unix.Close(fd) //nolint:errcheck // Best-effort close during error unwind
if parentFd != firstFd {
_ = unix.Close(parentFd) //nolint:errcheck // Best-effort close during error unwind
}
return nil, fstatErr
}
if stat.Mode&unix.S_IFMT != unix.S_IFDIR {
_ = unix.Close(fd) //nolint:errcheck // Best-effort close for unexpected type
if parentFd != firstFd {
_ = unix.Close(parentFd) //nolint:errcheck // Best-effort close; no longer needed
}
return nil, errFilePathCannotBeUsed
}
if parentFd != firstFd {
_ = unix.Close(parentFd) //nolint:errcheck // Parent fd closed after child opened
}
parentFd = fd
}
return nil, errOpenEmptyPath
}
// validateRegularFile verifies that the file descriptor fd points to a
// regular file. If the fstat call itself fails the error is propagated as-is;
// if the file exists but is not a regular file (e.g. a FIFO or device node)
// errFilePathCannotBeUsed is returned. On any failure fd is closed before
// returning.
func validateRegularFile(fd int, name string) (*os.File, error) {
var stat unix.Stat_t
fstatErr := unix.Fstat(fd, &stat)
if fstatErr != nil {
_ = unix.Close(fd) //nolint:errcheck // Close on stat failure
return nil, fstatErr
}
if stat.Mode&unix.S_IFMT != unix.S_IFREG {
_ = unix.Close(fd) //nolint:errcheck // Close non-regular file
return nil, errFilePathCannotBeUsed
}
return os.NewFile(uintptr(fd), name), nil
}
// splitPath splits a relative path into non-empty components.
func splitPath(relPath string) []string {
cleaned := filepath.ToSlash(filepath.Clean(relPath))
parts := strings.Split(cleaned, "/")
var result []string
for _, p := range parts {
if p != "" && p != "." {
result = append(result, p)
}
}
return result
}