The Path You Checked Is Not the File You Opened: Practical openat2 on Linux

2026-12-05来源 dev.toEnglish

A file upload service does the responsible thing. It takes a user-supplied name, joins it to an upload directory, calls realpath(), checks that the result still starts with the upload directory, and only then opens the file.

The check passes. The file that gets opened lives outside the upload directory — on a bad day, /etc/shadow.

Not because the prefix comparison was written backwards, and not because realpath() is broken. Because the check and the open are two separate path resolutions, and the path can change between them. The string is the same. The file is not.

I reproduced the race on Debian 13 with kernel 6.12.118. A regular file was validated inside the upload root, replaced with a symlink while the service slept, and then read as TOP SECRET from outside the root. The same directory, opened with openat2() and a resolve policy, refused with EXDEV.

This is the practical case for openat2(): not a new way to open files, but a way to tell the kernel the path rules while it resolves the path, instead of checking first and hoping nothing moves.

The check and the open are different operations

A pathname is not a handle. It is a recipe. Every syscall that takes a path walks the components again: it reads directories, follows symlinks, crosses mount points, and applies .. as it goes. realpath() performs that walk once and returns a string. open() performs it again, later, against whatever the filesystem looks like at that moment.

That gap is the vulnerability. It is usually called TOCTOU, time-of-check to time-of-use, but the name makes it sound like a scheduling accident. It is not. If an attacker can write to a directory component, the attacker controls what the second walk sees.

The usual defenses each cover less than they appear to:

  • O_NOFOLLOW applies only to the final component. Symlinks in parent directories are still followed.
  • openat() with a directory fd is better than concatenating strings, but it still resolves the remaining components normally. A swapped symlink is still a symlink.
  • chroot() changes the process root, but it is process-wide and not a per-open policy. It also has a long history of escapes when a process retains a directory fd from outside the new root.
  • A prefix check on the realpath() result is a check on a string. The next syscall does not have to agree with it.

What you want is not a better string comparison. You want the constraint enforced during the resolution that actually opens the file.

openat2: one syscall, one set of rules

openat2() was added in Linux 5.6. It is a superset of openat(): the same open flags, plus an extensible struct open_how that carries a resolve bitmask. The kernel applies those resolution rules while walking the path, and returns the fd only if the walk satisfies them.

There is no glibc wrapper. Call the syscall directly:

#define _GNU_SOURCE #include <fcntl.h> #include <linux/openat2.h> #include <sys/syscall.h> #include <unistd.h> struct open_how how = { .flags = O_RDONLY | O_CLOEXEC, .resolve = RESOLVE_BENEATH | RESOLVE_NO_MAGICLINKS, }; int fd = (int)syscall(SYS_openat2, rootfd, user_path, &how, sizeof(how)); if (fd < 0) { /* EINVAL, EXDEV, ELOOP, EAGAIN, ENOSYS, ... */ } 

Four details matter before the flags:

  1. Zero-fill the structure. New fields may be appended in future kernels. A zero value in an unknown field means "no behavior", which is what makes the size-based versioning work. Use a designated initializer or memset().
  2. Pass the real size. size is sizeof(struct open_how), not a hard-coded 24. The kernel uses it to distinguish "this caller does not know the field" from "this caller set the field to zero".
  3. Unknown flags are errors. Unlike open(), which ignores unknown flag bits, openat2() returns EINVAL for unknown or conflicting bits in how.flags. That is deliberate: silently ignoring a security-relevant flag is worse than failing.
  4. mode is conditional. A nonzero mode requires O_CREAT or O_TMPFILE, and bits outside 07777 are rejected. When those flags are absent, leave it at zero.

The kernel returns E2BIG if you set a nonzero field that the running kernel does not understand. If you build against newer headers and run on an older kernel, that is the error to expect.

The resolve flags, one by one

These values are stable ABI, defined in <linux/openat2.h>:

