]> git.ipfire.org Git - thirdparty/linux.git/commitdiff
libbpf: Set MFD_NOEXEC_SEAL when creating memfd
authorDaniel Xu <dxu@dxuuu.xyz>
Mon, 30 Dec 2024 21:31:22 +0000 (14:31 -0700)
committerAlexei Starovoitov <ast@kernel.org>
Mon, 30 Dec 2024 22:48:15 +0000 (14:48 -0800)
Starting from 105ff5339f49 ("mm/memfd: add MFD_NOEXEC_SEAL and
MFD_EXEC") and until 1717449b4417 ("memfd: drop warning for missing
exec-related flags"), the kernel would print a warning if neither
MFD_NOEXEC_SEAL nor MFD_EXEC is set in memfd_create().

If libbpf runs on on a kernel between these two commits (eg. on an
improperly backported system), it'll trigger this warning.

To avoid this warning (and also be more secure), explicitly set
MFD_NOEXEC_SEAL. But since libbpf can be run on potentially very old
kernels, leave a fallback for kernels without MFD_NOEXEC_SEAL support.

Signed-off-by: Daniel Xu <dxu@dxuuu.xyz>
Link: https://lore.kernel.org/r/6e62c2421ad7eb1da49cbf16da95aaaa7f94d394.1735594195.git.dxu@dxuuu.xyz
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
tools/lib/bpf/libbpf.c

index 66173ddb5a2df3ebe181f17ed299f9ebc5c78eb5..46492cc0927d9455fea89c33cf9f2f9f7bc8f9fd 100644 (file)
@@ -1731,12 +1731,24 @@ static int sys_memfd_create(const char *name, unsigned flags)
 #ifndef MFD_CLOEXEC
 #define MFD_CLOEXEC 0x0001U
 #endif
+#ifndef MFD_NOEXEC_SEAL
+#define MFD_NOEXEC_SEAL 0x0008U
+#endif
 
 static int create_placeholder_fd(void)
 {
+       unsigned int flags = MFD_CLOEXEC | MFD_NOEXEC_SEAL;
+       const char *name = "libbpf-placeholder-fd";
        int fd;
 
-       fd = ensure_good_fd(sys_memfd_create("libbpf-placeholder-fd", MFD_CLOEXEC));
+       fd = ensure_good_fd(sys_memfd_create(name, flags));
+       if (fd >= 0)
+               return fd;
+       else if (errno != EINVAL)
+               return -errno;
+
+       /* Possibly running on kernel without MFD_NOEXEC_SEAL */
+       fd = ensure_good_fd(sys_memfd_create(name, flags & ~MFD_NOEXEC_SEAL));
        if (fd < 0)
                return -errno;
        return fd;