2017-12-02 20:35:44 +01:00
|
|
|
package syscallcompat
|
|
|
|
|
|
|
|
import (
|
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
|
|
|
"syscall"
|
|
|
|
)
|
|
|
|
|
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.
|
2020-10-14 00:35:16 +02:00
|
|
|
// Retries on EINTR.
|
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) {
|
|
|
|
return -1, syscall.EINVAL
|
|
|
|
}
|
|
|
|
if filepath.IsAbs(relPath) {
|
|
|
|
return -1, syscall.EINVAL
|
|
|
|
}
|
2017-12-05 23:31:07 +01:00
|
|
|
// Open the base dir (following symlinks)
|
2020-10-14 00:35:16 +02:00
|
|
|
dirfd, err := retryEINTR2(func() (int, error) {
|
|
|
|
return syscall.Open(baseDir, syscall.O_DIRECTORY|O_PATH, 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 {
|
2019-01-03 17:48:54 +01:00
|
|
|
dirfd2, err = Openat(dirfd, name, 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
|
|
|
}
|