2017-12-02 20:35:44 +01:00
|
|
|
package syscallcompat
|
|
|
|
|
|
|
|
import (
|
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
|
|
|
"syscall"
|
|
|
|
|
|
|
|
"github.com/rfjakob/gocryptfs/internal/tlog"
|
|
|
|
)
|
|
|
|
|
2018-09-08 17:41:17 +02:00
|
|
|
// OpenDirNofollow opens the dir at "relPath" in a way that is secure against
|
2017-12-02 20:35:44 +01:00
|
|
|
// 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.
|
2018-09-08 17:41:17 +02:00
|
|
|
func OpenDirNofollow(baseDir string, relPath string) (fd int, err error) {
|
2017-12-02 20:35:44 +01:00
|
|
|
if !filepath.IsAbs(baseDir) {
|
2018-09-08 17:41:17 +02:00
|
|
|
tlog.Warn.Printf("BUG: OpenDirNofollow called with relative baseDir=%q", baseDir)
|
2017-12-02 20:35:44 +01:00
|
|
|
return -1, syscall.EINVAL
|
|
|
|
}
|
|
|
|
if filepath.IsAbs(relPath) {
|
2018-09-08 17:41:17 +02:00
|
|
|
tlog.Warn.Printf("BUG: OpenDirNofollow called with absolute relPath=%q", relPath)
|
2017-12-02 20:35:44 +01:00
|
|
|
return -1, syscall.EINVAL
|
|
|
|
}
|
2017-12-05 23:31:07 +01:00
|
|
|
// Open the base dir (following symlinks)
|
|
|
|
dirfd, err := syscall.Open(baseDir, syscall.O_RDONLY|syscall.O_DIRECTORY, 0)
|
2017-12-02 20:35:44 +01:00
|
|
|
if err != nil {
|
|
|
|
return -1, err
|
|
|
|
}
|
2017-12-05 23:08:55 +01:00
|
|
|
// Caller wanted to open baseDir itself?
|
|
|
|
if relPath == "" {
|
|
|
|
return dirfd, nil
|
|
|
|
}
|
2018-09-08 17:41:17 +02:00
|
|
|
// Split the path into components
|
2017-12-02 20:35:44 +01:00
|
|
|
parts := strings.Split(relPath, "/")
|
2018-09-08 17:41:17 +02:00
|
|
|
// Walk the directory tree
|
2017-12-02 20:35:44 +01:00
|
|
|
var dirfd2 int
|
2018-09-08 17:41:17 +02:00
|
|
|
for _, name := range parts {
|
2018-09-08 18:06:33 +02:00
|
|
|
dirfd2, err = Openat(dirfd, name, syscall.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_DIRECTORY|O_PATH, 0)
|
2017-12-02 20:35:44 +01:00
|
|
|
syscall.Close(dirfd)
|
|
|
|
if err != nil {
|
|
|
|
return -1, err
|
|
|
|
}
|
|
|
|
dirfd = dirfd2
|
|
|
|
}
|
2018-09-08 17:41:17 +02:00
|
|
|
// Return fd to final directory
|
|
|
|
return dirfd, nil
|
2017-12-02 20:35:44 +01:00
|
|
|
}
|