selftests/landlock: Test IOCTL with memfds
authorGünther Noack <gnoack@google.com>
Fri, 19 Apr 2024 16:11:14 +0000 (16:11 +0000)
committerMickaël Salaün <mic@digikod.net>
Mon, 13 May 2024 04:58:30 +0000 (06:58 +0200)
Because the LANDLOCK_ACCESS_FS_IOCTL_DEV right is associated with the
opened file during open(2), IOCTLs are supposed to work with files
which are opened by means other than open(2).

Signed-off-by: Günther Noack <gnoack@google.com>
Link: https://lore.kernel.org/r/20240419161122.2023765-4-gnoack@google.com
Signed-off-by: Mickaël Salaün <mic@digikod.net>
tools/testing/selftests/landlock/fs_test.c

index fd7793b413d1618ea38bb47c5bce318759e1f251..193dc58bac7a9ea356d46b886d43b9bc8a93fdb4 100644 (file)
@@ -3849,20 +3849,48 @@ TEST_F_FORK(ftruncate, open_and_ftruncate_in_different_processes)
        ASSERT_EQ(0, close(socket_fds[1]));
 }
 
-TEST(memfd_ftruncate)
+/* Invokes the FS_IOC_GETFLAGS IOCTL and returns its errno or 0. */
+static int test_fs_ioc_getflags_ioctl(int fd)
 {
-       int fd;
+       uint32_t flags;
+
+       if (ioctl(fd, FS_IOC_GETFLAGS, &flags) < 0)
+               return errno;
+       return 0;
+}
 
-       fd = memfd_create("name", MFD_CLOEXEC);
-       ASSERT_LE(0, fd);
+TEST(memfd_ftruncate_and_ioctl)
+{
+       const struct landlock_ruleset_attr attr = {
+               .handled_access_fs = ACCESS_ALL,
+       };
+       int ruleset_fd, fd, i;
 
        /*
-        * Checks that ftruncate is permitted on file descriptors that are
-        * created in ways other than open(2).
+        * We exercise the same test both with and without Landlock enabled, to
+        * ensure that it behaves the same in both cases.
         */
-       EXPECT_EQ(0, test_ftruncate(fd));
+       for (i = 0; i < 2; i++) {
+               /* Creates a new memfd. */
+               fd = memfd_create("name", MFD_CLOEXEC);
+               ASSERT_LE(0, fd);
 
-       ASSERT_EQ(0, close(fd));
+               /*
+                * Checks that operations associated with the opened file
+                * (ftruncate, ioctl) are permitted on file descriptors that are
+                * created in ways other than open(2).
+                */
+               EXPECT_EQ(0, test_ftruncate(fd));
+               EXPECT_EQ(0, test_fs_ioc_getflags_ioctl(fd));
+
+               ASSERT_EQ(0, close(fd));
+
+               /* Enables Landlock. */
+               ruleset_fd = landlock_create_ruleset(&attr, sizeof(attr), 0);
+               ASSERT_LE(0, ruleset_fd);
+               enforce_ruleset(_metadata, ruleset_fd);
+               ASSERT_EQ(0, close(ruleset_fd));
+       }
 }
 
 static int test_fionread_ioctl(int fd)