Files
ThothII/tools/thothctl/internal/safeio/files_unix.go
T

289 lines
9.7 KiB
Go

//go:build !windows && !linux
package safeio
import (
"crypto/rand"
"encoding/hex"
"io/fs"
"os"
"strings"
"golang.org/x/sys/unix"
)
// ReadCanonicalRegular opens an absolute canonical path component by component from the root
// descriptor. O_NOFOLLOW rejects symlinks at every component, and the open directory descriptors
// prevent later parent replacement from redirecting the final open.
func ReadCanonicalRegular(path string, maximum int64) ([]byte, error) {
if err := ValidateCanonicalPath(path); err != nil {
return nil, err
}
components := strings.Split(strings.TrimPrefix(path, string(os.PathSeparator)), string(os.PathSeparator))
if len(components) == 0 || components[0] == "" {
return nil, ErrUnsafeFile
}
directory, err := unix.Open(string(os.PathSeparator), unix.O_RDONLY|unix.O_CLOEXEC|unix.O_DIRECTORY, 0)
if err != nil {
return nil, ErrUnsafeFile
}
directories := []int{directory}
defer func() { closeUnixDescriptors(directories) }()
for _, component := range components[:len(components)-1] {
nextDirectory, err := unix.Openat(directory, component, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_DIRECTORY|unix.O_NOFOLLOW, 0)
if err != nil {
return nil, ErrUnsafeFile
}
directory = nextDirectory
directories = append(directories, directory)
}
descriptor, err := unix.Openat(directory, components[len(components)-1], unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0)
if err != nil {
return nil, ErrUnsafeFile
}
file := os.NewFile(uintptr(descriptor), "thothctl-safeio")
if file == nil {
unix.Close(descriptor)
return nil, ErrUnsafeFile
}
defer file.Close()
var before, after unix.Stat_t
if err := unix.Fstat(int(file.Fd()), &before); err != nil || before.Nlink > 1 || before.Mode&unix.S_IFMT != unix.S_IFREG {
return nil, ErrUnsafeFile
}
contents, err := readBoundedRegularFile(file, maximum)
if err != nil {
return nil, ErrUnsafeFile
}
// Checking the retained descriptor alone misses a pathname replacement while the
// read is in progress. The parent descriptor and final name must still resolve to
// the exact open file after reading.
if err := unix.Fstat(int(file.Fd()), &after); err != nil || after.Nlink > 1 || after.Mode != before.Mode || after.Ino != before.Ino || after.Dev != before.Dev || after.Size != before.Size {
return nil, ErrUnsafeFile
}
var named unix.Stat_t
if err := unix.Fstatat(directory, components[len(components)-1], &named, unix.AT_SYMLINK_NOFOLLOW); err != nil || named.Nlink > 1 || named.Mode != before.Mode || named.Ino != before.Ino || named.Dev != before.Dev {
return nil, ErrUnsafeFile
}
if !recheckUnixParents(components, directories) {
return nil, ErrUnsafeFile
}
return contents, nil
}
func closeUnixDescriptors(descriptors []int) {
for _, descriptor := range descriptors {
unix.Close(descriptor)
}
}
func writeCanonicalExclusive(path string, contents []byte, mode fs.FileMode) error {
if err := ValidateCanonicalPath(path); err != nil || len(contents) > 16<<20 || mode.Perm() != 0o600 {
return ErrUnsafeFile
}
components := strings.Split(strings.TrimPrefix(path, string(os.PathSeparator)), string(os.PathSeparator))
if len(components) == 0 || components[0] == "" {
return ErrUnsafeFile
}
dir, err := unix.Open("/", unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
if err != nil {
return ErrUnsafeFile
}
// Close the descriptor that owns the final retained parent. The traversal
// closes each superseded descriptor explicitly; evaluating unix.Close(dir)
// at defer time would close only the original root descriptor.
defer func() { _ = unix.Close(dir) }()
for _, component := range components[:len(components)-1] {
next, openErr := unix.Openat(dir, component, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC|unix.O_NOFOLLOW, 0)
if openErr != nil {
return ErrUnsafeFile
}
unix.Close(dir)
dir = next
}
if !recheckUnixParentPath(components[:len(components)-1], dir) {
return ErrUnsafeFile
}
// Build the candidate under a private, same-parent name. Only after it is fully
// written, synced, and identity-checked do we link it into the requested leaf.
stage, err := privateStageName()
if err != nil {
return ErrUnsafeFile
}
stageFD, err := unix.Openat(dir, stage, unix.O_WRONLY|unix.O_CREAT|unix.O_EXCL|unix.O_CLOEXEC|unix.O_NOFOLLOW, uint32(mode.Perm()))
if err != nil {
return ErrUnsafeFile
}
stageFile := os.NewFile(uintptr(stageFD), "thothctl-safeio-stage")
if stageFile == nil {
unix.Close(stageFD)
_ = unix.Unlinkat(dir, stage, 0)
return ErrUnsafeFile
}
stageCreated := true
var staged unix.Stat_t
if err := unix.Fstat(stageFD, &staged); err != nil || staged.Nlink != 1 || staged.Mode&unix.S_IFMT != unix.S_IFREG {
_ = stageFile.Close()
_ = unix.Unlinkat(dir, stage, 0)
return ErrUnsafeFile
}
published := false
// Keep the inode identity immutable across every check and cleanup path.
var publishedIdentity = staged
cleanup := func() {
if published {
var current unix.Stat_t
if unix.Fstatat(dir, components[len(components)-1], &current, unix.AT_SYMLINK_NOFOLLOW) == nil &&
current.Ino == publishedIdentity.Ino && current.Dev == publishedIdentity.Dev {
_ = unix.Unlinkat(dir, components[len(components)-1], 0)
}
}
if stageCreated {
var current unix.Stat_t
if unix.Fstatat(dir, stage, &current, unix.AT_SYMLINK_NOFOLLOW) == nil &&
current.Ino == staged.Ino && current.Dev == staged.Dev {
_ = unix.Unlinkat(dir, stage, 0)
}
}
}
fail := func() error {
_ = stageFile.Close()
cleanup()
return ErrUnsafeFile
}
if err := stageFile.Chmod(mode); err != nil {
return fail()
}
n, err := stageFile.Write(contents)
if err != nil || n != len(contents) {
return fail()
}
if err := stageFile.Sync(); err != nil {
return fail()
}
// On platforms without O_TMPFILE, a same-user actor can hard-link the
// nameable stage. Extra links are therefore not a post-write rejection:
// once observed, the bytes are already public and rejecting would leave the
// attacker's link behind. Cleanup still uses the immutable inode identity.
var afterWrite unix.Stat_t
if err := unix.Fstat(stageFD, &afterWrite); err != nil || afterWrite.Nlink < 1 || afterWrite.Mode&unix.S_IFMT != unix.S_IFREG || afterWrite.Size != int64(len(contents)) {
return fail()
}
if err := stageFile.Close(); err != nil {
cleanup()
return ErrUnsafeFile
}
stageCreated = true
if !recheckUnixParentPath(components[:len(components)-1], dir) {
return fail()
}
if err := unix.Linkat(dir, stage, dir, components[len(components)-1], 0); err != nil {
return fail()
}
published = true
var linked unix.Stat_t
if err := unix.Fstatat(dir, components[len(components)-1], &linked, unix.AT_SYMLINK_NOFOLLOW); err != nil ||
linked.Ino != staged.Ino || linked.Dev != staged.Dev || linked.Nlink < 2 {
return fail()
}
if err := unix.Unlinkat(dir, stage, 0); err != nil {
return fail()
}
stageCreated = false
var finalIdentity unix.Stat_t
if err := unix.Fstatat(dir, components[len(components)-1], &finalIdentity, unix.AT_SYMLINK_NOFOLLOW); err != nil || finalIdentity.Ino != publishedIdentity.Ino || finalIdentity.Dev != publishedIdentity.Dev || finalIdentity.Nlink < 1 {
return fail()
}
if err := unix.Fsync(dir); err != nil || !recheckUnixParentPath(components[:len(components)-1], dir) {
return fail()
}
return nil
}
func privateStageName() (string, error) {
var random [16]byte
if _, err := rand.Read(random[:]); err != nil {
return "", err
}
return ".thothctl-candidate-" + hex.EncodeToString(random[:]), nil
}
func validateCanonicalOutputPath(path string) error {
if err := ValidateCanonicalPath(path); err != nil {
return err
}
components := strings.Split(strings.TrimPrefix(path, string(os.PathSeparator)), string(os.PathSeparator))
if len(components) < 2 || components[0] == "" {
return ErrUnsafeFile
}
dir, err := unix.Open("/", unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
if err != nil {
return ErrUnsafeFile
}
defer func() { unix.Close(dir) }()
for _, component := range components[:len(components)-1] {
next, err := unix.Openat(dir, component, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC|unix.O_NOFOLLOW, 0)
if err != nil {
return ErrUnsafeFile
}
unix.Close(dir)
dir = next
}
var st unix.Stat_t
if err := unix.Fstatat(dir, components[len(components)-1], &st, unix.AT_SYMLINK_NOFOLLOW); err == nil {
return ErrUnsafeFile
} else if err != unix.ENOENT {
return ErrUnsafeFile
}
return nil
}
func recheckUnixParents(components []string, retained []int) bool {
if len(retained) != len(components) {
return false
}
dir, err := unix.Open("/", unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
if err != nil {
return false
}
defer func() { unix.Close(dir) }()
for i, component := range components[:len(components)-1] {
next, e := unix.Openat(dir, component, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC|unix.O_NOFOLLOW, 0)
if e != nil {
return false
}
var got, want unix.Stat_t
if unix.Fstat(next, &got) != nil || unix.Fstat(retained[i+1], &want) != nil || got.Ino != want.Ino || got.Dev != want.Dev {
unix.Close(next)
return false
}
unix.Close(dir)
dir = next
}
return true
}
func recheckUnixParentPath(components []string, retained int) bool {
dir, err := unix.Open("/", unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
if err != nil {
return false
}
defer func() { unix.Close(dir) }()
for _, component := range components {
next, e := unix.Openat(dir, component, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC|unix.O_NOFOLLOW, 0)
if e != nil {
return false
}
unix.Close(dir)
dir = next
}
var got, want unix.Stat_t
return unix.Fstat(dir, &got) == nil && unix.Fstat(retained, &want) == nil && got.Ino == want.Ino && got.Dev == want.Dev
}
func validatePlatformPathSyntax(path string) error { return nil }