Download this file
| 1 | package provider |
| 2 | |
| 3 | import ( |
| 4 | "os" |
| 5 | "path/filepath" |
| 6 | "strings" |
| 7 | |
| 8 | "golang.org/x/sys/unix" |
| 9 | ) |
| 10 | |
| 11 | // openNoLinks opens path refusing a symbolic link in any component |
| 12 | // (O_NOFOLLOW_ANY, macOS 11 and later). |
| 13 | func openNoLinks(path string, flags int) (int, error) { |
| 14 | return unix.Open(path, flags|unix.O_NOFOLLOW_ANY, 0) |
| 15 | } |
| 16 | |
| 17 | // OpenBeneath opens rel beneath the open directory dir: no symbolic link |
| 18 | // in any component (O_NOFOLLOW_ANY), and rel may not climb out of dir. |
| 19 | func OpenBeneath(dir *os.File, rel string, flags int) (*os.File, error) { |
| 20 | if filepath.IsAbs(rel) || rel == ".." || strings.HasPrefix(rel, "../") || strings.Contains(rel, "/../") { |
| 21 | return nil, ErrPolicy |
| 22 | } |
| 23 | fd, err := unix.Openat(int(dir.Fd()), rel, flags|unix.O_NOFOLLOW_ANY|unix.O_CLOEXEC, 0) |
| 24 | if err != nil { |
| 25 | return nil, err |
| 26 | } |
| 27 | return os.NewFile(uintptr(fd), filepath.Join(dir.Name(), rel)), nil |
| 28 | } |
| 29 | |