Initial commit

Proof-of-concept implementation. Bugs will occur.
This commit is contained in:
2026-02-12 01:18:46 +03:00
commit 13ac06c14b
553 changed files with 253003 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
package openat
import (
"golang.org/x/sys/unix"
)
// OpenSymlinkAware is a symlink-aware syscall.Open replacement.
//
// What it does:
//
// 1. Open baseDir (usually an absolute path), following symlinks.
//
// The user may have set up the directory tree with symlinks,
// that's not neccessarily malicous, but a normal use case.
//
// 2. Open path (must be a relative path) within baseDir, rejecting symlinks with ELOOP.
//
// On Linux, it calls openat2(2) with RESOLVE_NO_SYMLINKS. This prevents following
// symlinks in any component of the path.
//
// On other platforms, it calls openat(2) with O_NOFOLLOW.
// TODO: This is insecure as O_NOFOLLOW only affects the final path component.
func OpenSymlinkAware(baseDir string, path string, flags int, mode uint32) (fd int, err error) {
// Passing an absolute path is a bug in the caller
if len(path) > 0 && path[0] == '/' {
return -1, unix.EINVAL
}
baseFd, err := unix.Open(baseDir, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
if err != nil {
return -1, err
}
defer unix.Close(baseFd)
return openatNoSymlinks(baseFd, path, flags, mode)
}

View File

@@ -0,0 +1,20 @@
package openat
import (
"golang.org/x/sys/unix"
)
func openatNoSymlinks(dirfd int, path string, flags int, mode uint32) (fd int, err error) {
how := unix.OpenHow{
// os/exec expects all fds to have O_CLOEXEC or it will leak them to subprocesses.
Flags: uint64(flags) | unix.O_CLOEXEC,
Mode: uint64(mode),
Resolve: unix.RESOLVE_NO_SYMLINKS,
}
fd, err = unix.Openat2(dirfd, path, &how)
if err != nil && err == unix.ENOSYS {
flags |= unix.O_NOFOLLOW | unix.O_CLOEXEC
fd, err = unix.Openat(dirfd, path, flags, mode)
}
return fd, err
}

View File

@@ -0,0 +1,15 @@
//go:build !linux
package openat
import (
"golang.org/x/sys/unix"
)
// TODO: This is insecure as O_NOFOLLOW only affects the final path component.
// See https://github.com/rfjakob/gocryptfs/issues/165 for how this could be handled.
func openatNoSymlinks(dirfd int, path string, flags int, mode uint32) (fd int, err error) {
// os/exec expects all fds to have O_CLOEXEC or it will leak them to subprocesses.
flags |= unix.O_NOFOLLOW | unix.O_CLOEXEC
return unix.Openat(dirfd, path, flags, mode)
}