libgocryptfs/internal/syscallcompat/open_nofollow.go
Jakob Unterwurzacher 69d88505fd go mod: declare module version v2
Our git version is v2+ for some time now, but go.mod
still declared v1. Hopefully making both match makes
https://pkg.go.dev/github.com/rfjakob/gocryptfs/v2 work.

All the import paths have been fixed like this:

  find . -name \*.go | xargs sed -i s%github.com/rfjakob/gocryptfs/%github.com/rfjakob/gocryptfs/v2/%
2021-08-23 15:05:15 +02:00

48 lines
1.3 KiB
Go

package syscallcompat
import (
"path/filepath"
"strings"
"syscall"
)
// OpenDirNofollow opens the dir at "relPath" in a way that is secure against
// symlink attacks. Symlinks that are part of "relPath" are never followed.
// This function is implemented by walking the directory tree, starting at
// "baseDir", using the Openat syscall with the O_NOFOLLOW flag.
// Symlinks that are part of the "baseDir" path are followed.
// Retries on EINTR.
func OpenDirNofollow(baseDir string, relPath string) (fd int, err error) {
if !filepath.IsAbs(baseDir) {
return -1, syscall.EINVAL
}
if filepath.IsAbs(relPath) {
return -1, syscall.EINVAL
}
// Open the base dir (following symlinks)
dirfd, err := retryEINTR2(func() (int, error) {
return syscall.Open(baseDir, syscall.O_DIRECTORY|O_PATH, 0)
})
if err != nil {
return -1, err
}
// Caller wanted to open baseDir itself?
if relPath == "" {
return dirfd, nil
}
// Split the path into components
parts := strings.Split(relPath, "/")
// Walk the directory tree
var dirfd2 int
for _, name := range parts {
dirfd2, err = Openat(dirfd, name, syscall.O_NOFOLLOW|syscall.O_DIRECTORY|O_PATH, 0)
syscall.Close(dirfd)
if err != nil {
return -1, err
}
dirfd = dirfd2
}
// Return fd to final directory
return dirfd, nil
}