Articles / Go

  • go
  • linux
  • security
  • openat2
  • symlinks
  • path-traversal

filepath.Clean Won't Stop Symlink Escapes in Go, but openat2 Will

A cleaned path can still open /etc/passwd. Suppose a service stores user files beneath /srv/uploads. A request supplies avatars/alice.png, and the service cleans the path, checks that it still looks like it's inside the upload directory, and opens it.

clean := filepath.Clean(filepath.Join(uploadDir, name))
if !strings.HasPrefix(clean, uploadDir+string(filepath.Separator)) {
	return errors.New("path escapes upload directory")
}

f, err := os.Open(clean)

This catches an obvious ../../etc/passwd. What it can't tell you is whether the file the kernel actually opens is beneath /srv/uploads.

An attacker who can create /srv/uploads/avatars as a symbolic link to /etc can request avatars/passwd. The cleaned path is still the thoroughly respectable /srv/uploads/avatars/passwd. Path cleaning did its job; unfortunately, its job was only string manipulation.

Why a clean-looking name tells you nothing about the file

filepath.Clean does lexical simplification. It removes redundant separators and resolves . and .. components without ever looking at the filesystem. It has no way of knowing that a component is a symbolic link, a mount point, or something another process is busy renaming.

The usual patches don't close the gap either:

  • Replacing the prefix check with filepath.Rel fixes several string-comparison mistakes, but not this one.
  • Calling filepath.EvalSymlinks before os.Open isn't enough when an attacker can modify the directory tree. They can change a link after validation and before the open.
  • O_NOFOLLOW is useful but narrower than its name suggests. On Linux it prevents following a symbolic link only in the final pathname component.

That check-then-use window may be tiny, but computers are rather good at aiming for tiny windows over and over again.

As for O_NOFOLLOW: in avatars/alice.png, the link can hide in avatars and still get followed. The Linux open(2) documentation spells this out.

openat2 makes containment part of the lookup itself

Linux 5.6 introduced openat2, an extended relative-open system call. It takes a directory file descriptor plus a set of resolution rules, and the kernel applies those rules while walking every component of the pathname. The one that matters here is RESOLVE_BENEATH: resolution fails if a component would escape above or outside the directory that descriptor represents.

That moves the security boundary. Instead of asking, "Did my earlier string check describe a safe path?", the program asks the kernel, "Open this only if the resolution itself remains beneath this directory." Symlink lookup and the containment decision happen within the same kernel operation.

Here's a Linux-only helper that opens a file for reading beneath a trusted root:

//go:build linux

package confined

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"

	"golang.org/x/sys/unix"
)

func OpenBeneath(root, name string) (*os.File, error) {
	if name == "" {
		return nil, errors.New("empty path")
	}
	if filepath.IsAbs(name) {
		return nil, errors.New("absolute paths are not accepted")
	}

	rootFD, err := unix.Open(
		root,
		unix.O_PATH|unix.O_DIRECTORY|unix.O_CLOEXEC,
		0,
	)
	if err != nil {
		return nil, fmt.Errorf("open root %q: %w", root, err)
	}
	defer unix.Close(rootFD)

	how := &unix.OpenHow{
		Flags: uint64(unix.O_RDONLY | unix.O_CLOEXEC),
		Resolve: uint64(
			unix.RESOLVE_BENEATH |
				unix.RESOLVE_NO_MAGICLINKS,
		),
	}

	fd, err := unix.Openat2(rootFD, name, how)
	if err != nil {
		switch {
		case errors.Is(err, unix.ENOSYS):
			return nil, fmt.Errorf("openat2 is unavailable: %w", err)
		case errors.Is(err, unix.EXDEV), errors.Is(err, unix.ELOOP):
			return nil, fmt.Errorf("path escaped root or used a forbidden link: %w", err)
		default:
			return nil, fmt.Errorf("open %q beneath root: %w", name, err)
		}
	}

	f := os.NewFile(uintptr(fd), name)
	if f == nil {
		_ = unix.Close(fd)
		return nil, errors.New("could not construct os.File")
	}
	return f, nil
}

O_PATH creates a lightweight reference to the root directory. It's an anchor for later pathname resolution; you can't read directory entries through it. The descriptor also keeps identifying that directory if it's renamed while the operation is in progress.

RESOLVE_BENEATH rejects absolute input and absolute symbolic links, so the explicit filepath.IsAbs check is mostly there to give a clearer API-level error message.

Hang on, the helper never cleans the untrusted name? Correct, and on purpose. Components such as .. go to the kernel as they are, and the kernel can decide whether their actual resolution escapes the root. Cleaning first would only bring back the string guesswork we just stopped trusting.

RESOLVE_NO_MAGICLINKS blocks Linux magic links, notably the entries under /proc/PID/fd. The current RESOLVE_BENEATH behaviour disables them too, but the openat2(2) manual explicitly recommends asking for this rule instead of leaning on that incidental behaviour.

Deciding whether ordinary symlinks are allowed at all

The example allows an ordinary symlink as long as its target stays beneath the root. So current -> releases/2026-09 can work, while current -> /etc can't. For content trees and deployment directories, that's often the policy you want.

If no untrusted path component should ever be a symlink, add unix.RESOLVE_NO_SYMLINKS. Unlike O_NOFOLLOW, it applies to every component:

Resolve: uint64(
	unix.RESOLVE_BENEATH |
		unix.RESOLVE_NO_MAGICLINKS |
		unix.RESOLVE_NO_SYMLINKS,
),

That stricter rule can reject perfectly legitimate layouts, so add it because you have an actual security policy, rather than a vague fondness for more flags.

Mounts are a separate question. RESOLVE_BENEATH can traverse a mount or bind mount located beneath the root. Add RESOLVE_NO_XDEV if crossing one must fail, but expect it to clash with some container, package and deployment arrangements.

Then again, an attacker who can create mounts generally has more power than an ordinary account that can only add symlinks.

Errors and fallbacks are part of the boundary

Each failure mode has its own errno, and it's worth knowing which is which:

  • An escape detected under RESOLVE_BENEATH normally produces EXDEV.
  • Forbidden symbolic or magic links can produce ELOOP.
  • The kernel may return EAGAIN if it cannot prove containment during a racing lookup; a caller may retry a bounded number of times or simply reject the request.

For a file-serving endpoint, treating EAGAIN as a failed request is often the calmer choice.

openat2 returns ENOSYS on kernels older than Linux 5.6, and a restrictive seccomp profile may block it as well. Do not silently fall back to filepath.Clean followed by os.Open, because that turns a deployment incompatibility into a security vulnerability. Pick one of these instead:

  • refuse to start;
  • disable the affected feature;
  • use a carefully implemented component-by-component openat walk.

Go 1.24 already has a portable higher-level option

If your application uses Go 1.24 or later, os.OpenRoot and os.Root should usually be the first choice. They give you traversal-resistant operations beneath an opened directory and work across the supported operating systems:

root, err := os.OpenRoot("/srv/uploads")
if err != nil {
	return err
}
defer root.Close()

f, err := root.Open(name)
if err != nil {
	return err
}
defer f.Close()

The standard-library version follows symlinks that stay inside the root and rejects ones that escape. Calling openat2 directly is still useful when a Linux-specific service needs explicit policies such as RESOLVE_NO_SYMLINKS or RESOLVE_NO_XDEV, or when the exact error behaviour matters.

Neither API freezes file contents or stops another process modifying a file once it's open. The returned descriptor gives you something narrower and more precise: it refers to the object that safely resolved beneath the chosen root. That's the guarantee filepath.Clean was never designed to make.