namei: openat2(2) path resolution restrictions
Subsystems (21)
v11 cover namei: openat2(2) path resolution restrictions
This patch is being developed here (with snapshots of each series version being stashed in separate branches with names of the form "resolveat/vX-summary"):
<https://github.com/cyphar/linux/tree/resolveat/master>
Patch changelog:
v11:
* Fix checkpatch.pl errors and warnings where reasonable.
* Minor cleanup to pr_warn logging for may_open_magiclink().
* Drop kselftests patch to handle %m formatting correctly, and send it through the kselftests tree directly. [Shuah Khan]
v10:
* Ensure that unlazy_walk() will fail if we are in a scoped walk and the caller has zeroed nd->root (this happens in a few places, I'm not sure why because unlazy_walk() does legitimize_path() already). In this case we need to go through path_init() again to reset it (otherwise we will have a breakout because set_root() will breakout).
* Also add a WARN_ON (and return -ENOTRECOVERABLE) if LOOKUP_IN_ROOT is set and we are in set_root() -- which should never happen and will cause a breakout.
* Make changes suggested by Al Viro:
* Remove nd->{opath_mask,acc_mode} by moving all of the magic-link permission logic be done after trailing_symlink() (with trailing_magiclink()) only within path_openat().
* Introduce LOOKUP_MAGICLINK_JUMPED to be able to detect magic-link jumps done with nd_jump_link() (so we don't end up blocking other LOOKUP_JUMPED cases).
* Simplify all of the path_init() changes to make the code far less confusing. dirfd_path_init() turns out to be un-necessary.
* Make openat2(2) also -EINVAL on unknown how->flags. [Dmitry V. Levin]
* Clean up bad definitions of O_EMPTYPATH on architectures where O_* flags are subtly different to <asm-generic/fcntl.h>.
* Switch away from passing a struct to build_open_flags() and instead just copy the one field we need to temporarily modify (how->flags). Also fix a bug in OPENHOW_MODE. [Rasmus Villemoes]
* Fix syscall linkages and switch to 437. [Arnd Bergmann]
* Clean up text in commit messages and the cover-letter. [Rolf Eike Beer]
* Fix openat2 selftest makefile. [Michael Ellerman]
The need for some sort of control over VFS's path resolution (to avoid malicious paths resulting in inadvertent breakouts) has been a very long-standing desire of many userspace applications. This patchset is a revival of Al Viro's old AT_NO_JUMPS[1,2] patchset (which was a variant of David Drysdale's O_BENEATH patchset[3] which was a spin-off of the Capsicum project[4]) with a few additions and changes made based on the previous discussion within [5] as well as others I felt were useful.
In line with the conclusions of the original discussion of AT_NO_JUMPS, the flag has been split up into separate flags. However, instead of being an openat(2) flag it is provided through a new syscall openat2(2) which provides several other improvements to the openat(2) interface (see the patch description for more details). The following new LOOKUP_* flags are added:
* LOOKUP_NO_XDEV blocks all mountpoint crossings (upwards, downwards, or through absolute links). Absolute pathnames alone in openat(2) do not trigger this.
* LOOKUP_NO_MAGICLINKS blocks resolution through /proc/$pid/fd-style links. This is done by blocking the usage of nd_jump_link() during resolution in a filesystem. The term "magic-links" is used to match with the only reference to these links in Documentation/, but I'm happy to change the name.
It should be noted that this is different to the scope of ~LOOKUP_FOLLOW in that it applies to all path components. However, you can do openat2(NO_FOLLOW|NO_MAGICLINKS) on a magic-link and it will *not* fail (assuming that no parent component was a magic-link), and you will have an fd for the magic-link.
* LOOKUP_BENEATH disallows escapes to outside the starting dirfd's tree, using techniques such as ".." or absolute links. Absolute paths in openat(2) are also disallowed. Conceptually this flag is to ensure you "stay below" a certain point in the filesystem tree -- but this requires some additional to protect against various races that would allow escape using "..".
Currently LOOKUP_BENEATH implies LOOKUP_NO_MAGICLINKS, because it can trivially beam you around the filesystem (breaking the protection). In future, there might be similar safety checks done as in LOOKUP_IN_ROOT, but that requires more discussion.
In addition, two new flags are added that expand on the above ideas:
* LOOKUP_NO_SYMLINKS does what it says on the tin. No symlink resolution is allowed at all, including magic-links. Just as with LOOKUP_NO_MAGICLINKS this can still be used with NOFOLLOW to open an fd for the symlink as long as no parent path had a symlink component.
* LOOKUP_IN_ROOT is an extension of LOOKUP_BENEATH that, rather than blocking attempts to move past the root, forces all such movements to be scoped to the starting point. This provides chroot(2)-like protection but without the cost of a chroot(2) for each filesystem operation, as well as being safe against race attacks that chroot(2) is not.
If a race is detected (as with LOOKUP_BENEATH) then an error is generated, and similar to LOOKUP_BENEATH it is not permitted to cross magic-links with LOOKUP_IN_ROOT.
The primary need for this is from container runtimes, which currently need to do symlink scoping in userspace[6] when opening paths in a potentially malicious container. There is a long list of CVEs that could have bene mitigated by having RESOLVE_THIS_ROOT (such as CVE-2017-1002101, CVE-2017-1002102, CVE-2018-15664, and CVE-2019-5736, just to name a few).
And further, several semantics of file descriptor "re-opening" are now changed to prevent attacks like CVE-2019-5736 by restricting how magic-links can be resolved (based on their mode). This required some other changes to the semantics of the modes of O_PATH file descriptor's associated /proc/self/fd magic-links. openat2(2) has the ability to further restrict re-opening of its own O_PATH fds, so that users can make even better use of this feature.
Finally, O_EMPTYPATH was added so that users can do /proc/self/fd-style re-opening without depending on procfs. The new restricted semantics for magic-links are applied here too.
In order to make all of the above more usable, I'm working on libpathrs[7] which is a C-friendly library for safe path resolution. It features a userspace-emulated backend if the kernel doesn't support openat2(2). Hopefully we can get userspace to switch to using it, and thus get openat2(2) support for free once it's ready.
[1]: https://lwn.net/Articles/721443/
[2]: https://lore.kernel.org/patchwork/patch/784221/
[3]: https://lwn.net/Articles/619151/
[4]: https://lwn.net/Articles/603929/
[5]: https://lwn.net/Articles/723057/
[6]: https://github.com/cyphar/filepath-securejoin
[7]: https://github.com/openSUSE/libpathrs
Aleksa Sarai (8):
namei: obey trailing magic-link DAC permissions
procfs: switch magic-link modes to be more sane
open: O_EMPTYPATH: procfs-less file descriptor re-opening
namei: O_BENEATH-style path resolution flags
namei: LOOKUP_IN_ROOT: chroot-like path resolution
namei: aggressively check for nd->root escape on ".." resolution
open: openat2(2) syscall
selftests: add openat2(2) selftests
Documentation/filesystems/path-lookup.rst | 12 +- arch/alpha/include/uapi/asm/fcntl.h | 1 + arch/alpha/kernel/syscalls/syscall.tbl | 1 + arch/arm/tools/syscall.tbl | 1 + arch/arm64/include/asm/unistd.h | 2 +- arch/arm64/include/asm/unistd32.h | 2 + arch/ia64/kernel/syscalls/syscall.tbl | 1 + arch/m68k/kernel/syscalls/syscall.tbl | 1 + arch/microblaze/kernel/syscalls/syscall.tbl | 1 + arch/mips/kernel/syscalls/syscall_n32.tbl | 1 + arch/mips/kernel/syscalls/syscall_n64.tbl | 1 + arch/mips/kernel/syscalls/syscall_o32.tbl | 1 + arch/parisc/include/uapi/asm/fcntl.h | 39 +- arch/parisc/kernel/syscalls/syscall.tbl | 1 + arch/powerpc/kernel/syscalls/syscall.tbl | 1 + arch/s390/kernel/syscalls/syscall.tbl | 1 + arch/sh/kernel/syscalls/syscall.tbl | 1 + arch/sparc/include/uapi/asm/fcntl.h | 1 + arch/sparc/kernel/syscalls/syscall.tbl | 1 + arch/x86/entry/syscalls/syscall_32.tbl | 1 + arch/x86/entry/syscalls/syscall_64.tbl | 1 + arch/xtensa/kernel/syscalls/syscall.tbl | 1 + fs/fcntl.c | 2 +- fs/internal.h | 1 + fs/namei.c | 270 ++++++++++-- fs/open.c | 112 ++++- fs/proc/base.c | 20 +- fs/proc/fd.c | 23 +- fs/proc/namespaces.c | 2 +- include/linux/fcntl.h | 17 +- include/linux/fs.h | 8 +- include/linux/namei.h | 9 + include/linux/syscalls.h | 17 +- include/uapi/asm-generic/fcntl.h | 4 + include/uapi/asm-generic/unistd.h | 5 +- include/uapi/linux/fcntl.h | 42 ++ tools/testing/selftests/Makefile | 1 + tools/testing/selftests/memfd/memfd_test.c | 7 +- tools/testing/selftests/openat2/.gitignore | 1 + tools/testing/selftests/openat2/Makefile | 8 + tools/testing/selftests/openat2/helpers.c | 162 +++++++ tools/testing/selftests/openat2/helpers.h | 116 +++++ .../testing/selftests/openat2/linkmode_test.c | 333 +++++++++++++++ .../selftests/openat2/rename_attack_test.c | 127 ++++++ .../testing/selftests/openat2/resolve_test.c | 402 ++++++++++++++++++ 45 files changed, 1655 insertions(+), 107 deletions(-) create mode 100644 tools/testing/selftests/openat2/.gitignore create mode 100644 tools/testing/selftests/openat2/Makefile create mode 100644 tools/testing/selftests/openat2/helpers.c create mode 100644 tools/testing/selftests/openat2/helpers.h create mode 100644 tools/testing/selftests/openat2/linkmode_test.c create mode 100644 tools/testing/selftests/openat2/rename_attack_test.c create mode 100644 tools/testing/selftests/openat2/resolve_test.c
Signature · 1 line
2.22.0
PATCH v11 1/8 namei: obey trailing magic-link DAC permissions
The ability for userspace to "re-open" file descriptors through /proc/self/fd has been a very useful tool for all sorts of usecases (container runtimes are one common example). However, the current interface for doing this has resulted in some pretty subtle security holes. Userspace can re-open a file descriptor with more permissions than the original, which can result in cases such as /proc/$pid/exe being re-opened O_RDWR at a later date even though (by definition) /proc/$pid/exe cannot be opened for writing. When combined with O_PATH the results can get even more confusing.
We cannot block this outright. Aside from userspace already depending on it, it's a useful feature which can actually increase the security of userspace. For instance, LXC keeps an O_PATH of the container's /dev/pts/ptmx that gets re-opened to create new ptys and then uses TIOCGPTPEER to get the slave end. This allows for pty allocation without resolving paths inside an (untrusted) container's rootfs. There isn't a trivial way of doing this that is as straight-forward and safe as O_PATH re-opening.
Instead we have to restrict it in such a way that it doesn't break (good) users but does block potential attackers. The solution applied in this patch is to restrict *re-opening* (not resolution through) magic-links by requiring that mode of the link be obeyed. Normal symlinks have modes of a+rwx but magic-links have other modes. These magic-link modes were historically ignored during path resolution, but they've now been re-purposed for more useful ends.
It is also necessary to define semantics for the mode of an O_PATH descriptor, since re-opening a magic-link through an O_PATH needs to be just as restricted as the corresponding magic-link -- otherwise the above protection can be bypassed. There are two distinct cases:
1. The target is a regular file (not a magic-link). Userspace depends on being able to re-open the O_PATH of a regular file, so we must define the mode to be a+rwx.
2. The target is a magic-link. In this case, we simply copy the mode of the magic-link. This results in an O_PATH of a magic-link effectively acting as a no-op in terms of how much re-opening privileges a process has.
CAP_DAC_OVERRIDE can be used to override all of these restrictions, but we only permit &init_userns's capabilities to affect these semantics. The reason for this is that there isn't a clear way to track what user_ns is the original owner of a given O_PATH chain -- thus an unprivileged user could create a new userns and O_PATH the file descriptor, owning it. All signs would indicate that the user really does have CAP_DAC_OVERRIDE over the new descriptor and the protection would be bypassed. We thus opt for the more conservative approach.
I have run this patch on several machines for several days. So far, the only processes which have hit this case ("loadkeys" and "kbd_mode" from the kbd package[1]) gracefully handle the permission error and do not cause any user-visible problems. In order to give users a heads-up, a warning is output to dmesg whenever may_open_magiclink() refuses access.
[1]: http://git.altlinux.org/people/legion/packages/kbd.git
--- Documentation/filesystems/path-lookup.rst | 12 +-- fs/internal.h | 1 + fs/namei.c | 105 +++++++++++++++++++--- fs/open.c | 3 +- fs/proc/fd.c | 23 ++++- include/linux/fs.h | 4 + include/linux/namei.h | 1 + 7 files changed, 130 insertions(+), 19 deletions(-)
Documentation/filesystems/path-lookup.rst +7 -5
@@ -1310,12 +1310,14 @@ longer needed. ``LOOKUP_JUMPED`` means that the current dentry was chosen not because it had the right name but for some other reason. This happens when following "``..``", following a symlink to ``/``, crossing a mount point -or accessing a "``/proc/$PID/fd/$FD``" symlink. In this case the -filesystem has not been asked to revalidate the name (with -``d_revalidate()``). In such cases the inode may still need to be -revalidated, so ``d_op->d_weak_revalidate()`` is called if +or accessing a "``/proc/$PID/fd/$FD``" symlink (also known as a "magic +link"). In this case the filesystem has not been asked to revalidate the +name (with ``d_revalidate()``). In such cases the inode may still need +to be revalidated, so ``d_op->d_weak_revalidate()`` is called if ``LOOKUP_JUMPED`` is set when the look completes - which may be at the -final component or, when creating, unlinking, or renaming, at the penultimate component. +final component or, when creating, unlinking, or renaming, at the +penultimate component. ``LOOKUP_MAGICLINK_JUMPED`` is set alongside +``LOOKUP_JUMPED`` if a magic-link was traversed. Final-component flags ~~~~~~~~~~~~~~~~~~~~~
fs/internal.h +1 -0
@@ -119,6 +119,7 @@ struct open_flags {int acc_mode;int intent;int lookup_flags; +fmode_t opath_mask; };extern struct file *do_filp_open (int dfd,struct filename *pathname,const struct open_flags *op);
fs/namei.c +94 -11
136 lines not on this page · raw message
fs/open.c +2 -1
@@ -982,8 +982,9 @@ static inline int build_open_flags(int flags, umode_t mode, struct open_flags *o acc_mode |=MAY_APPEND ; op->acc_mode = acc_mode; - op->intent = flags &O_PATH ?0 :LOOKUP_OPEN ; +/* For O_PATH backwards-compatibility we default to an all-set mask. */ + op->opath_mask =FMODE_PATH_READ |FMODE_PATH_WRITE ;if (flags &O_CREAT ) { op->intent |=LOOKUP_CREATE ;
fs/proc/fd.c +21 -2
@@ -104,11 +104,30 @@ static void tid_fd_update_inode(struct task_struct *task, struct inode *inode,task_dump_owner (task,0 , &inode->i_uid, &inode->i_gid);if (S_ISLNK (inode->i_mode)) { +/* +* Always set +x (depending on the fmode type), since there +* currently aren't FMODE_PATH_EXEC restrictions and there is +* no O_MAYEXEC yet. This might change in the future, in which +* case we will restrict +x. +*/ unsigned i_mode =S_IFLNK ; +if (f_mode &FMODE_PATH ) + i_mode |=S_IXGRP ; +else + i_mode |=S_IXUSR ; +/* +* Construct the mode bits based on the open-mode. The u+rwx +* bits are for "ordinary" open modes while g+rwx are for +* O_PATH modes. +*/ if (f_mode &FMODE_READ ) - i_mode |=S_IRUSR |S_IXUSR ; + i_mode |=S_IRUSR ;if (f_mode &FMODE_WRITE ) - i_mode |=S_IWUSR |S_IXUSR ; + i_mode |=S_IWUSR ; +if (f_mode &FMODE_PATH_READ ) + i_mode |=S_IRGRP ; +if (f_mode &FMODE_PATH_WRITE ) + i_mode |=S_IWGRP ; inode->i_mode = i_mode; }security_task_to_inode (task, inode);
include/linux/fs.h +4 -0
@@ -173,6 +173,10 @@ typedef int (dio_iodone_t)(struct kiocb *iocb, loff_t offset,/* File does not contribute to nr_files count */ #define FMODE_NOACCOUNT ((__force fmode_t)0x20000000) +/* File is an O_PATH descriptor which can be upgraded to (read, write). */ +#define FMODE_PATH_READ ((__force fmode_t)0x40000000) +#define FMODE_PATH_WRITE ((__force fmode_t)0x80000000) +/* * Flag for rw_copy_check_uvector and compat_rw_copy_check_uvector * that indicates that they should check the contents of the iovec are
include/linux/namei.h +1 -0
@@ -49,6 +49,7 @@ enum {LAST_NORM, LAST_ROOT, LAST_DOT, LAST_DOTDOT, LAST_BIND};#define LOOKUP_ROOT 0x2000#define LOOKUP_EMPTY 0x4000#define LOOKUP_DOWN 0x8000 +#define LOOKUP_MAGICLINK_JUMPED 0x10000extern int path_pts (struct path *path);
Signature · 1 line
2.22.0
PATCH v11 2/8 procfs: switch magic-link modes to be more sane
In reply to Aleksa SaraiNow that magic-link modes are obeyed for file re-opening purposes, some of the pre-existing magic-link modes need to be adjusted to be more semantically correct.
The most blatant example of this is /proc/self/exe, which had a mode of a+rwx even though tautologically the file could never be opened for writing (because it is the current->mm of a live process).
With the new O_PATH restrictions, changing the default mode of these magic-links allows us to avoid delayed-access attacks such as we saw in CVE-2019-5736.
--- fs/proc/base.c | 20 ++++++++++---------- fs/proc/namespaces.c | 2 +- 2 files changed, 11 insertions(+), 11 deletions(-)
fs/proc/base.c +10 -10
@@ -133,9 +133,9 @@ struct pid_entry {#define DIR (NAME ,MODE , iops, fops) \ NOD(NAME, (S_IFDIR|(MODE)), &iops, &fops, {} ) -#define LNK (NAME , get_link) \ - NOD(NAME, (S_IFLNK|S_IRWXUGO), \ - &proc_pid_link_inode_operations, NULL, \ +#define LNK (NAME ,MODE , get_link) \ + NOD(NAME, (S_IFLNK|(MODE)), \ + &proc_pid_link_inode_operations, NULL, \ { .proc_get_link = get_link } )#define REG (NAME ,MODE , fops) \ NOD(NAME, (S_IFREG|(MODE)), NULL, &fops, {})
@@ -3028,9 +3028,9 @@ static const struct pid_entry tgid_base_stuff[] = {REG ("numa_maps" ,S_IRUGO , proc_pid_numa_maps_operations), #endifREG ("mem" ,S_IRUSR |S_IWUSR , proc_mem_operations), -LNK ("cwd" , proc_cwd_link), -LNK ("root" , proc_root_link), -LNK ("exe" , proc_exe_link), +LNK ("cwd" ,S_IRWXUGO , proc_cwd_link), +LNK ("root" ,S_IRWXUGO , proc_root_link), +LNK ("exe" ,S_IRUGO |S_IXUGO , proc_exe_link),REG ("mounts" ,S_IRUGO , proc_mounts_operations),REG ("mountinfo" ,S_IRUGO , proc_mountinfo_operations), REG("mountstats", S_IRUSR, proc_mountstats_operations),
@@ -3429,11 +3429,11 @@ static const struct pid_entry tid_base_stuff[] = {REG ("numa_maps" ,S_IRUGO , proc_pid_numa_maps_operations), #endifREG ("mem" ,S_IRUSR |S_IWUSR , proc_mem_operations), -LNK ("cwd" , proc_cwd_link), -LNK ("root" , proc_root_link), -LNK ("exe" , proc_exe_link), +LNK ("cwd" ,S_IRWXUGO , proc_cwd_link), +LNK ("root" ,S_IRWXUGO , proc_root_link), +LNK ("exe" ,S_IRUGO |S_IXUGO , proc_exe_link),REG ("mounts" ,S_IRUGO , proc_mounts_operations), -REG ("mountinfo" ,S_IRUGO , proc_mountinfo_operations), +REG ("mountinfo" ,S_IRUGO , proc_mountinfo_operations), #ifdef CONFIG_PROC_PAGE_MONITORREG ("clear_refs" ,S_IWUSR , proc_clear_refs_operations), REG("smaps", S_IRUGO, proc_pid_smaps_operations),
fs/proc/namespaces.c +1 -1
@@ -94,7 +94,7 @@ static struct dentry *proc_ns_instantiate(struct dentry *dentry,struct inode *inode;struct proc_inode *ei; - inode =proc_pid_make_inode (dentry->d_sb, task,S_IFLNK |S_IRWXUGO ); + inode =proc_pid_make_inode (dentry->d_sb, task,S_IFLNK |S_IRUGO );if (!inode)return ERR_PTR (-ENOENT );
Signature · 1 line
2.22.0
PATCH v11 3/8 open: O_EMPTYPATH: procfs-less file descriptor re-opening
In reply to Aleksa SaraiUserspace has made use of /proc/self/fd very liberally to allow for descriptors to be re-opened. There are a wide variety of uses for this feature, but it has always required constructing a pathname and could not be done without procfs mounted. The obvious solution for this is to extend openat(2) to have an AT_EMPTY_PATH-equivalent -- O_EMPTYPATH.
Now that descriptor re-opening has been made safe through the new magic-link resolution restrictions, we can replicate these restrictions for O_EMPTYPATH. In particular, we only allow "upgrading" the file descriptor if the corresponding FMODE_PATH_* bit is set (or the FMODE_{READ,WRITE} cases for non-O_PATH file descriptors).
When doing openat(O_EMPTYPATH|O_PATH), O_PATH takes precedence and O_EMPTYPATH is ignored. Very few users ever have a need to O_PATH re-open an existing file descriptor, and so accommodating them at the expense of further complicating O_PATH makes little sense. Ultimately, if users ask for this we can always add RESOLVE_EMPTY_PATH to resolveat(2) in the future.
--- arch/alpha/include/uapi/asm/fcntl.h | 1 + arch/parisc/include/uapi/asm/fcntl.h | 39 ++++++++++++++-------------- arch/sparc/include/uapi/asm/fcntl.h | 1 + fs/fcntl.c | 2 +- fs/namei.c | 20 ++++++++++++++ fs/open.c | 7 ++++- include/linux/fcntl.h | 2 +- include/uapi/asm-generic/fcntl.h | 4 +++ 8 files changed, 54 insertions(+), 22 deletions(-)
arch/alpha/include/uapi/asm/fcntl.h +1 -0
@@ -34,6 +34,7 @@#define O_PATH 040000000#define __O_TMPFILE 0100000000 +#define O_EMPTYPATH 0200000000#define F_GETLK 7#define F_SETLK 8
arch/parisc/include/uapi/asm/fcntl.h +20 -19
@@ -2,26 +2,27 @@#ifndef _PARISC_FCNTL_H#define _PARISC_FCNTL_H -#define O_APPEND 000000010 -#define O_BLKSEEK 000000100/* HPUX only */ -#define O_CREAT 000000400/* not fcntl */ -#define O_EXCL 000002000/* not fcntl */ -#define O_LARGEFILE 000004000 -#define __O_SYNC 000100000 +#define O_APPEND 0000000010 +#define O_BLKSEEK 0000000100/* HPUX only */ +#define O_CREAT 0000000400/* not fcntl */ +#define O_EXCL 0000002000/* not fcntl */ +#define O_LARGEFILE 0000004000 +#define __O_SYNC 0000100000#define O_SYNC (__O_SYNC|O_DSYNC) -#define O_NONBLOCK 000200004/* HPUX has separate NDELAY & NONBLOCK */ -#define O_NOCTTY 000400000/* not fcntl */ -#define O_DSYNC 001000000/* HPUX only */ -#define O_RSYNC 002000000/* HPUX only */ -#define O_NOATIME 004000000 -#define O_CLOEXEC 010000000/* set close_on_exec */ - -#define O_DIRECTORY 000010000/* must be a directory */ -#define O_NOFOLLOW 000000200/* don't follow links */ -#define O_INVISIBLE 004000000/* invisible I/O, for DMAPI/XDSM */ - -#define O_PATH 020000000 -#define __O_TMPFILE 040000000 +#define O_NONBLOCK 0000200004/* HPUX has separate NDELAY & NONBLOCK */ +#define O_NOCTTY 0000400000/* not fcntl */ +#define O_DSYNC 0001000000/* HPUX only */ +#define O_RSYNC 0002000000/* HPUX only */ +#define O_NOATIME 0004000000 +#define O_CLOEXEC 0010000000/* set close_on_exec */ + +#define O_DIRECTORY 0000010000/* must be a directory */ +#define O_NOFOLLOW 0000000200/* don't follow links */ +#define O_INVISIBLE 0004000000/* invisible I/O, for DMAPI/XDSM */ + +#define O_PATH 0020000000 +#define __O_TMPFILE 0040000000 +#define O_EMPTYPATH 0100000000#define F_GETLK64 8#define F_SETLK64 9
arch/sparc/include/uapi/asm/fcntl.h +1 -0
@@ -37,6 +37,7 @@#define O_PATH 0x1000000#define __O_TMPFILE 0x2000000 +#define O_EMPTYPATH 0x4000000#define F_GETOWN 5/* for sockets. */ #define F_SETOWN 6/* for sockets. */
fs/fcntl.c +1 -1
@@ -1031,7 +1031,7 @@ static int __init fcntl_init(void)* Exceptions: O_NONBLOCK is a two bit define on parisc; O_NDELAY * is defined as O_NONBLOCK on some platforms and not on others. */ -BUILD_BUG_ON (21 -1 /* for O_RDONLY being 0 */ != +BUILD_BUG_ON (22 -1 /* for O_RDONLY being 0 */ !=HWEIGHT32 ( (VALID_OPEN_FLAGS & ~(O_NONBLOCK |O_NDELAY )) | __FMODE_EXEC | __FMODE_NONOTIFY));
fs/namei.c +20 -0
@@ -3571,6 +3571,24 @@ static int trailing_magiclink(struct nameidata *nd, int acc_mode,return may_open_magiclink (upgrade_mask, acc_mode); } +static int do_emptypath (struct nameidata *nd,const struct open_flags *op, +struct file *file) +{ +int error; +/* We don't support AT_FDCWD (since O_PATH is disallowed here). */ +struct fd f =fdget_raw (nd->dfd); + +if (!f.file) +return -EBADF ; + +/* Apply trailing_magiclink()-like restrictions. */ + error =may_open_magiclink (f.file->f_mode, op->acc_mode); +if (!error) + error =vfs_open (&f.file->f_path, file); +fdput (f); +return error; +} +static struct file *path_openat (struct nameidata *nd,const struct open_flags *op,unsigned flags) {
@@ -3583,6 +3601,8 @@ static struct file *path_openat(struct nameidata *nd,if (unlikely (file->f_flags & __O_TMPFILE)) { error =do_tmpfile (nd, flags, op, file); + }else if (unlikely (file->f_flags &O_EMPTYPATH )) { + error =do_emptypath (nd, op, file); }else if (unlikely (file->f_flags &O_PATH )) {/* Inlined path_lookupat() with a trailing_magiclink() check. */ fmode_t opath_mask = op->opath_mask;
fs/open.c +6 -1
@@ -996,6 +996,8 @@ static inline int build_open_flags(int flags, umode_t mode, struct open_flags *o lookup_flags |=LOOKUP_DIRECTORY ;if (!(flags &O_NOFOLLOW )) lookup_flags |=LOOKUP_FOLLOW ; +if (flags &O_EMPTYPATH ) + lookup_flags |=LOOKUP_EMPTY ; op->lookup_flags = lookup_flags;return 0 ; }
@@ -1057,14 +1059,17 @@ long do_sys_open(int dfd, const char __user *filename, int flags, umode_t mode) {struct open_flags op;int fd =build_open_flags (flags, mode, &op); +int empty =0 ;struct filename *tmp;if (fd)return fd; - tmp =getname (filename); + tmp =getname_flags (filename, op.lookup_flags, &empty);if (IS_ERR (tmp))return PTR_ERR (tmp); +if (!empty) + op.open_flag &= ~O_EMPTYPATH ; fd =get_unused_fd_flags (flags);if (fd >=0 ) {
include/linux/fcntl.h +1 -1
@@ -9,7 +9,7 @@ (O_RDONLY |O_WRONLY |O_RDWR |O_CREAT |O_EXCL |O_NOCTTY |O_TRUNC | \O_APPEND |O_NDELAY |O_NONBLOCK |O_NDELAY | __O_SYNC |O_DSYNC | \FASYNC |O_DIRECT |O_LARGEFILE |O_DIRECTORY |O_NOFOLLOW | \ - O_NOATIME | O_CLOEXEC | O_PATH | __O_TMPFILE) + O_NOATIME | O_CLOEXEC | O_PATH | __O_TMPFILE | O_EMPTYPATH)#ifndef force_o_largefile#define force_o_largefile () (!IS_ENABLED(CONFIG_ARCH_32BIT_OFF_T))
include/uapi/asm-generic/fcntl.h +4 -0
@@ -89,6 +89,10 @@#define __O_TMPFILE 020000000#endif +#ifndef O_EMPTYPATH +#define O_EMPTYPATH 040000000 +#endif +/* a horrid kludge trying to make sure that this will fail on old kernels */ #define O_TMPFILE (__O_TMPFILE | O_DIRECTORY)#define O_TMPFILE_MASK (__O_TMPFILE | O_DIRECTORY | O_CREAT)
Signature · 1 line
2.22.0
PATCH v11 4/8 namei: O_BENEATH-style path resolution flags
In reply to Aleksa SaraiAdd the following flags to allow various restrictions on path resolution (these affect the *entire* resolution, rather than just the final path component -- as is the case with LOOKUP_FOLLOW).
The primary justification for these flags is to allow for programs to be far more strict about how they want path resolution to handle symlinks, mountpoint crossings, and paths that escape the dirfd (through an absolute path or ".." shenanigans).
This is of particular concern to container runtimes that want to be very careful about malicious root filesystems that a container's init might have screwed around with (and there is no real way to protect against this in userspace if you consider potential races against a malicious container's init). More classical applications (which have their own potentially buggy userspace path sanitisation code) include web servers, archive extraction tools, network file servers, and so on.
These flags are exposed to userspace through openat2(2) in a later patchset.
* LOOKUP_NO_XDEV: Disallow mount-point crossing (both *down* into one, or *up* from one). Both bind-mounts and cross-filesystem mounts are blocked by this flag. The naming is based on "find -xdev" as well as -EXDEV (though find(1) doesn't walk upwards, the semantics seem obvious).
* LOOKUP_NO_MAGICLINKS: Disallows ->get_link "symlink" (or rather, magic-link) jumping. This is a very specific restriction, and it exists because /proc/$pid/fd/... "symlinks" allow for access outside nd->root and pose risk to container runtimes that don't want to be tricked into accessing a host path (but do want to allow no-funny-business symlink resolution).
* LOOKUP_NO_SYMLINKS: Disallows resolution through symlinks of any kind (including magic-links).
* LOOKUP_BENEATH: Disallow "escapes" from the starting point of the filesystem tree during resolution (you must stay "beneath" the starting point at all times). Currently this is done by disallowing ".." and absolute paths (either in the given path or found during symlink resolution) entirely, as well as all magic-link jumping.
The wholesale banning of ".." is because it is currently not safe to allow ".." resolution (races can cause the path to be moved outside of the root -- this is conceptually similar to historical chroot(2) escape attacks). Future patches in this series will address this, and will re-enable ".." resolution once it is safe. With those patches, ".." resolution will only be allowed if it remains in the root throughout resolution (such as "a/../b" not "a/../../outside/b").
The banning of magic-link jumping is done because it is not clear whether semantically they should be allowed -- while some magic-links are safe there are many that can cause escapes (and once a resolution is outside of the root, O_BENEATH will no longer detect it). Future patches may re-enable magic-link jumping when such jumps would remain inside the root.
The LOOKUP_NO_*LINK flags return -ELOOP if path resolution would violates their requirement, while the others all return -EXDEV.
This is a refresh of Al's AT_NO_JUMPS patchset[1] (which was a variation on David Drysdale's O_BENEATH patchset[2], which in turn was based on the Capsicum project[3]). Input from Linus and Andy in the AT_NO_JUMPS thread[4] determined most of the API changes made in this refresh.
[1]: https://lwn.net/Articles/721443/
[2]: https://lwn.net/Articles/619151/
[3]: https://lwn.net/Articles/603929/
[4]: https://lwn.net/Articles/723057/
--- fs/namei.c | 85 ++++++++++++++++++++++++++++++++++++------- include/linux/namei.h | 7 ++++ 2 files changed, 78 insertions(+), 14 deletions(-)
fs/namei.c +71 -14
@@ -674,7 +674,11 @@ static int unlazy_walk(struct nameidata *nd) goto out2;if (unlikely (!legitimize_path (nd, &nd->path, nd->seq))) goto out1; -if (nd->root.mnt && !(nd->flags &LOOKUP_ROOT )) { +if (!nd->root.mnt) { +/* Restart from path_init() if nd->root was cleared. */ +if (nd->flags &LOOKUP_BENEATH ) + goto out; + }else if (!(nd->flags &LOOKUP_ROOT )) {if (unlikely (!legitimize_path (nd, &nd->root, nd->root_seq))) goto out; }
@@ -843,6 +847,13 @@ static inline void path_to_nameidata(const struct path *path,static int nd_jump_root (struct nameidata *nd) { +if (unlikely (nd->flags &LOOKUP_BENEATH )) +return -EXDEV ; +if (unlikely (nd->flags &LOOKUP_NO_XDEV )) { +/* Absolute path arguments to path_init() are allowed. */ +if (nd->path.mnt !=NULL && nd->path.mnt != nd->root.mnt) +return -EXDEV ; + }if (nd->flags &LOOKUP_RCU ) {struct dentry *d; nd->path = nd->root;
@@ -1051,6 +1062,9 @@ const char *get_link(struct nameidata *nd)int error;const char *res; +if (unlikely (nd->flags &LOOKUP_NO_SYMLINKS )) +return ERR_PTR (-ELOOP ); +if (!(nd->flags &LOOKUP_RCU )) {touch_atime (&last->link);cond_resched ();
@@ -1082,14 +1096,22 @@ const char *get_link(struct nameidata *nd) }else { res =get (dentry, inode, &last->done); } +if (nd->flags &LOOKUP_MAGICLINK_JUMPED ) { +if (unlikely (nd->flags &LOOKUP_NO_MAGICLINKS )) +return ERR_PTR (-ELOOP ); +/* Not currently safe. */ +if (unlikely (nd->flags &LOOKUP_BENEATH )) +return ERR_PTR (-EXDEV ); + }if (IS_ERR_OR_NULL (res))return res; }if (*res =='/' ) {if (!nd->root.mnt)set_root (nd); -if (unlikely (nd_jump_root (nd))) -return ERR_PTR (-ECHILD ); + error =nd_jump_root (nd); +if (unlikely (error)) +return ERR_PTR (error);while (unlikely (*++res =='/' )) ; }
@@ -1270,12 +1292,16 @@ static int follow_managed(struct path *path, struct nameidata *nd)break ; } -if (need_mntput && path->mnt == mnt) -mntput (path->mnt); +if (need_mntput) { +if (path->mnt == mnt) +mntput (path->mnt); +if (unlikely (nd->flags &LOOKUP_NO_XDEV )) + ret = -EXDEV ; +else + nd->flags |=LOOKUP_JUMPED ; + }if (ret == -EISDIR || !ret) ret =1 ; -if (need_mntput) - nd->flags |=LOOKUP_JUMPED ;if (unlikely (ret <0 ))path_put_conditional (path, nd);return ret;
@@ -1332,6 +1358,8 @@ static bool __follow_mount_rcu(struct nameidata *nd, struct path *path, mounted =__lookup_mnt (path->mnt, path->dentry);if (!mounted)break ; +if (unlikely (nd->flags &LOOKUP_NO_XDEV )) +return false; path->mnt = &mounted->mnt; path->dentry = mounted->mnt.mnt_root; nd->flags |=LOOKUP_JUMPED ;
@@ -1352,8 +1380,11 @@ static int follow_dotdot_rcu(struct nameidata *nd)struct inode *inode = nd->inode;while (1 ) { -if (path_equal (&nd->path, &nd->root)) +if (path_equal (&nd->path, &nd->root)) { +if (unlikely (nd->flags &LOOKUP_BENEATH )) +return -EXDEV ;break ; + }if (nd->path.dentry != nd->path.mnt->mnt_root) {struct dentry *old = nd->path.dentry;struct dentry *parent = old->d_parent;
@@ -1378,6 +1409,8 @@ static int follow_dotdot_rcu(struct nameidata *nd)return -ECHILD ;if (&mparent->mnt == nd->path.mnt)break ; +if (unlikely (nd->flags &LOOKUP_NO_XDEV )) +return -EXDEV ;/* we know that mountpoint was pinned */ nd->path.dentry = mountpoint; nd->path.mnt = &mparent->mnt;
@@ -1392,6 +1425,8 @@ static int follow_dotdot_rcu(struct nameidata *nd)return -ECHILD ;if (!mounted)break ; +if (unlikely (nd->flags &LOOKUP_NO_XDEV )) +return -EXDEV ; nd->path.mnt = &mounted->mnt; nd->path.dentry = mounted->mnt.mnt_root; inode = nd->path.dentry->d_inode;
@@ -1480,8 +1515,11 @@ static int path_parent_directory(struct path *path)static int follow_dotdot (struct nameidata *nd) {while (1 ) { -if (path_equal (&nd->path, &nd->root)) +if (path_equal (&nd->path, &nd->root)) { +if (unlikely (nd->flags &LOOKUP_BENEATH )) +return -EXDEV ;break ; + }if (nd->path.dentry != nd->path.mnt->mnt_root) {int ret =path_parent_directory (&nd->path);if (ret)
@@ -1490,6 +1528,8 @@ static int follow_dotdot(struct nameidata *nd) }if (!follow_up (&nd->path))break ; +if (unlikely (nd->flags &LOOKUP_NO_XDEV )) +return -EXDEV ; }follow_mount (&nd->path); nd->inode = nd->path.dentry->d_inode;
@@ -1704,6 +1744,13 @@ static inline int may_lookup(struct nameidata *nd)static inline int handle_dots (struct nameidata *nd,int type) {if (type ==LAST_DOTDOT ) { +/* +* LOOKUP_BENEATH resolving ".." is not currently safe -- races +* can cause our parent to have moved outside of the root and +* us to skip over it. +*/ +if (unlikely (nd->flags &LOOKUP_BENEATH )) +return -EXDEV ;if (!nd->root.mnt)set_root (nd);if (nd->flags &LOOKUP_RCU ) {
@@ -2170,6 +2217,7 @@ static int link_path_walk(const char *name, struct nameidata *nd)/* must be paired with terminate_walk() */ static const char *path_init (struct nameidata *nd,unsigned flags) { +int error;const char *s = nd->name->name;if (!*s)
@@ -2202,11 +2250,13 @@ static const char *path_init(struct nameidata *nd, unsigned flags) nd->path.dentry =NULL ; nd->m_seq =read_seqbegin (&mount_lock); + +/* Figure out the starting path and root (if needed). */ if (*s =='/' ) {set_root (nd); -if (likely (!nd_jump_root (nd))) -return s; -return ERR_PTR (-ECHILD ); + error =nd_jump_root (nd); +if (unlikely (error)) +return ERR_PTR (error); }else if (nd->dfd ==AT_FDCWD ) {if (flags &LOOKUP_RCU ) {struct fs_struct *fs = current->fs;
@@ -2222,7 +2272,6 @@ static const char *path_init(struct nameidata *nd, unsigned flags)get_fs_pwd (current->fs, &nd->path); nd->inode = nd->path.dentry->d_inode; } -return s; }else {/* Caller must check execute permissions on the starting path component */ struct fd f =fdget_raw (nd->dfd);
@@ -2247,8 +2296,16 @@ static const char *path_init(struct nameidata *nd, unsigned flags) nd->inode = nd->path.dentry->d_inode; }fdput (f); -return s; } +/* For scoped-lookups we need to set the root to the dirfd as well. */ +if (flags &LOOKUP_BENEATH ) { + nd->root = nd->path; +if (flags &LOOKUP_RCU ) + nd->root_seq = nd->seq; +else +path_get (&nd->root); + } +return s; }static const char *trailing_symlink (struct nameidata *nd)
include/linux/namei.h +7 -0
@@ -51,6 +51,13 @@ enum {LAST_NORM, LAST_ROOT, LAST_DOT, LAST_DOTDOT, LAST_BIND};#define LOOKUP_DOWN 0x8000#define LOOKUP_MAGICLINK_JUMPED 0x10000 +/* Scoping flags for lookup. */ +#define LOOKUP_BENEATH 0x020000/* No escaping from starting point. */ +#define LOOKUP_NO_XDEV 0x040000/* No mountpoint crossing. */ +#define LOOKUP_NO_MAGICLINKS 0x080000/* No /proc/$pid/fd/ "symlink" crossing. */ +#define LOOKUP_NO_SYMLINKS 0x100000/* No symlink crossing *at all*. +Implies LOOKUP_NO_MAGICLINKS. */ +extern int path_pts (struct path *path);extern int user_path_at_empty (int ,const char __user *,unsigned ,struct path *,int *empty);
Signature · 1 line
2.22.0
PATCH v11 5/8 namei: LOOKUP_IN_ROOT: chroot-like path resolution
In reply to Aleksa SaraiThe primary motivation for the need for this flag is container runtimes which have to interact with malicious root filesystems in the host namespaces. One of the first requirements for a container runtime to be secure against a malicious rootfs is that they correctly scope symlinks (that is, they should be scoped as though they are chroot(2)ed into the container's rootfs) and ".."-style paths[*]. The already-existing LOOKUP_NO_XDEV and LOOKUP_NO_MAGICLINKS help defend against other potential attacks in a malicious rootfs scenario.
Currently most container runtimes try to do this resolution in userspace[1], causing many potential race conditions. In addition, the "obvious" alternative (actually performing a {ch,pivot_}root(2)) requires a fork+exec (for some runtimes) which is *very* costly if necessary for every filesystem operation involving a container.
[*] At the moment, ".." and magic-link jumping are disallowed for the
same reason it is disabled for LOOKUP_BENEATH -- currently it is not safe to allow it. Future patches may enable it unconditionally once we have resolved the possible races (for "..") and semantics (for magic-link jumping).
The most significant *at(2) semantic change with LOOKUP_IN_ROOT is that absolute pathnames no longer cause the dirfd to be ignored completely.
The rationale is that LOOKUP_IN_ROOT must necessarily chroot-scope symlinks with absolute paths to dirfd, and so doing it for the base path seems to be the most consistent behaviour (and also avoids foot-gunning users who want to scope paths that are absolute).
[1]: https://github.com/cyphar/filepath-securejoin
--- fs/namei.c | 41 +++++++++++++++++++++++++++++++---------- include/linux/namei.h | 1 + 2 files changed, 32 insertions(+), 10 deletions(-)
fs/namei.c +31 -10
@@ -676,7 +676,7 @@ static int unlazy_walk(struct nameidata *nd) goto out1;if (!nd->root.mnt) {/* Restart from path_init() if nd->root was cleared. */ -if (nd->flags &LOOKUP_BENEATH ) +if (nd->flags & (LOOKUP_BENEATH |LOOKUP_IN_ROOT )) goto out; }else if (!(nd->flags &LOOKUP_ROOT )) {if (unlikely (!legitimize_path (nd, &nd->root, nd->root_seq)))
@@ -809,10 +809,18 @@ static int complete_walk(struct nameidata *nd)return status; } -static void set_root (struct nameidata *nd) +static int set_root (struct nameidata *nd) {struct fs_struct *fs = current->fs; +/* +* Jumping to the real root as part of LOOKUP_IN_ROOT is a BUG in namei, +* but we still have to ensure it doesn't happen because it will cause a +* breakout from the dirfd. +*/ +if (WARN_ON (nd->flags &LOOKUP_IN_ROOT )) +return -ENOTRECOVERABLE ; +if (nd->flags &LOOKUP_RCU ) {unsigned seq;
@@ -824,6 +832,7 @@ static void set_root(struct nameidata *nd) }else {get_fs_root (fs, &nd->root); } +return 0 ; }static void path_put_conditional (struct path *path,struct nameidata *nd)
@@ -854,6 +863,11 @@ static int nd_jump_root(struct nameidata *nd)if (nd->path.mnt !=NULL && nd->path.mnt != nd->root.mnt)return -EXDEV ; } +if (!nd->root.mnt) { +int error =set_root (nd); +if (error) +return error; + }if (nd->flags &LOOKUP_RCU ) {struct dentry *d; nd->path = nd->root;
@@ -1100,15 +1114,13 @@ const char *get_link(struct nameidata *nd)if (unlikely (nd->flags &LOOKUP_NO_MAGICLINKS ))return ERR_PTR (-ELOOP );/* Not currently safe. */ -if (unlikely (nd->flags &LOOKUP_BENEATH )) +if (unlikely (nd->flags & (LOOKUP_BENEATH |LOOKUP_IN_ROOT )))return ERR_PTR (-EXDEV ); }if (IS_ERR_OR_NULL (res))return res; }if (*res =='/' ) { -if (!nd->root.mnt) -set_root (nd); error =nd_jump_root (nd);if (unlikely (error))return ERR_PTR (error);
@@ -1744,15 +1756,20 @@ static inline int may_lookup(struct nameidata *nd)static inline int handle_dots (struct nameidata *nd,int type) {if (type ==LAST_DOTDOT ) { +int error =0 ; +/* * LOOKUP_BENEATH resolving ".." is not currently safe -- races * can cause our parent to have moved outside of the root and * us to skip over it. */ -if (unlikely (nd->flags &LOOKUP_BENEATH )) +if (unlikely (nd->flags & (LOOKUP_BENEATH |LOOKUP_IN_ROOT )))return -EXDEV ; -if (!nd->root.mnt) -set_root (nd); +if (!nd->root.mnt) { + error =set_root (nd); +if (error) +return error; + }if (nd->flags &LOOKUP_RCU ) {return follow_dotdot_rcu (nd); }else
@@ -2251,9 +2268,13 @@ static const char *path_init(struct nameidata *nd, unsigned flags) nd->m_seq =read_seqbegin (&mount_lock); +/* LOOKUP_IN_ROOT treats absolute paths as being relative-to-dirfd. */ +if (flags &LOOKUP_IN_ROOT ) +while (*s =='/' ) + s++; +/* Figure out the starting path and root (if needed). */ if (*s =='/' ) { -set_root (nd); error =nd_jump_root (nd);if (unlikely (error))return ERR_PTR (error);
@@ -2298,7 +2319,7 @@ static const char *path_init(struct nameidata *nd, unsigned flags)fdput (f); }/* For scoped-lookups we need to set the root to the dirfd as well. */ -if (flags &LOOKUP_BENEATH ) { +if (flags & (LOOKUP_BENEATH |LOOKUP_IN_ROOT )) { nd->root = nd->path;if (flags &LOOKUP_RCU ) nd->root_seq = nd->seq;
include/linux/namei.h +1 -0
@@ -57,6 +57,7 @@ enum {LAST_NORM, LAST_ROOT, LAST_DOT, LAST_DOTDOT, LAST_BIND};#define LOOKUP_NO_MAGICLINKS 0x080000/* No /proc/$pid/fd/ "symlink" crossing. */ #define LOOKUP_NO_SYMLINKS 0x100000/* No symlink crossing *at all*. Implies LOOKUP_NO_MAGICLINKS. */ +#define LOOKUP_IN_ROOT 0x200000/* Treat dirfd as %current->fs->root. */ extern int path_pts (struct path *path);
Signature · 1 line
2.22.0
PATCH v11 6/8 namei: aggressively check for nd->root escape on ".." resolution
In reply to Aleksa SaraiThis patch allows for LOOKUP_BENEATH and LOOKUP_IN_ROOT to safely permit ".." resolution (in the case of LOOKUP_BENEATH the resolution will still fail if ".." resolution would resolve a path outside of the root -- while LOOKUP_IN_ROOT will chroot(2)-style scope it). Magic-link jumps are still disallowed entirely because now they could result in inconsistent behaviour if resolution encounters a subsequent ".."[*].
The need for this patch is explained by observing there is a fairly easy-to-exploit race condition with chroot(2) (and thus by extension LOOKUP_IN_ROOT and LOOKUP_BENEATH if ".." is allowed) where a rename(2) of a path can be used to "skip over" nd->root and thus escape to the filesystem above nd->root.
thread1 [attacker]:
for (;;)
renameat2(AT_FDCWD, "/a/b/c", AT_FDCWD, "/a/d", RENAME_EXCHANGE);
thread2 [victim]:
for (;;)
openat2(dirb, "b/c/../../etc/shadow",
{ .flags = O_PATH, .resolve = RESOLVE_IN_ROOT } );With fairly significant regularity, thread2 will resolve to "/etc/shadow" rather than "/a/b/etc/shadow". There is also a similar (though somewhat more privileged) attack using MS_MOVE.
With this patch, such cases will be detected *during* ".." resolution (which is the weak point of chroot(2) -- since walking *into* a subdirectory tautologically cannot result in you walking *outside* nd->root -- except through a bind-mount or magic-link). By detecting this at ".." resolution (rather than checking only at the end of the entire resolution) we can both correct escapes by jumping back to the root (in the case of LOOKUP_IN_ROOT), as well as avoid revealing to attackers the structure of the filesystem outside of the root (through timing attacks for instance).
In order to avoid a quadratic lookup with each ".." entry, we only activate the slow path if a write through &rename_lock or &mount_lock has occurred during path resolution (&rename_lock and &mount_lock are re-taken to further optimise the lookup). Since the primary attack being protected against is MS_MOVE or rename(2), not doing additional checks unless a mount or rename have occurred avoids making the common case slow.
The use of path_is_under() here might seem suspect, but on further inspection of the most important race (a path was *inside* the root but is now *outside*), there appears to be no attack potential:
* If path_is_under() occurs before the rename, then the path will be resolved -- however the path was originally inside the root and thus there is no escape (and to userspace it'd look like the rename occurred after the path was resolved). If path_is_under() occurs afterwards, the resolution is blocked.
* Subsequent ".." jumps are guaranteed to check path_is_under() -- by construction, &rename_lock or &mount_lock must have been taken by the attacker after path_is_under() returned in the victim. Thus ".." will not be able to escape from the previously-inside-root path.
* Walking down in the moved path is still safe since the entire subtree was moved (either by rename(2) or MS_MOVE) and because (as discussed above) walking down is safe.
A variant of the above attack is included in the selftests for openat2(2) later in this patch series. I've run this test on several machines for several days and no instances of a breakout were detected. While this is not concrete proof that this is safe, when combined with the above argument it should lend some trustworthiness to this construction.
[*] It may be acceptable in the future to do a path_is_under() check
after resolving a magic-link and permit resolution if the nd_jump_link() result is still within the dirfd. However this seems unlikely to be a feature that people *really* need* -- it can be added later if it turns out a lot of people want it.
--- fs/namei.c | 45 +++++++++++++++++++++++++++++++-------------- 1 file changed, 31 insertions(+), 14 deletions(-)
fs/namei.c +31 -14
@@ -491,7 +491,7 @@ struct nameidata {struct path root;struct inode *inode;/* path.dentry.d_inode */ unsigned int flags; -unsigned seq, m_seq; +unsigned seq, m_seq, r_seq;int last_type;unsigned depth;int total_link_count;
@@ -1758,22 +1758,36 @@ static inline int handle_dots(struct nameidata *nd, int type)if (type ==LAST_DOTDOT ) {int error =0 ; -/* -* LOOKUP_BENEATH resolving ".." is not currently safe -- races -* can cause our parent to have moved outside of the root and -* us to skip over it. -*/ -if (unlikely (nd->flags & (LOOKUP_BENEATH |LOOKUP_IN_ROOT ))) -return -EXDEV ;if (!nd->root.mnt) { error =set_root (nd);if (error)return error; } -if (nd->flags &LOOKUP_RCU ) { -return follow_dotdot_rcu (nd); - }else -return follow_dotdot (nd); +if (nd->flags &LOOKUP_RCU ) + error =follow_dotdot_rcu (nd); +else + error =follow_dotdot (nd); +if (error) +return error; + +if (unlikely (nd->flags & (LOOKUP_BENEATH |LOOKUP_IN_ROOT ))) { +bool m_retry =read_seqretry (&mount_lock, nd->m_seq); +bool r_retry =read_seqretry (&rename_lock, nd->r_seq); + +/* +* Don't bother checking unless there's a racing +* rename(2) or MS_MOVE. +*/ +if (likely (!m_retry && !r_retry)) +return 0 ; + +if (m_retry && !(nd->flags &LOOKUP_RCU )) + nd->m_seq =read_seqbegin (&mount_lock); +if (r_retry) + nd->r_seq =read_seqbegin (&rename_lock); +if (!path_is_under (&nd->path, &nd->root)) +return -EXDEV ; + } }return 0 ; }
@@ -2245,6 +2259,11 @@ static const char *path_init(struct nameidata *nd, unsigned flags) nd->last_type =LAST_ROOT ;/* if there are only slashes... */ nd->flags = flags |LOOKUP_JUMPED |LOOKUP_PARENT ; nd->depth =0 ; + + nd->m_seq =read_seqbegin (&mount_lock); +if (flags & (LOOKUP_BENEATH |LOOKUP_IN_ROOT )) + nd->r_seq =read_seqbegin (&rename_lock); +if (flags &LOOKUP_ROOT ) {struct dentry *root = nd->root.dentry;struct inode *inode = root->d_inode;
@@ -2266,8 +2285,6 @@ static const char *path_init(struct nameidata *nd, unsigned flags) nd->path.mnt =NULL ; nd->path.dentry =NULL ; - nd->m_seq =read_seqbegin (&mount_lock); -/* LOOKUP_IN_ROOT treats absolute paths as being relative-to-dirfd. */ if (flags &LOOKUP_IN_ROOT )while (*s =='/' )
Signature · 1 line
2.22.0
PATCH v11 7/8 open: openat2(2) syscall
In reply to Aleksa SaraiThe most obvious syscall to add support for the new LOOKUP_* scoping flags would be openat(2). However, there are a few reasons why this is not the best course of action:
* The new LOOKUP_* flags are intended to be security features, and openat(2) will silently ignore all unknown flags. This means that users would need to avoid foot-gunning themselves constantly when using this interface if it were part of openat(2). This can be fixed by having userspace libraries handle this for users[1], but should be avoided if possible.
* Resolution scoping feels like a different operation to the existing O_* flags. And since openat(2) has limited flag space, it seems to be quite wasteful to clutter it with 5 flags that are all resolution-related. Arguably O_NOFOLLOW is also a resolution flag but its entire purpose is to error out if you encounter a trailing symlink -- not to scope resolution.
* Other systems would be able to reimplement this syscall allowing for cross-OS standardisation rather than being hidden amongst O_* flags which may result in it not being used by all the parties that might want to use it (file servers, web servers, container runtimes, etc).
* It gives us the opportunity to iterate on the O_PATH interface. In particular, the new @how->upgrade_mask field for fd re-opening is only possible because we have a clean slate without needing to re-use the ACC_MODE flag design nor the existing openat(2) @mode semantics.
To this end, we introduce the openat2(2) syscall. It provides all of the features of openat(2) through the @how->flags argument, but also also provides a new @how->resolve argument which exposes RESOLVE_* flags that map to our new LOOKUP_* flags. It also eliminates the long-standing ugliness of variadic-open(2) by embedding it in a struct.
In order to allow for userspace to lock down their usage of file descriptor re-opening, openat2(2) has the ability for users to disallow certain re-opening modes through @how->upgrade_mask. At the moment, there is no UPGRADE_NOEXEC. The open_how struct is padded to 64 bytes for future extensions (all of the reserved bits must be zeroed).
[1]: https://github.com/openSUSE/libpathrs
--- arch/alpha/kernel/syscalls/syscall.tbl | 1 + arch/arm/tools/syscall.tbl | 1 + arch/arm64/include/asm/unistd.h | 2 +- arch/arm64/include/asm/unistd32.h | 2 + arch/ia64/kernel/syscalls/syscall.tbl | 1 + arch/m68k/kernel/syscalls/syscall.tbl | 1 + arch/microblaze/kernel/syscalls/syscall.tbl | 1 + arch/mips/kernel/syscalls/syscall_n32.tbl | 1 + arch/mips/kernel/syscalls/syscall_n64.tbl | 1 + arch/mips/kernel/syscalls/syscall_o32.tbl | 1 + arch/parisc/kernel/syscalls/syscall.tbl | 1 + arch/powerpc/kernel/syscalls/syscall.tbl | 1 + arch/s390/kernel/syscalls/syscall.tbl | 1 + arch/sh/kernel/syscalls/syscall.tbl | 1 + arch/sparc/kernel/syscalls/syscall.tbl | 1 + arch/x86/entry/syscalls/syscall_32.tbl | 1 + arch/x86/entry/syscalls/syscall_64.tbl | 1 + arch/xtensa/kernel/syscalls/syscall.tbl | 1 + fs/open.c | 106 ++++++++++++++++---- include/linux/fcntl.h | 15 ++- include/linux/fs.h | 4 +- include/linux/syscalls.h | 17 +++- include/uapi/asm-generic/unistd.h | 5 +- include/uapi/linux/fcntl.h | 42 ++++++++ 24 files changed, 179 insertions(+), 30 deletions(-)
arch/alpha/kernel/syscalls/syscall.tbl +1 -0
@@ -475,3 +475,4 @@ 543 common fspick sys_fspick 544 common pidfd_open sys_pidfd_open # 545 reserved for clone3 +547 common openat2 sys_openat2
arch/arm/tools/syscall.tbl +1 -0
@@ -449,3 +449,4 @@ 433 common fspick sys_fspick 434 common pidfd_open sys_pidfd_open 435 common clone3 sys_clone3 +437 common openat2 sys_openat2
arch/arm64/include/asm/unistd.h +1 -1
@@ -38,7 +38,7 @@#define __ARM_NR_compat_set_tls (__ARM_NR_COMPAT_BASE + 5)#define __ARM_NR_COMPAT_END (__ARM_NR_COMPAT_BASE + 0x800) -#define __NR_compat_syscalls 436 +#define __NR_compat_syscalls 438#endif #define __ARCH_WANT_SYS_CLONE
arch/arm64/include/asm/unistd32.h +2 -0
@@ -879,6 +879,8 @@ __SYSCALL(__NR_fspick, sys_fspick) __SYSCALL(__NR_pidfd_open, sys_pidfd_open)#define __NR_clone3 435 __SYSCALL(__NR_clone3, sys_clone3) +#define __NR_openat2 437 +__SYSCALL (__NR_openat2, sys_openat2)/* * Please add new compat syscalls above this comment and update
arch/ia64/kernel/syscalls/syscall.tbl +1 -0
@@ -356,3 +356,4 @@ 433 common fspick sys_fspick 434 common pidfd_open sys_pidfd_open # 435 reserved for clone3 +437 common openat2 sys_openat2
arch/m68k/kernel/syscalls/syscall.tbl +1 -0
@@ -435,3 +435,4 @@ 433 common fspick sys_fspick 434 common pidfd_open sys_pidfd_open # 435 reserved for clone3 +437 common openat2 sys_openat2
arch/microblaze/kernel/syscalls/syscall.tbl +1 -0
@@ -441,3 +441,4 @@ 433 common fspick sys_fspick 434 common pidfd_open sys_pidfd_open 435 common clone3 sys_clone3 +437 common openat2 sys_openat2
arch/mips/kernel/syscalls/syscall_n32.tbl +1 -0
@@ -374,3 +374,4 @@ 433 n32 fspick sys_fspick 434 n32 pidfd_open sys_pidfd_open # 435 reserved for clone3 +437 n32 openat2 sys_openat2
arch/mips/kernel/syscalls/syscall_n64.tbl +1 -0
@@ -350,3 +350,4 @@ 433 n64 fspick sys_fspick 434 n64 pidfd_open sys_pidfd_open # 435 reserved for clone3 +437 n64 openat2 sys_openat2
arch/mips/kernel/syscalls/syscall_o32.tbl +1 -0
@@ -423,3 +423,4 @@ 433 o32 fspick sys_fspick 434 o32 pidfd_open sys_pidfd_open # 435 reserved for clone3 +437 o32 openat2 sys_openat2 sys_openat2
arch/parisc/kernel/syscalls/syscall.tbl +1 -0
@@ -432,3 +432,4 @@ 433 common fspick sys_fspick 434 common pidfd_open sys_pidfd_open 435 common clone3 sys_clone3_wrapper +437 common openat2 sys_openat2
arch/powerpc/kernel/syscalls/syscall.tbl +1 -0
@@ -517,3 +517,4 @@ 433 common fspick sys_fspick 434 common pidfd_open sys_pidfd_open # 435 reserved for clone3 +437 common openat2 sys_openat2
arch/s390/kernel/syscalls/syscall.tbl +1 -0
@@ -438,3 +438,4 @@ 433 common fspick sys_fspick sys_fspick 434 common pidfd_open sys_pidfd_open sys_pidfd_open # 435 reserved for clone3 +437 common openat2 sys_openat2 sys_openat2
arch/sh/kernel/syscalls/syscall.tbl +1 -0
@@ -438,3 +438,4 @@ 433 common fspick sys_fspick 434 common pidfd_open sys_pidfd_open # 435 reserved for clone3 +437 common openat2 sys_openat2
arch/sparc/kernel/syscalls/syscall.tbl +1 -0
@@ -481,3 +481,4 @@ 433 common fspick sys_fspick 434 common pidfd_open sys_pidfd_open # 435 reserved for clone3 +437 common openat2 sys_openat2
arch/x86/entry/syscalls/syscall_32.tbl +1 -0
@@ -440,3 +440,4 @@ 433 i386 fspick sys_fspick __ia32_sys_fspick 434 i386 pidfd_open sys_pidfd_open __ia32_sys_pidfd_open 435 i386 clone3 sys_clone3 __ia32_sys_clone3 +437 i386 openat2 sys_openat2 __ia32_sys_openat2
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
@@ -357,6 +357,7 @@ 433 common fspick __x64_sys_fspick 434 common pidfd_open __x64_sys_pidfd_open 435 common clone3 __x64_sys_clone3/ptregs +437 common openat2 __x64_sys_openat2 # # x32-specific system call numbers start at 512 to avoid cache impact
arch/xtensa/kernel/syscalls/syscall.tbl +1 -0
@@ -406,3 +406,4 @@ 433 common fspick sys_fspick 434 common pidfd_open sys_pidfd_open 435 common clone3 sys_clone3 +437 common openat2 sys_openat2
fs/open.c +85 -21
189 lines not on this page · raw message
include/linux/fcntl.h +14 -1
@@ -4,13 +4,26 @@#include <uapi/linux/fcntl.h> -/* list of all valid flags for the open/openat flags argument: */ +/* Should open_how.mode be set for older syscalls wrappers? */ +#define OPENHOW_MODE (flags, mode) \ + (((flags) & (O_CREAT | __O_TMPFILE)) ? (mode) : 0) + +/* List of all valid flags for the open/openat flags argument: */ #define VALID_OPEN_FLAGS \ (O_RDONLY | O_WRONLY | O_RDWR | O_CREAT | O_EXCL | O_NOCTTY | O_TRUNC | \ O_APPEND | O_NDELAY | O_NONBLOCK | O_NDELAY | __O_SYNC | O_DSYNC | \ FASYNC | O_DIRECT | O_LARGEFILE | O_DIRECTORY | O_NOFOLLOW | \ O_NOATIME | O_CLOEXEC | O_PATH | __O_TMPFILE | O_EMPTYPATH) +/* List of all valid flags for the how->upgrade_mask argument: */ +#define VALID_UPGRADE_FLAGS \ + (UPGRADE_NOWRITE | UPGRADE_NOREAD) + +/* List of all valid flags for the how->resolve argument: */ +#define VALID_RESOLVE_FLAGS \ + (RESOLVE_NO_XDEV | RESOLVE_NO_MAGICLINKS | RESOLVE_NO_SYMLINKS | \ + RESOLVE_BENEATH | RESOLVE_IN_ROOT) +#ifndef force_o_largefile#define force_o_largefile () (!IS_ENABLED(CONFIG_ARCH_32BIT_OFF_T))#endif
include/linux/fs.h +2 -2
@@ -2498,8 +2498,8 @@ extern int do_truncate(struct dentry *, loff_t start, unsigned int time_attrs, struct file *filp);extern int vfs_fallocate (struct file *file,int mode,loff_t offset,loff_t len); -extern long do_sys_open (int dfd,const char __user *filename,int flags, -umode_t mode); +extern long do_sys_open (int dfd,const char __user *filename, +struct open_how *how);extern struct file *file_open_name (struct filename *,int ,umode_t );extern struct file *filp_open (const char *,int ,umode_t ); extern struct file *file_open_root(struct dentry *, struct vfsmount *,
include/linux/syscalls.h +13 -4
@@ -69,6 +69,7 @@ struct rseq;union bpf_attr ;struct io_uring_params ;struct clone_args ; +struct open_how ;#include <linux/types.h> #include <linux/aio_abi.h>
@@ -439,6 +440,8 @@ asmlinkage long sys_fchownat(int dfd, const char __user *filename, uid_t user,asmlinkage long sys_fchown (unsigned int fd,uid_t user,gid_t group);asmlinkage long sys_openat (int dfd,const char __user *filename,int flags,umode_t mode); +asmlinkage long sys_openat2 (int dfd,const char __user *filename, +const struct open_how *how);asmlinkage long sys_close (unsigned int fd);asmlinkage long sys_vhangup (void );
@@ -1374,15 +1377,21 @@ static inline int ksys_close(unsigned int fd)return __close_fd (current->files, fd); } -extern long do_sys_open (int dfd,const char __user *filename,int flags, -umode_t mode); +extern long do_sys_open (int dfd,const char __user *filename, +struct open_how *how);static inline long ksys_open (const char __user *filename,int flags,umode_t mode) { +struct open_how how = { + .flags = flags &VALID_OPEN_FLAGS , + .mode =OPENHOW_MODE (flags, mode), + }; +if (force_o_largefile ()) - flags |=O_LARGEFILE ; -return do_sys_open (AT_FDCWD , filename, flags, mode); + how.flags |=O_LARGEFILE ; + +return do_sys_open (AT_FDCWD , filename, &how); }extern long do_sys_truncate (const char __user *pathname,loff_t length);
include/uapi/asm-generic/unistd.h +4 -1
@@ -851,8 +851,11 @@ __SYSCALL(__NR_pidfd_open, sys_pidfd_open) __SYSCALL(__NR_clone3, sys_clone3)#endif +#define __NR_openat2 437 +__SYSCALL(__NR_openat2, sys_openat2) +#undef __NR_syscalls -#define __NR_syscalls 436 +#define __NR_syscalls 438/* * 32 bit systems traditionally used different
include/uapi/linux/fcntl.h +42 -0
47 lines not on this page · raw message
Signature · 1 line
2.22.0
PATCH v11 8/8 selftests: add openat2(2) selftests
In reply to Aleksa SaraiTest all of the various openat2(2) flags, as well as how file descriptor re-opening works. A small stress-test of a symlink-rename attack is included to show that the protections against ".."-based attacks are sufficient.
In addition, the memfd selftest is fixed to no longer depend on the now-disallowed functionality of upgrading an O_RDONLY descriptor to O_RDWR.
--- tools/testing/selftests/Makefile | 1 + tools/testing/selftests/memfd/memfd_test.c | 7 +- tools/testing/selftests/openat2/.gitignore | 1 + tools/testing/selftests/openat2/Makefile | 8 + tools/testing/selftests/openat2/helpers.c | 162 +++++++ tools/testing/selftests/openat2/helpers.h | 116 +++++ .../testing/selftests/openat2/linkmode_test.c | 333 +++++++++++++++ .../selftests/openat2/rename_attack_test.c | 127 ++++++ .../testing/selftests/openat2/resolve_test.c | 402 ++++++++++++++++++ 9 files changed, 1155 insertions(+), 2 deletions(-) create mode 100644 tools/testing/selftests/openat2/.gitignore create mode 100644 tools/testing/selftests/openat2/Makefile create mode 100644 tools/testing/selftests/openat2/helpers.c create mode 100644 tools/testing/selftests/openat2/helpers.h create mode 100644 tools/testing/selftests/openat2/linkmode_test.c create mode 100644 tools/testing/selftests/openat2/rename_attack_test.c create mode 100644 tools/testing/selftests/openat2/resolve_test.c
tools/testing/selftests/Makefile +1 -0
@@ -37,6 +37,7 @@ TARGETS += powerpc TARGETS += proc TARGETS += pstore TARGETS += ptrace +TARGETS += openat2 TARGETS += rseq TARGETS += rtc TARGETS += seccomp
tools/testing/selftests/memfd/memfd_test.c +5 -2
@@ -925,7 +925,7 @@ static void test_share_mmap(char *banner, char *b_suffix)*/ static void test_share_open (char *banner,char *b_suffix) { -int fd, fd2; +int procfd, fd, fd2;printf ("%s %s %s\n" , memfd_str, banner, b_suffix);
@@ -950,13 +950,16 @@ static void test_share_open(char *banner, char *b_suffix)mfd_assert_has_seals (fd,F_SEAL_WRITE |F_SEAL_SHRINK );mfd_assert_has_seals (fd2,F_SEAL_WRITE |F_SEAL_SHRINK ); +/* We cannot do a MAY_WRITE re-open of an O_RDONLY fd. */ + procfd =mfd_assert_open (fd2,O_PATH ,0 );close (fd2); - fd2 =mfd_assert_open (fd,O_RDWR ,0 ); + fd2 =mfd_assert_open (procfd,O_WRONLY ,0 );mfd_assert_add_seals (fd2,F_SEAL_SEAL );mfd_assert_has_seals (fd,F_SEAL_WRITE |F_SEAL_SHRINK |F_SEAL_SEAL );mfd_assert_has_seals (fd2,F_SEAL_WRITE |F_SEAL_SHRINK |F_SEAL_SEAL ); +close (procfd);close (fd2);close (fd); }
tools/testing/selftests/openat2/.gitignore new file +1 -0
@@ -0,0 +1 @@ +/*_test
tools/testing/selftests/openat2/Makefile new file +8 -0
@@ -0,0 +1,8 @@ +# SPDX-License-Identifier: GPL-2.0 + +CFLAGS += -Wall -O2 -g +TEST_GEN_PROGS := linkmode_test resolve_test rename_attack_test + +include ../lib.mk + +$(TEST_GEN_PROGS): helpers.c
tools/testing/selftests/openat2/helpers.c new file +162 -0
162 lines not on this page · raw message
tools/testing/selftests/openat2/helpers.h new file +116 -0
116 lines not on this page · raw message
tools/testing/selftests/openat2/linkmode_test.c new file +333 -0
333 lines not on this page · raw message
tools/testing/selftests/openat2/rename_attack_test.c new file +127 -0
127 lines not on this page · raw message
tools/testing/selftests/openat2/resolve_test.c new file +402 -0
402 lines not on this page · raw message
Signature · 1 line
2.22.0