Flag Value What it prevents Typical error
RESOLVE_NO_XDEV 0x01 Crossing any mount point, including bind mounts EXDEV
RESOLVE_NO_MAGICLINKS 0x02 Traversal through procfs-style magic links such as /proc/pid/fd/* ELOOP
RESOLVE_NO_SYMLINKS 0x04 Any symlink in any component; implies no magic links ELOOP
RESOLVE_BENEATH 0x08 Absolute paths, .. escapes, and absolute symlinks that leave dirfd EXDEV
RESOLVE_IN_ROOT 0x10 Escapes by treating dirfd as / and clamping .. there clamped, not rejected
RESOLVE_CACHED 0x20 Nothing; it is a performance hint that fails with EAGAIN if a lookup is not cached EAGAIN

The important pair is BENEATH versus IN_ROOT. They solve related problems with different failure behavior:

  • RESOLVE_BENEATH rejects an escape. ../outside/secret returns EXDEV. An absolute path returns EXDEV even if the path happens to point inside the root. An absolute symlink target also returns EXDEV. If you want a strict "this name must stay under this directory" policy, this is the flag.
  • RESOLVE_IN_ROOT clamps instead. The directory fd becomes the root for this resolution, so /etc/hostname is looked up as <dirfd>/etc/hostname, and .. at the top stays at the top. That is useful when you are implementing a chroot-like view or resolving paths inside an extracted image, but it is not the same promise as BENEATH.

RESOLVE_BENEATH currently disables magic links as a side effect, but the man page warns that this may change. Set RESOLVE_NO_MAGICLINKS explicitly if you depend on it. RESOLVE_NO_SYMLINKS already implies NO_MAGICLINKS.

There is one deliberate exception worth knowing: if the final component is a symlink or magic link, and how.flags contains both O_PATH and O_NOFOLLOW, the kernel can return an O_PATH fd that refers to the link itself instead of following it. That is useful for inspection tools. It is not what you want for a normal file open.

A complete example you can run

The program below has two modes. legacy performs the check-then-open pattern and sleeps between them so the race is easy to see. beneath, inroot, and nofollow use openat2() with different resolve sets.

#define _GNU_SOURCE #include <errno.h> #include <fcntl.h> #include <limits.h> #include <linux/openat2.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/syscall.h> #include <unistd.h> static int open_under_root(int rootfd, const char *path, __u64 resolve) { struct open_how how = { .flags = O_RDONLY | O_CLOEXEC, .resolve = resolve, }; return (int)syscall(SYS_openat2, rootfd, path, &how, sizeof(how)); } static void show(int fd) { char buf[128] = {0}; ssize_t n = read(fd, buf, sizeof(buf) - 1); if (n < 0) { perror("read"); return; } printf("read(%zd): %s\n", n, buf); } int main(int argc, char **argv) { const char *mode = argc > 1 ? argv[1] : "beneath"; const char *rel = argc > 2 ? argv[2] : "upload.txt"; const char *root = getenv("LAB_ROOT"); if (!root) root = "/tmp/openat2-lab/root"; int rootfd = open(root, O_PATH | O_DIRECTORY | O_CLOEXEC); if (rootfd < 0) { perror("open root"); return 1; } if (strcmp(mode, "legacy") == 0) { char full[PATH_MAX], resolved[PATH_MAX], rootreal[PATH_MAX]; snprintf(full, sizeof(full), "%s/%s", root, rel); if (!realpath(root, rootreal) || !realpath(full, resolved)) { perror("realpath"); return 1; } size_t n = strlen(rootreal); if (strncmp(resolved, rootreal, n) != 0 || (resolved[n] != '/' && resolved[n] != '\0')) { fprintf(stderr, "rejected outside root: %s\n", resolved); return 2; } printf("validated: %s\n", resolved); if (getenv("LAB_SLEEP")) { fflush(stdout); sleep(3); } int fd = open(full, O_RDONLY | O_CLOEXEC); if (fd < 0) { perror("open"); return 1; } show(fd); return 0; } __u64 resolve = RESOLVE_BENEATH | RESOLVE_NO_MAGICLINKS; if (strcmp(mode, "nofollow") == 0) resolve |= RESOLVE_NO_SYMLINKS; if (strcmp(mode, "inroot") == 0) resolve = RESOLVE_IN_ROOT | RESOLVE_NO_MAGICLINKS; int fd = open_under_root(rootfd, rel, resolve); if (fd < 0) { printf("openat2 failed: %s (errno %d)\n", strerror(errno), errno); return 1; } show(fd); return 0; } 

Build it and create a root directory with a file inside, plus a file outside that should never be readable through the root:

rm -rf /tmp/openat2-lab mkdir -p /tmp/openat2-lab/root /tmp/openat2-lab/outside gcc -Wall -Wextra -O2 -o /tmp/openat2-lab/safeopen safeopen.c printf 'benign file\n' > /tmp/openat2-lab/root/upload.txt printf 'TOP SECRET\n' > /tmp/openat2-lab/outside/secret.txt 

Now run the legacy check in the background. The program prints validated: after realpath() succeeds, then sleeps for three seconds before calling open().

LAB_ROOT=/tmp/openat2-lab/root LAB_SLEEP=1 \ /tmp/openat2-lab/safeopen legacy upload.txt > /tmp/openat2-lab/legacy.out & pid=$! # Wait until the check has passed, then swap the file for a symlink. until grep -q '^validated:' /tmp/openat2-lab/legacy.out 2>/dev/null; do sleep 0.1 done rm -f /tmp/openat2-lab/root/upload.txt ln -s ../outside/secret.txt /tmp/openat2-lab/root/upload.txt wait "$pid" cat /tmp/openat2-lab/legacy.out 

Measured output on this machine:

validated: /tmp/openat2-lab/root/upload.txt read(11): TOP SECRET 

The check was correct. The open was a normal open() call. The file was outside the directory the program promised to stay inside.

Put the swapped symlink back in place and try the openat2() version:

rm -f /tmp/openat2-lab/root/upload.txt ln -s ../outside/secret.txt /tmp/openat2-lab/root/upload.txt /tmp/openat2-lab/safeopen beneath upload.txt /tmp/openat2-lab/safeopen nofollow upload.txt 
openat2 failed: Invalid cross-device link (errno 18) openat2 failed: Too many levels of symbolic links (errno 40) 

EXDEV is errno 18: the kernel detected that resolving the symlink would leave the directory named by dirfd. ELOOP is errno 40: RESOLVE_NO_SYMLINKS refuses the link before it can resolve at all. Those are policy denials, not I/O failures. An application should log them and return a client error, not retry with a looser flag.

The absolute-path behavior is also visible:

/tmp/openat2-lab/safeopen beneath /etc/hostname /tmp/openat2-lab/safeopen inroot /etc/hostname 
openat2 failed: Invalid cross-device link (errno 18) openat2 failed: No such file or directory (errno 2) 

BENEATH rejects the absolute path outright. IN_ROOT treats it as <root>/etc/hostname, which does not exist in this lab. That difference is the whole reason both flags exist.

Traps that survive the first fix

ENOSYS means the kernel is too old, not that you should go back to realpath

openat2() needs Linux 5.6 or newer. On an older kernel the syscall returns ENOSYS. The wrong response is to fall back to realpath() plus open(), because that reintroduces the race on exactly the systems that need the protection most.

The fallback that preserves the guarantee is a component-by-component walk: keep a directory fd, split the relative path, reject . and .., and open each component with O_PATH | O_NOFOLLOW | O_DIRECTORY before moving to the next. The final component is opened with O_NOFOLLOW. Each opened directory fd pins that component, so renaming a parent later does not redirect the walk. It is more code, and it has to handle empty components and trailing slashes carefully, but it is the safe primitive.

If you would rather not maintain that code, libpathrs packages these semantics for Rust, Go, Python, and C. It is a reasonable dependency for anything that resolves untrusted paths.

Your seccomp profile may not allow the syscall

On x86_64, openat2 is syscall 437, but the number is architecture-specific. Use SYS_openat2 in C, and use the syscall name in security policy.

Docker's current default seccomp profile includes openat2, so a normal container can call it. A hand-written default-deny profile, an older runtime profile, or a restrictive Kubernetes seccomp profile may not. A blocked syscall under Docker's default action surfaces as EPERM, which looks like a permissions bug rather than a policy bug. If openat2() fails with EPERM while the same path works in a shell, check the seccomp profile before you change the code. Do not reach for --privileged to test it; run a tiny program with a custom profile that allows just this syscall.

BENEATH is a path rule, not a mount policy

RESOLVE_BENEATH constrains how the path is walked. It does not stop a bind mount that already exists inside the tree from exposing another filesystem. If /srv/root/data is a bind mount of /etc, then data/passwd is beneath /srv/root in path terms. Add RESOLVE_NO_XDEV when crossing mount points is not acceptable, and remember that it also rejects ordinary nested mounts, which may break legitimate layouts.

The resolve flags do not replace permissions or LSMs

openat2() answers "which file did this path resolve to?" It does not answer "should this process be allowed to read it?" DAC permissions still apply. A process running as root can still read the file if the path policy allows it. Landlock, AppArmor, and seccomp answer different questions; use them together rather than treating openat2() as a sandbox.

EAGAIN is part of the contract

If RESOLVE_BENEATH or RESOLVE_IN_ROOT cannot prove that a .. component stayed inside during a concurrent rename, the kernel returns EAGAIN rather than guessing. A retry loop with a small cap is appropriate. RESOLVE_CACHED also returns EAGAIN by design: it means "this lookup would have required I/O", so retry without the flag.

A directory fd is only as trustworthy as the open that produced it

Open the root once with O_PATH | O_DIRECTORY | O_CLOEXEC and keep it for the lifetime of the request. Do not accept a directory fd from an untrusted process. openat2() enforces that the path stays beneath the fd you passed; it cannot know whether that fd itself points where you think it does.

A migration checklist

  • Replace every realpath()-then-open() sequence that handles user-controlled paths. The check is not the fix; the single resolution is.
  • For "must stay under this directory", use RESOLVE_BENEATH | RESOLVE_NO_MAGICLINKS. Add RESOLVE_NO_SYMLINKS if symlinks are not part of the expected layout.
  • For "treat this directory as /", use RESOLVE_IN_ROOT, and be clear that it clamps rather than rejects.
  • Open the root with O_PATH | O_DIRECTORY | O_CLOEXEC and resolve every request relative to it.
  • Map EXDEV and ELOOP to a denial, ENOSYS to the fallback path, EAGAIN to a bounded retry, and EPERM to a seccomp investigation.
  • Keep O_NOFOLLOW on the final open as defense in depth, even when the resolve flags already cover it.
  • Log readlink("/proc/self/fd/<fd>") after a successful open if you need an audit trail. It shows the current path of the opened inode, or (deleted) if the name is gone. Do not log the requested string and call it evidence.
  • Test with a symlink swap, a .. escape, an absolute path, and a bind mount. A unit test that only uses a normal filename does not exercise the policy.

The useful mental shift is small and permanent: a path is an instruction to resolve, not a reference to a file. Once the kernel is doing the resolution and the policy in the same walk, the check-then-open race stops being a matter of timing.

Sources

Tested on Debian 13, kernel 6.12.118+deb13-amd64, gcc 14.2.0. The exploit and the denials above are measured output from the program in this article, not illustrative pseudocode.

原文:https://www.a8q9.cn/en/article/the-path-you-checked-is-not-the-file-you-opened-practical-openat2-on-linux-4e973b.html

相关文章