Skip to contentSkip to conversation

mm: Add an F_SEAL_FUTURE_WRITE seal to memfd

PATCH RESEND Superseded Joel Fernandes (Google) 6 participants 33 messages Nov 8, 2018 – Nov 11, 2018

Subsystems (7)

v3 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

PATCH RESEND v3 1/2 mm: Add an F_SEAL_FUTURE_WRITE seal to memfd

Android uses ashmem for sharing memory regions. We are looking forward to migrating all usecases of ashmem to memfd so that we can possibly remove the ashmem driver in the future from staging while also benefiting from using memfd and contributing to it. Note staging drivers are also not ABI and generally can be removed at anytime.

One of the main usecases Android has is the ability to create a region and mmap it as writeable, then add protection against making any "future" writes while keeping the existing already mmap'ed writeable-region active. This allows us to implement a usecase where receivers of the shared memory buffer can get a read-only view, while the sender continues to write to the buffer.
See CursorWindow documentation in Android for more details:
https://developer.android.com/reference/android/database/CursorWindow

This usecase cannot be implemented with the existing F_SEAL_WRITE seal. To support the usecase, this patch adds a new F_SEAL_FUTURE_WRITE seal which prevents any future mmap and write syscalls from succeeding while keeping the existing mmap active. The following program shows the seal working in action:

#include <stdio.h>
#include <errno.h>
#include <sys/mman.h>
#include <linux/memfd.h>
#include <linux/fcntl.h>
#include <asm/unistd.h>
#include <unistd.h>
#define F_SEAL_FUTURE_WRITE 0x0010
#define REGION_SIZE (5 * 1024 * 1024)

int memfd_create_region(const char *name, size_t size)

{
    int ret;
    int fd = syscall(__NR_memfd_create, name, MFD_ALLOW_SEALING);
    if (fd < 0) return fd;
    ret = ftruncate(fd, size);
    if (ret < 0) { close(fd); return ret; }
    return fd;
}
int main() {
    int ret, fd;
    void *addr, *addr2, *addr3, *addr1;
    ret = memfd_create_region("test_region", REGION_SIZE);
    printf("ret=%d\n", ret);
    fd = ret;

    // Create map
    addr = mmap(0, REGION_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
    if (addr == MAP_FAILED)
	    printf("map 0 failed\n");
    else
	    printf("map 0 passed\n");

    if ((ret = write(fd, "test", 4)) != 4)
	    printf("write failed even though no future-write seal "
		   "(ret=%d errno =%d)\n", ret, errno);
    else
	    printf("write passed\n");

    addr1 = mmap(0, REGION_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
    if (addr1 == MAP_FAILED)
	    perror("map 1 prot-write failed even though no seal\n");
    else
	    printf("map 1 prot-write passed as expected\n");

    ret = fcntl(fd, F_ADD_SEALS, F_SEAL_FUTURE_WRITE |
				 F_SEAL_GROW |
				 F_SEAL_SHRINK);
    if (ret == -1)
	    printf("fcntl failed, errno: %d\n", errno);
    else
	    printf("future-write seal now active\n");

    if ((ret = write(fd, "test", 4)) != 4)
	    printf("write failed as expected due to future-write seal\n");
    else
	    printf("write passed (unexpected)\n");

    addr2 = mmap(0, REGION_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
    if (addr2 == MAP_FAILED)
	    perror("map 2 prot-write failed as expected due to seal\n");
    else
	    printf("map 2 passed\n");

    addr3 = mmap(0, REGION_SIZE, PROT_READ, MAP_SHARED, fd, 0);
    if (addr3 == MAP_FAILED)
	    perror("map 3 failed\n");
    else
	    printf("map 3 prot-read passed as expected\n");
}

The output of running this program is as follows:
ret=3
map 0 passed
write passed
map 1 prot-write passed as expected
future-write seal now active
write failed as expected due to future-write seal
map 2 prot-write failed as expected due to seal
: Permission denied
map 3 prot-read passed as expected

---
v1->v2: No change, just added selftests to the series. manpages are ready and I'll submit them once the patches are accepted.

v2->v3: Updated commit message to have more support code (John Stultz)
Renamed seal from F_SEAL_FS_WRITE to F_SEAL_FUTURE_WRITE
(Christoph Hellwig)
Allow for this seal only if grow/shrink seals are also either previous set, or are requested along with this seal.
(Christoph Hellwig)
Added locking to synchronize access to file->f_mode.
(Christoph Hellwig)

 include/uapi/linux/fcntl.h |  1 +
 mm/memfd.c                 | 22 +++++++++++++++++++++-
 2 files changed, 22 insertions(+), 1 deletion(-)
include/uapi/linux/fcntl.h +1 -0
index 6448cdd9a350..a2f8658f1c55 100644
@@ -41,6 +41,7 @@
 #define F_SEAL_SHRINK	0x0002	/* prevent file from shrinking */
 #define F_SEAL_GROW	0x0004	/* prevent file from growing */
 #define F_SEAL_WRITE	0x0008	/* prevent writes */
+#define F_SEAL_FUTURE_WRITE	0x0010  /* prevent future writes while mapped */
 /* (1U << 31) is reserved for signed error codes */
 
 /*
mm/memfd.c +21 -1
index 2bb5e257080e..5ba9804e9515 100644
@@ -150,7 +150,8 @@ static unsigned int *memfd_file_seals_ptr(struct file *file)
 #define F_ALL_SEALS (F_SEAL_SEAL | \
 		     F_SEAL_SHRINK | \
 		     F_SEAL_GROW | \
-		     F_SEAL_WRITE)
+		     F_SEAL_WRITE | \
+		     F_SEAL_FUTURE_WRITE)
 
 static int memfd_add_seals(struct file *file, unsigned int seals)
 {
@@ -219,6 +220,25 @@ static int memfd_add_seals(struct file *file, unsigned int seals)
 		}
 	}
 
+	if ((seals & F_SEAL_FUTURE_WRITE) &&
+	    !(*file_seals & F_SEAL_FUTURE_WRITE)) {
+		/*
+		 * The FUTURE_WRITE seal also prevents growing and shrinking
+		 * so we need them to be already set, or requested now.
+		 */
+		int test_seals = (seals | *file_seals) &
+				 (F_SEAL_GROW | F_SEAL_SHRINK);
+
+		if (test_seals != (F_SEAL_GROW | F_SEAL_SHRINK)) {
+			error = -EINVAL;
+			goto unlock;
+		}
+
+		spin_lock(&file->f_lock);
+		file->f_mode &= ~(FMODE_WRITE | FMODE_PWRITE);
+		spin_unlock(&file->f_lock);
+	}
+
 	*file_seals |= seals;
 	error = 0;
 
Signature · 1 line
2.19.1.930.g4563a0d9d0-goog
#1 lore raw

PATCH RESEND v3 2/2 selftests/memfd: Add tests for F_SEAL_FUTURE_WRITE seal

Add tests to verify sealing memfds with the F_SEAL_FUTURE_WRITE works as expected.

---
 tools/testing/selftests/memfd/memfd_test.c | 74 ++++++++++++++++++++++
 1 file changed, 74 insertions(+)
tools/testing/selftests/memfd/memfd_test.c +74 -0
index 10baa1652fc2..32b207ca7372 100644
@@ -692,6 +692,79 @@ static void test_seal_write(void)
 	close(fd);
 }
 
+/*
+ * Test SEAL_FUTURE_WRITE
+ * Test whether SEAL_FUTURE_WRITE actually prevents modifications.
+ */
+static void test_seal_future_write(void)
+{
+	int fd;
+	void *p;
+
+	printf("%s SEAL-FUTURE-WRITE\n", memfd_str);
+
+	fd = mfd_assert_new("kern_memfd_seal_future_write",
+			    mfd_def_size,
+			    MFD_CLOEXEC | MFD_ALLOW_SEALING);
+
+	p = mfd_assert_mmap_shared(fd);
+
+	mfd_assert_has_seals(fd, 0);
+	/* Not adding grow/shrink seals makes the future write
+	 * seal fail to get added
+	 */
+	mfd_fail_add_seals(fd, F_SEAL_FUTURE_WRITE);
+
+	mfd_assert_add_seals(fd, F_SEAL_GROW);
+	mfd_assert_has_seals(fd, F_SEAL_GROW);
+
+	/* Should still fail since shrink seal has
+	 * not yet been added
+	 */
+	mfd_fail_add_seals(fd, F_SEAL_FUTURE_WRITE);
+
+	mfd_assert_add_seals(fd, F_SEAL_SHRINK);
+	mfd_assert_has_seals(fd, F_SEAL_GROW |
+				 F_SEAL_SHRINK);
+
+	/* Now should succeed, also verifies that the seal
+	 * could be added with an existing writable mmap
+	 */
+	mfd_assert_add_seals(fd, F_SEAL_FUTURE_WRITE);
+	mfd_assert_has_seals(fd, F_SEAL_SHRINK |
+				 F_SEAL_GROW |
+				 F_SEAL_FUTURE_WRITE);
+
+	/* read should pass, writes should fail */
+	mfd_assert_read(fd);
+	mfd_fail_write(fd);
+
+	munmap(p, mfd_def_size);
+	close(fd);
+
+	/* Test adding all seals (grow, shrink, future write) at once */
+	fd = mfd_assert_new("kern_memfd_seal_future_write2",
+			    mfd_def_size,
+			    MFD_CLOEXEC | MFD_ALLOW_SEALING);
+
+	p = mfd_assert_mmap_shared(fd);
+
+	mfd_assert_has_seals(fd, 0);
+	mfd_assert_add_seals(fd, F_SEAL_SHRINK |
+				 F_SEAL_GROW |
+				 F_SEAL_FUTURE_WRITE);
+	mfd_assert_has_seals(fd, F_SEAL_SHRINK |
+				 F_SEAL_GROW |
+				 F_SEAL_FUTURE_WRITE);
+
+	/* read should pass, writes should fail */
+	mfd_assert_read(fd);
+	mfd_fail_write(fd);
+
+	munmap(p, mfd_def_size);
+	close(fd);
+}
+
 /*
  * Test SEAL_SHRINK
  * Test whether SEAL_SHRINK actually prevents shrinking
@@ -945,6 +1018,7 @@ int main(int argc, char **argv)
 	test_basic();
 
 	test_seal_write();
+	test_seal_future_write();
 	test_seal_shrink();
 	test_seal_grow();
 	test_seal_resize();
Signature · 1 line
2.19.1.930.g4563a0d9d0-goog
#2 lore raw
In reply to Joel Fernandes (Google)
Quoted 21 lines · Joel Fernandes (Google)

Android uses ashmem for sharing memory regions. We are looking forward to migrating all usecases of ashmem to memfd so that we can possibly remove the ashmem driver in the future from staging while also benefiting from using memfd and contributing to it. Note staging drivers are also not ABI and generally can be removed at anytime.

One of the main usecases Android has is the ability to create a region and mmap it as writeable, then add protection against making any "future" writes while keeping the existing already mmap'ed writeable-region active. This allows us to implement a usecase where receivers of the shared memory buffer can get a read-only view, while the sender continues to write to the buffer.
See CursorWindow documentation in Android for more details:
https://developer.android.com/reference/android/database/CursorWindow

This usecase cannot be implemented with the existing F_SEAL_WRITE seal. To support the usecase, this patch adds a new F_SEAL_FUTURE_WRITE seal which prevents any future mmap and write syscalls from succeeding while keeping the existing mmap active. The following program shows the seal working in action:

[...]

Quoted 22 lines

The output of running this program is as follows:
ret=3
map 0 passed
write passed
map 1 prot-write passed as expected
future-write seal now active
write failed as expected due to future-write seal
map 2 prot-write failed as expected due to seal
: Permission denied
map 3 prot-read passed as expected

---
v1->v2: No change, just added selftests to the series. manpages are ready and I'll submit them once the patches are accepted.

Quoted 8 lines

v2->v3: Updated commit message to have more support code (John Stultz)
Renamed seal from F_SEAL_FS_WRITE to F_SEAL_FUTURE_WRITE
(Christoph Hellwig)
Allow for this seal only if grow/shrink seals are also either previous set, or are requested along with this seal.
(Christoph Hellwig)
Added locking to synchronize access to file->f_mode.
(Christoph Hellwig)

Christoph, do the patches look Ok to you now? If so, then could you give an Acked-by or Reviewed-by tag?

Thanks a lot,

- Joel

Quoted 58 lines
 include/uapi/linux/fcntl.h |  1 +
 mm/memfd.c                 | 22 +++++++++++++++++++++-
 2 files changed, 22 insertions(+), 1 deletion(-)
include/uapi/linux/fcntl.h +1 -0
index 6448cdd9a350..a2f8658f1c55 100644
@@ -41,6 +41,7 @@
 #define F_SEAL_SHRINK	0x0002	/* prevent file from shrinking */
 #define F_SEAL_GROW	0x0004	/* prevent file from growing */
 #define F_SEAL_WRITE	0x0008	/* prevent writes */
+#define F_SEAL_FUTURE_WRITE	0x0010  /* prevent future writes while mapped */
 /* (1U << 31) is reserved for signed error codes */
 
 /*
mm/memfd.c +21 -1
index 2bb5e257080e..5ba9804e9515 100644
@@ -150,7 +150,8 @@ static unsigned int *memfd_file_seals_ptr(struct file *file)
 #define F_ALL_SEALS (F_SEAL_SEAL | \
 		     F_SEAL_SHRINK | \
 		     F_SEAL_GROW | \
-		     F_SEAL_WRITE)
+		     F_SEAL_WRITE | \
+		     F_SEAL_FUTURE_WRITE)
 
 static int memfd_add_seals(struct file *file, unsigned int seals)
 {
@@ -219,6 +220,25 @@ static int memfd_add_seals(struct file *file, unsigned int seals)
 		}
 	}
 
+	if ((seals & F_SEAL_FUTURE_WRITE) &&
+	    !(*file_seals & F_SEAL_FUTURE_WRITE)) {
+		/*
+		 * The FUTURE_WRITE seal also prevents growing and shrinking
+		 * so we need them to be already set, or requested now.
+		 */
+		int test_seals = (seals | *file_seals) &
+				 (F_SEAL_GROW | F_SEAL_SHRINK);
+
+		if (test_seals != (F_SEAL_GROW | F_SEAL_SHRINK)) {
+			error = -EINVAL;
+			goto unlock;
+		}
+
+		spin_lock(&file->f_lock);
+		file->f_mode &= ~(FMODE_WRITE | FMODE_PWRITE);
+		spin_unlock(&file->f_lock);
+	}
+
 	*file_seals |= seals;
 	error = 0;
 
Signature · 1 line
2.19.1.930.g4563a0d9d0-goog
#3 lore raw
In reply to Joel Fernandes (Google)

+linux-api for API addition
+hughd as FYI since this is somewhat related to mm/shmem

Quoted 15 lines · Joel Fernandes (Google)

Android uses ashmem for sharing memory regions. We are looking forward to migrating all usecases of ashmem to memfd so that we can possibly remove the ashmem driver in the future from staging while also benefiting from using memfd and contributing to it. Note staging drivers are also not ABI and generally can be removed at anytime.

One of the main usecases Android has is the ability to create a region and mmap it as writeable, then add protection against making any "future" writes while keeping the existing already mmap'ed writeable-region active. This allows us to implement a usecase where receivers of the shared memory buffer can get a read-only view, while the sender continues to write to the buffer.
See CursorWindow documentation in Android for more details:
https://developer.android.com/reference/android/database/CursorWindow

Quoted 4 lines

This usecase cannot be implemented with the existing F_SEAL_WRITE seal. To support the usecase, this patch adds a new F_SEAL_FUTURE_WRITE seal which prevents any future mmap and write syscalls from succeeding while keeping the existing mmap active.

Please CC linux-api@ on patches like this. If you had done that, I might have criticized your v1 patch instead of your v3 patch...

Quoted 2 lines

The following program shows the seal
working in action:

[...]

Quoted 8 lines

---

[...]

Quoted 4 lines
mm/memfd.c +0 -0
index 2bb5e257080e..5ba9804e9515 100644

[...]

Quoted 12 lines
mm/memfd.c +8 -0
@@ -219,6 +220,25 @@ static int memfd_add_seals(struct file *file, unsigned int seals)
                }
        }
 
+       if ((seals & F_SEAL_FUTURE_WRITE) &&
+           !(*file_seals & F_SEAL_FUTURE_WRITE)) {
+               /*
+                * The FUTURE_WRITE seal also prevents growing and shrinking
+                * so we need them to be already set, or requested now.
+                */
+               int test_seals = (seals | *file_seals) &
+                                (F_SEAL_GROW | F_SEAL_SHRINK);

mm/memfd.c static int memfd_add_seals(struct file *file, unsigned int seals) · line 240

Quoted 10 lines
mm/memfd.c +10 -0
+
+               if (test_seals != (F_SEAL_GROW | F_SEAL_SHRINK)) {
+                       error = -EINVAL;
+                       goto unlock;
+               }
+
+               spin_lock(&file->f_lock);
+               file->f_mode &= ~(FMODE_WRITE | FMODE_PWRITE);
+               spin_unlock(&file->f_lock);
+       }

So you're fiddling around with the file, but not the inode? How are you preventing code like the following from re-opening the file as writable?

$ cat memfd.c
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <printf.h>
#include <fcntl.h>
#include <err.h>
#include <stdio.h>

int main(void) {
int fd = syscall(__NR_memfd_create, "testfd", 0); if (fd == -1) err(1, "memfd");
char path[100];
sprintf(path, "/proc/self/fd/%d", fd); int fd2 = open(path, O_RDWR);
if (fd2 == -1) err(1, "reopen"); printf("reopen successful: %d\n", fd2);
}

$ gcc -o memfd memfd.c
$ ./memfd
reopen successful: 4
$

That aside: I wonder whether a better API would be something that allows you to create a new readonly file descriptor, instead of fiddling with the writability of an existing fd.

#4 lore raw
Quoted 94 lines · Jann Horn
(quoted diff) +2 -0
+linux-api for API addition
+hughd as FYI since this is somewhat related to mm/shmem
Quoted 15 lines · Joel Fernandes (Google)

Android uses ashmem for sharing memory regions. We are looking forward to migrating all usecases of ashmem to memfd so that we can possibly remove the ashmem driver in the future from staging while also benefiting from using memfd and contributing to it. Note staging drivers are also not ABI and generally can be removed at anytime.

One of the main usecases Android has is the ability to create a region and mmap it as writeable, then add protection against making any "future" writes while keeping the existing already mmap'ed writeable-region active. This allows us to implement a usecase where receivers of the shared memory buffer can get a read-only view, while the sender continues to write to the buffer.
See CursorWindow documentation in Android for more details:
https://developer.android.com/reference/android/database/CursorWindow

Quoted 4 lines

This usecase cannot be implemented with the existing F_SEAL_WRITE seal. To support the usecase, this patch adds a new F_SEAL_FUTURE_WRITE seal which prevents any future mmap and write syscalls from succeeding while keeping the existing mmap active.

Please CC linux-api@ on patches like this. If you had done that, I might have criticized your v1 patch instead of your v3 patch...

Quoted 2 lines

The following program shows the seal
working in action:

[...]

Quoted 8 lines

---

[...]

Quoted 4 lines
mm/memfd.c +0 -0
index 2bb5e257080e..5ba9804e9515 100644

[...]

Quoted 12 lines
mm/memfd.c +8 -0
@@ -219,6 +220,25 @@ static int memfd_add_seals(struct file *file, unsigned int seals)
               }
       }
 
+       if ((seals & F_SEAL_FUTURE_WRITE) &&
+           !(*file_seals & F_SEAL_FUTURE_WRITE)) {
+               /*
+                * The FUTURE_WRITE seal also prevents growing and shrinking
+                * so we need them to be already set, or requested now.
+                */
+               int test_seals = (seals | *file_seals) &
+                                (F_SEAL_GROW | F_SEAL_SHRINK);

mm/memfd.c static int memfd_add_seals(struct file *file, unsigned int seals) · line 240

Quoted 10 lines
mm/memfd.c +10 -0
+
+               if (test_seals != (F_SEAL_GROW | F_SEAL_SHRINK)) {
+                       error = -EINVAL;
+                       goto unlock;
+               }
+
+               spin_lock(&file->f_lock);
+               file->f_mode &= ~(FMODE_WRITE | FMODE_PWRITE);
+               spin_unlock(&file->f_lock);
+       }

So you're fiddling around with the file, but not the inode? How are you preventing code like the following from re-opening the file as writable?

$ cat memfd.c
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <printf.h>
#include <fcntl.h>
#include <err.h>
#include <stdio.h>

int main(void) {
int fd = syscall(__NR_memfd_create, "testfd", 0); if (fd == -1) err(1, "memfd");
char path[100];
sprintf(path, "/proc/self/fd/%d", fd); int fd2 = open(path, O_RDWR);
if (fd2 == -1) err(1, "reopen"); printf("reopen successful: %d\n", fd2);
}

Quoted 8 lines
$ gcc -o memfd memfd.c
$ ./memfd
reopen successful: 4
$

That aside: I wonder whether a better API would be something that allows you to create a new readonly file descriptor, instead of fiddling with the writability of an existing fd.

Every now and then I try to write a patch to prevent using proc to reopen a file with greater permission than the original open.

I like your idea to have a clean way to reopen a a memfd with reduced permissions. But I would make it a syscall instead and maybe make it only work for memfd at first. And the proc issue would need to be fixed, too.

#5 lore raw
Quoted 16 lines · Andy Lutomirski
Quoted 16 lines · Jann Horn
(quoted diff) +2 -0
+linux-api for API addition
+hughd as FYI since this is somewhat related to mm/shmem
Quoted 6 lines · Joel Fernandes (Google)

Android uses ashmem for sharing memory regions. We are looking forward to migrating all usecases of ashmem to memfd so that we can possibly remove the ashmem driver in the future from staging while also benefiting from using memfd and contributing to it. Note staging drivers are also not ABI and generally can be removed at anytime.

Quoted 6 lines
Quoted 6 lines
Quoted 6 lines

One of the main usecases Android has is the ability to create a region and mmap it as writeable, then add protection against making any "future" writes while keeping the existing already mmap'ed writeable-region active. This allows us to implement a usecase where receivers of the shared memory buffer can get a read-only view, while the sender continues to write to the buffer.

Oh I remember trying this years ago with a new seal, F_SEAL_WRITE_PEER, or something like that.

Quoted 14 lines
Quoted 14 lines

So you're fiddling around with the file, but not the inode? How are you preventing code like the following from re-opening the file as writable?

$ cat memfd.c
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <printf.h>
#include <fcntl.h>
#include <err.h>
#include <stdio.h>
Quoted 14 lines
Quoted 9 lines

int main(void) {
int fd = syscall(__NR_memfd_create, "testfd", 0); if (fd == -1) err(1, "memfd");
char path[100];
sprintf(path, "/proc/self/fd/%d", fd); int fd2 = open(path, O_RDWR);
if (fd2 == -1) err(1, "reopen"); printf("reopen successful: %d\n", fd2);
}

Quoted 5 lines
$ gcc -o memfd memfd.c
$ ./memfd
reopen successful: 4
$

The race condition between memfd_create and applying seals in fcntl? I think it would be possible to block new write mappings from peer processes if there is a new memfd_create api that accepts seals. Allowing caller to set a seal
like the one I proposed years ago, though in a race-free manner. Then also consider
how to properly handle blocking inherited +W mapping through clone/fork. Maybe I'm
forgetting some other pitfalls?

Quoted 7 lines
Quoted 3 lines

That aside: I wonder whether a better API would be something that allows you to create a new readonly file descriptor, instead of fiddling with the writability of an existing fd.

Every now and then I try to write a patch to prevent using proc to reopen a file with greater permission than the original open.

I like your idea to have a clean way to reopen a a memfd with reduced permissions. But I would make it a syscall instead and maybe make it only work for memfd at first. And the proc issue would need to be fixed, too.

IMO the best solution would handle the issue at memfd creation time by removing the race condition.

#6 lore raw

On Fri, Nov 09, 2018 at 08:02:14PM +0000, Michael Tirado wrote:
[...]

Quoted 7 lines
Quoted 7 lines
Quoted 3 lines

That aside: I wonder whether a better API would be something that allows you to create a new readonly file descriptor, instead of fiddling with the writability of an existing fd.

Every now and then I try to write a patch to prevent using proc to reopen a file with greater permission than the original open.

Quoted 6 lines
Quoted 3 lines

I like your idea to have a clean way to reopen a a memfd with reduced permissions. But I would make it a syscall instead and maybe make it only work for memfd at first. And the proc issue would need to be fixed, too.

IMO the best solution would handle the issue at memfd creation time by removing the race condition.

I agree, this is another idea I'm exploring. We could add a new .open callback to shmem_file_operations and check for seals there.

thanks,

- Joel

#7 lore raw
In reply to Jann Horn
Quoted 87 lines · Jann Horn
Quoted 15 lines · Joel Fernandes (Google)

Android uses ashmem for sharing memory regions. We are looking forward to migrating all usecases of ashmem to memfd so that we can possibly remove the ashmem driver in the future from staging while also benefiting from using memfd and contributing to it. Note staging drivers are also not ABI and generally can be removed at anytime.

One of the main usecases Android has is the ability to create a region and mmap it as writeable, then add protection against making any "future" writes while keeping the existing already mmap'ed writeable-region active. This allows us to implement a usecase where receivers of the shared memory buffer can get a read-only view, while the sender continues to write to the buffer.
See CursorWindow documentation in Android for more details:
https://developer.android.com/reference/android/database/CursorWindow

Quoted 4 lines

This usecase cannot be implemented with the existing F_SEAL_WRITE seal. To support the usecase, this patch adds a new F_SEAL_FUTURE_WRITE seal which prevents any future mmap and write syscalls from succeeding while keeping the existing mmap active.

Please CC linux-api@ on patches like this. If you had done that, I might have criticized your v1 patch instead of your v3 patch...

Quoted 2 lines

The following program shows the seal
working in action:

[...]

Quoted 8 lines

---

[...]

Quoted 4 lines
mm/memfd.c +0 -0
index 2bb5e257080e..5ba9804e9515 100644

[...]

Quoted 12 lines
mm/memfd.c +8 -0
@@ -219,6 +220,25 @@ static int memfd_add_seals(struct file *file, unsigned int seals)
                }
        }
 
+       if ((seals & F_SEAL_FUTURE_WRITE) &&
+           !(*file_seals & F_SEAL_FUTURE_WRITE)) {
+               /*
+                * The FUTURE_WRITE seal also prevents growing and shrinking
+                * so we need them to be already set, or requested now.
+                */
+               int test_seals = (seals | *file_seals) &
+                                (F_SEAL_GROW | F_SEAL_SHRINK);

mm/memfd.c static int memfd_add_seals(struct file *file, unsigned int seals) · line 240

Quoted 10 lines
mm/memfd.c +10 -0
+
+               if (test_seals != (F_SEAL_GROW | F_SEAL_SHRINK)) {
+                       error = -EINVAL;
+                       goto unlock;
+               }
+
+               spin_lock(&file->f_lock);
+               file->f_mode &= ~(FMODE_WRITE | FMODE_PWRITE);
+               spin_unlock(&file->f_lock);
+       }

So you're fiddling around with the file, but not the inode? How are you preventing code like the following from re-opening the file as writable?

$ cat memfd.c
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <printf.h>
#include <fcntl.h>
#include <err.h>
#include <stdio.h>

int main(void) {
int fd = syscall(__NR_memfd_create, "testfd", 0); if (fd == -1) err(1, "memfd");
char path[100];
sprintf(path, "/proc/self/fd/%d", fd); int fd2 = open(path, O_RDWR);
if (fd2 == -1) err(1, "reopen"); printf("reopen successful: %d\n", fd2);
}

Quoted 8 lines
$ gcc -o memfd memfd.c
$ ./memfd
reopen successful: 4
$

That aside: I wonder whether a better API would be something that allows you to create a new readonly file descriptor, instead of fiddling with the writability of an existing fd.

My favorite approach would be to forbid open() on memfds, hope that nobody notices the tiny API break, and then add an ioctl for "reopen this memfd with reduced permissions" - but that's just my personal opinion.

#8 lore raw
Quoted 93 lines · Jann Horn
Quoted 92 lines · Jann Horn
Quoted 15 lines · Joel Fernandes (Google)

Android uses ashmem for sharing memory regions. We are looking forward to migrating all usecases of ashmem to memfd so that we can possibly remove the ashmem driver in the future from staging while also benefiting from using memfd and contributing to it. Note staging drivers are also not ABI and generally can be removed at anytime.

One of the main usecases Android has is the ability to create a region and mmap it as writeable, then add protection against making any "future" writes while keeping the existing already mmap'ed writeable-region active. This allows us to implement a usecase where receivers of the shared memory buffer can get a read-only view, while the sender continues to write to the buffer.
See CursorWindow documentation in Android for more details:
https://developer.android.com/reference/android/database/CursorWindow

Quoted 4 lines

This usecase cannot be implemented with the existing F_SEAL_WRITE seal. To support the usecase, this patch adds a new F_SEAL_FUTURE_WRITE seal which prevents any future mmap and write syscalls from succeeding while keeping the existing mmap active.

Please CC linux-api@ on patches like this. If you had done that, I might have criticized your v1 patch instead of your v3 patch...

Quoted 2 lines

The following program shows the seal
working in action:

[...]

Quoted 8 lines

---

[...]

Quoted 4 lines
mm/memfd.c +0 -0
index 2bb5e257080e..5ba9804e9515 100644

[...]

Quoted 12 lines
mm/memfd.c +8 -0
@@ -219,6 +220,25 @@ static int memfd_add_seals(struct file *file, unsigned int seals)
                }
        }
 
+       if ((seals & F_SEAL_FUTURE_WRITE) &&
+           !(*file_seals & F_SEAL_FUTURE_WRITE)) {
+               /*
+                * The FUTURE_WRITE seal also prevents growing and shrinking
+                * so we need them to be already set, or requested now.
+                */
+               int test_seals = (seals | *file_seals) &
+                                (F_SEAL_GROW | F_SEAL_SHRINK);

mm/memfd.c static int memfd_add_seals(struct file *file, unsigned int seals) · line 240

Quoted 10 lines
mm/memfd.c +10 -0
+
+               if (test_seals != (F_SEAL_GROW | F_SEAL_SHRINK)) {
+                       error = -EINVAL;
+                       goto unlock;
+               }
+
+               spin_lock(&file->f_lock);
+               file->f_mode &= ~(FMODE_WRITE | FMODE_PWRITE);
+               spin_unlock(&file->f_lock);
+       }

So you're fiddling around with the file, but not the inode? How are you preventing code like the following from re-opening the file as writable?

$ cat memfd.c
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <printf.h>
#include <fcntl.h>
#include <err.h>
#include <stdio.h>

int main(void) {
int fd = syscall(__NR_memfd_create, "testfd", 0); if (fd == -1) err(1, "memfd");
char path[100];
sprintf(path, "/proc/self/fd/%d", fd); int fd2 = open(path, O_RDWR);
if (fd2 == -1) err(1, "reopen"); printf("reopen successful: %d\n", fd2);
}

$ gcc -o memfd memfd.c
$ ./memfd
reopen successful: 4
$
Quoted 8 lines
Quoted 3 lines

That aside: I wonder whether a better API would be something that allows you to create a new readonly file descriptor, instead of fiddling with the writability of an existing fd.

My favorite approach would be to forbid open() on memfds, hope that nobody notices the tiny API break, and then add an ioctl for "reopen this memfd with reduced permissions" - but that's just my personal opinion.

I did something along these lines and it fixes the issue, but I forbid open of memfd only when the F_SEAL_FUTURE_WRITE seal is in place. So then its not an ABI break because this is a brand new seal. That seems the least intrusive solution and it works. Do you mind testing it and I'll add your and Tested-by to the new fix? The patch is based on top of this series.

---8<-----------
From: "Joel Fernandes (Google)" <[email protected]>
Subject: [PATCH] mm/memfd: Fix possible promotion to writeable of sealed memfd

Jann Horn found that reopening an F_SEAL_FUTURE_WRITE sealed memfd through /proc/self/fd/N symlink as writeable succeeds. The simplest fix without causing ABI breakages and ugly VFS hacks is to simply deny all opens on F_SEAL_FUTURE_WRITE sealed fds.

---
 mm/shmem.c | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)
mm/shmem.c +18 -0
index 446942677cd4..5b378c486b8f 100644
@@ -3611,7 +3611,25 @@ static const struct address_space_operations shmem_aops = {
 	.error_remove_page = generic_error_remove_page,
 };
 
+/* Could arrive here for memfds opened through /proc/ */
+int shmem_open(struct inode *inode, struct file *file)
+{
+	struct shmem_inode_info *info = SHMEM_I(inode);
+
+	/*
+	 * memfds for which future writes have been prevented
+	 * should not be reopened, say, through /proc/pid/fd/N
+	 * symlinks otherwise it can cause a sealed memfd to be
+	 * promoted to writable.
+	 */
+	if (info->seals & F_SEAL_FUTURE_WRITE)
+		return -EACCES;
+
+	return 0;
+}
+
 static const struct file_operations shmem_file_operations = {
+	.open		= shmem_open,
 	.mmap		= shmem_mmap,
 	.get_unmapped_area = shmem_get_unmapped_area,
 #ifdef CONFIG_TMPFS
Signature · 1 line
2.19.1.930.g4563a0d9d0-goog
#9 lore raw
Quoted 142 lines · Joel Fernandes
Quoted 95 lines · Jann Horn
Quoted 93 lines · Jann Horn
Quoted 15 lines · Joel Fernandes (Google)

Android uses ashmem for sharing memory regions. We are looking forward to migrating all usecases of ashmem to memfd so that we can possibly remove the ashmem driver in the future from staging while also benefiting from using memfd and contributing to it. Note staging drivers are also not ABI and generally can be removed at anytime.

One of the main usecases Android has is the ability to create a region and mmap it as writeable, then add protection against making any "future" writes while keeping the existing already mmap'ed writeable-region active. This allows us to implement a usecase where receivers of the shared memory buffer can get a read-only view, while the sender continues to write to the buffer.
See CursorWindow documentation in Android for more details:
https://developer.android.com/reference/android/database/CursorWindow

Quoted 4 lines

This usecase cannot be implemented with the existing F_SEAL_WRITE seal. To support the usecase, this patch adds a new F_SEAL_FUTURE_WRITE seal which prevents any future mmap and write syscalls from succeeding while keeping the existing mmap active.

Please CC linux-api@ on patches like this. If you had done that, I might have criticized your v1 patch instead of your v3 patch...

Quoted 2 lines

The following program shows the seal
working in action:

[...]

Quoted 8 lines

---

[...]

Quoted 4 lines
mm/memfd.c +0 -0
index 2bb5e257080e..5ba9804e9515 100644

[...]

Quoted 12 lines
mm/memfd.c +8 -0
@@ -219,6 +220,25 @@ static int memfd_add_seals(struct file *file, unsigned int seals)
               }
       }
 
+       if ((seals & F_SEAL_FUTURE_WRITE) &&
+           !(*file_seals & F_SEAL_FUTURE_WRITE)) {
+               /*
+                * The FUTURE_WRITE seal also prevents growing and shrinking
+                * so we need them to be already set, or requested now.
+                */
+               int test_seals = (seals | *file_seals) &
+                                (F_SEAL_GROW | F_SEAL_SHRINK);

mm/memfd.c static int memfd_add_seals(struct file *file, unsigned int seals) · line 240

Quoted 10 lines
mm/memfd.c +10 -0
+
+               if (test_seals != (F_SEAL_GROW | F_SEAL_SHRINK)) {
+                       error = -EINVAL;
+                       goto unlock;
+               }
+
+               spin_lock(&file->f_lock);
+               file->f_mode &= ~(FMODE_WRITE | FMODE_PWRITE);
+               spin_unlock(&file->f_lock);
+       }

So you're fiddling around with the file, but not the inode? How are you preventing code like the following from re-opening the file as writable?

$ cat memfd.c
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <printf.h>
#include <fcntl.h>
#include <err.h>
#include <stdio.h>

int main(void) {
int fd = syscall(__NR_memfd_create, "testfd", 0); if (fd == -1) err(1, "memfd");
char path[100];
sprintf(path, "/proc/self/fd/%d", fd); int fd2 = open(path, O_RDWR);
if (fd2 == -1) err(1, "reopen"); printf("reopen successful: %d\n", fd2);
}

$ gcc -o memfd memfd.c
$ ./memfd
reopen successful: 4
$
Quoted 8 lines
Quoted 3 lines

That aside: I wonder whether a better API would be something that allows you to create a new readonly file descriptor, instead of fiddling with the writability of an existing fd.

My favorite approach would be to forbid open() on memfds, hope that nobody notices the tiny API break, and then add an ioctl for "reopen this memfd with reduced permissions" - but that's just my personal opinion.

I did something along these lines and it fixes the issue, but I forbid open of memfd only when the F_SEAL_FUTURE_WRITE seal is in place. So then its not an ABI break because this is a brand new seal. That seems the least intrusive solution and it works. Do you mind testing it and I'll add your and Tested-by to the new fix? The patch is based on top of this series.

---8<-----------
From: "Joel Fernandes (Google)" <[email protected]>
Subject: [PATCH] mm/memfd: Fix possible promotion to writeable of sealed memfd

Jann Horn found that reopening an F_SEAL_FUTURE_WRITE sealed memfd through /proc/self/fd/N symlink as writeable succeeds. The simplest fix without causing ABI breakages and ugly VFS hacks is to simply deny all opens on F_SEAL_FUTURE_WRITE sealed fds.

---
mm/shmem.c | 18 ++++++++++++++++++

1 file changed, 18 insertions(+)
mm/shmem.c +6 -0
index 446942677cd4..5b378c486b8f 100644
@@ -3611,7 +3611,25 @@ static const struct address_space_operations shmem_aops = {
   .error_remove_page = generic_error_remove_page,
 };
 
+/* Could arrive here for memfds opened through /proc/ */
+int shmem_open(struct inode *inode, struct file *file)
+{
+    struct shmem_inode_info *info = SHMEM_I(inode);
+
+    /*

mm/shmem.c static const struct address_space_operations shmem_aops = { · line 3629

Quoted 10 lines
mm/shmem.c +10 -0
+     * memfds for which future writes have been prevented
+     * should not be reopened, say, through /proc/pid/fd/N
+     * symlinks otherwise it can cause a sealed memfd to be
+     * promoted to writable.
+     */
+    if (info->seals & F_SEAL_FUTURE_WRITE)
+        return -EACCES;
+
+    return 0;
+}

The result of this series is very warty. We have a concept of seals, and they all work similarly, except the new future write seal. That one:

- causes a probably-observable effect in the file mode in F_GETFL.

- causes reopen to fail.

- does *not* affect other struct files that may already exist on the same inode.

- mysteriously malfunctions if you try to set it again on another struct file that already exists

- probably is insecure when used on hugetlbfs.

I see two reasonable solutions:

1. Don’t fiddle with the struct file at all. Instead make the inode flag work by itself.

2. Don’t call it a “seal”. Instead fix the /proc hole and add an API to drop write access on an existing struct file.

I personally prefer #2.

Quoted 9 lines
mm/shmem.c +2 -0
+
 static const struct file_operations shmem_file_operations = {
+    .open        = shmem_open,
   .mmap        = shmem_mmap,
   .get_unmapped_area = shmem_get_unmapped_area,
 #ifdef CONFIG_TMPFS
Signature · 1 line
2.19.1.930.g4563a0d9d0-goog
#10 lore raw

Thanks Andy for your thoughts, my comments below:

Quoted 146 lines · Andy Lutomirski
Quoted 146 lines · Joel Fernandes
Quoted 95 lines · Jann Horn
Quoted 93 lines · Jann Horn
Quoted 15 lines · Joel Fernandes (Google)

Android uses ashmem for sharing memory regions. We are looking forward to migrating all usecases of ashmem to memfd so that we can possibly remove the ashmem driver in the future from staging while also benefiting from using memfd and contributing to it. Note staging drivers are also not ABI and generally can be removed at anytime.

One of the main usecases Android has is the ability to create a region and mmap it as writeable, then add protection against making any "future" writes while keeping the existing already mmap'ed writeable-region active. This allows us to implement a usecase where receivers of the shared memory buffer can get a read-only view, while the sender continues to write to the buffer.
See CursorWindow documentation in Android for more details:
https://developer.android.com/reference/android/database/CursorWindow

Quoted 4 lines

This usecase cannot be implemented with the existing F_SEAL_WRITE seal. To support the usecase, this patch adds a new F_SEAL_FUTURE_WRITE seal which prevents any future mmap and write syscalls from succeeding while keeping the existing mmap active.

Please CC linux-api@ on patches like this. If you had done that, I might have criticized your v1 patch instead of your v3 patch...

Quoted 2 lines

The following program shows the seal
working in action:

[...]

Quoted 8 lines

---

[...]

Quoted 4 lines
mm/memfd.c +0 -0
index 2bb5e257080e..5ba9804e9515 100644

[...]

Quoted 12 lines
mm/memfd.c +8 -0
@@ -219,6 +220,25 @@ static int memfd_add_seals(struct file *file, unsigned int seals)
               }
       }
 
+       if ((seals & F_SEAL_FUTURE_WRITE) &&
+           !(*file_seals & F_SEAL_FUTURE_WRITE)) {
+               /*
+                * The FUTURE_WRITE seal also prevents growing and shrinking
+                * so we need them to be already set, or requested now.
+                */
+               int test_seals = (seals | *file_seals) &
+                                (F_SEAL_GROW | F_SEAL_SHRINK);

mm/memfd.c static int memfd_add_seals(struct file *file, unsigned int seals) · line 240

Quoted 10 lines
mm/memfd.c +10 -0
+
+               if (test_seals != (F_SEAL_GROW | F_SEAL_SHRINK)) {
+                       error = -EINVAL;
+                       goto unlock;
+               }
+
+               spin_lock(&file->f_lock);
+               file->f_mode &= ~(FMODE_WRITE | FMODE_PWRITE);
+               spin_unlock(&file->f_lock);
+       }

So you're fiddling around with the file, but not the inode? How are you preventing code like the following from re-opening the file as writable?

$ cat memfd.c
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <printf.h>
#include <fcntl.h>
#include <err.h>
#include <stdio.h>

int main(void) {
int fd = syscall(__NR_memfd_create, "testfd", 0); if (fd == -1) err(1, "memfd");
char path[100];
sprintf(path, "/proc/self/fd/%d", fd); int fd2 = open(path, O_RDWR);
if (fd2 == -1) err(1, "reopen"); printf("reopen successful: %d\n", fd2);
}

$ gcc -o memfd memfd.c
$ ./memfd
reopen successful: 4
$
Quoted 8 lines
Quoted 3 lines

That aside: I wonder whether a better API would be something that allows you to create a new readonly file descriptor, instead of fiddling with the writability of an existing fd.

My favorite approach would be to forbid open() on memfds, hope that nobody notices the tiny API break, and then add an ioctl for "reopen this memfd with reduced permissions" - but that's just my personal opinion.

I did something along these lines and it fixes the issue, but I forbid open of memfd only when the F_SEAL_FUTURE_WRITE seal is in place. So then its not an ABI break because this is a brand new seal. That seems the least intrusive solution and it works. Do you mind testing it and I'll add your and Tested-by to the new fix? The patch is based on top of this series.

---8<-----------
From: "Joel Fernandes (Google)" <[email protected]>
Subject: [PATCH] mm/memfd: Fix possible promotion to writeable of sealed memfd

Jann Horn found that reopening an F_SEAL_FUTURE_WRITE sealed memfd through /proc/self/fd/N symlink as writeable succeeds. The simplest fix without causing ABI breakages and ugly VFS hacks is to simply deny all opens on F_SEAL_FUTURE_WRITE sealed fds.

---
mm/shmem.c | 18 ++++++++++++++++++

1 file changed, 18 insertions(+)
mm/shmem.c +10 -0
index 446942677cd4..5b378c486b8f 100644
@@ -3611,7 +3611,25 @@ static const struct address_space_operations shmem_aops = {
   .error_remove_page = generic_error_remove_page,
 };
 
+/* Could arrive here for memfds opened through /proc/ */
+int shmem_open(struct inode *inode, struct file *file)
+{
+    struct shmem_inode_info *info = SHMEM_I(inode);
+
+    /*
+     * memfds for which future writes have been prevented
+     * should not be reopened, say, through /proc/pid/fd/N
+     * symlinks otherwise it can cause a sealed memfd to be
+     * promoted to writable.
Quoted 9 lines

mm/shmem.c static const struct address_space_operations shmem_aops = { · line 3629

Quoted 6 lines
mm/shmem.c +6 -0
+     */
+    if (info->seals & F_SEAL_FUTURE_WRITE)
+        return -EACCES;
+
+    return 0;
+}

The result of this series is very warty. We have a concept of seals, and they all work similarly, except the new future write seal. That one:

I don't see it as warty, different seals will work differently. It works quite well for our usecase, and since Linux is all about solving real problems in the real work, it would be useful to have it.

Quoted 1 line

- causes a probably-observable effect in the file mode in F_GETFL.

Wouldn't that be the right thing to observe anyway?

Quoted 1 line

- causes reopen to fail.

So this concern isn't true anymore if we make reopen fail only for WRITE opens as Daniel suggested. I will make this change so that the security fix is a clean one.

Quoted 1 line

- does *not* affect other struct files that may already exist on the same inode.

TBH if you really want to block all writes to the file, then you want F_SEAL_WRITE, not this seal. The usecase we have is the fd is sent over IPC to another process and we want to prevent any new writes in the receiver side. There is no way this other receiving process can have an existing fd unless it was already sent one without the seal applied. The proposed seal could be renamed to F_SEAL_FD_WRITE if that is preferred.

Quoted 3 lines

- mysteriously malfunctions if you try to set it again on another struct file that already exists

I didn't follow this, could you explain more?

Quoted 1 line

- probably is insecure when used on hugetlbfs.

The usecase is not expected to prevent all writes, indeed the usecase requires existing mmaps to continue to be able to write into the memory map. So would you call that a security issue too? The use of the seal wants to allow existing mmap regions to be continue to be written into (I mentioned more details in the cover letter).

Quoted 4 lines

I see two reasonable solutions:

1. Don’t fiddle with the struct file at all. Instead make the inode flag work by itself.

Currently, the various VFS paths check only the struct file's f_mode to deny writes of already opened files. This would mean more checking in all those paths (and modification of all those paths).

Anyway going with that idea, we could
1. call deny_write_access(file) from the memfd's seal path which decrements the inode::i_writecount.
2. call get_write_access(inode) in the various VFS paths in addition to checking for FMODE_*WRITE and deny the write (incase i_writecount is negative)

That will prevent both reopens, and writes from succeeding. However I worry a bit about 2 not being too familiar with VFS internals, about what the consequences of doing that may be.

Quoted 4 lines

2. Don’t call it a “seal”. Instead fix the /proc hole and add an API to drop write access on an existing struct file.

I personally prefer #2.

So I don't think proc has a hole looking at the code yesterday. As I was saying in other thread, its just how symlinks work. If we were to apply this API to files in general, and we had symlinks to files and we tried to reopen the file, we would run into the same issue - that's why I believe it has nothing to do with proc, and the fix has to be in the underlying inode being pointed to. Does that make sense or did I miss something?

thanks,

- Joel

#11 lore raw
Quoted 211 lines · Joel Fernandes

Thanks Andy for your thoughts, my comments below:

Quoted 146 lines · Andy Lutomirski
Quoted 146 lines · Joel Fernandes
Quoted 95 lines · Jann Horn
Quoted 93 lines · Jann Horn
Quoted 15 lines · Joel Fernandes (Google)

Android uses ashmem for sharing memory regions. We are looking forward to migrating all usecases of ashmem to memfd so that we can possibly remove the ashmem driver in the future from staging while also benefiting from using memfd and contributing to it. Note staging drivers are also not ABI and generally can be removed at anytime.

One of the main usecases Android has is the ability to create a region and mmap it as writeable, then add protection against making any "future" writes while keeping the existing already mmap'ed writeable-region active. This allows us to implement a usecase where receivers of the shared memory buffer can get a read-only view, while the sender continues to write to the buffer.
See CursorWindow documentation in Android for more details:
https://developer.android.com/reference/android/database/CursorWindow

Quoted 4 lines

This usecase cannot be implemented with the existing F_SEAL_WRITE seal. To support the usecase, this patch adds a new F_SEAL_FUTURE_WRITE seal which prevents any future mmap and write syscalls from succeeding while keeping the existing mmap active.

Please CC linux-api@ on patches like this. If you had done that, I might have criticized your v1 patch instead of your v3 patch...

Quoted 2 lines

The following program shows the seal
working in action:

[...]

Quoted 8 lines

---

[...]

Quoted 4 lines
mm/memfd.c +0 -0
index 2bb5e257080e..5ba9804e9515 100644

[...]

Quoted 12 lines
mm/memfd.c +8 -0
@@ -219,6 +220,25 @@ static int memfd_add_seals(struct file *file, unsigned int seals)
               }
       }
 
+       if ((seals & F_SEAL_FUTURE_WRITE) &&
+           !(*file_seals & F_SEAL_FUTURE_WRITE)) {
+               /*
+                * The FUTURE_WRITE seal also prevents growing and shrinking
+                * so we need them to be already set, or requested now.
+                */
+               int test_seals = (seals | *file_seals) &
+                                (F_SEAL_GROW | F_SEAL_SHRINK);

mm/memfd.c static int memfd_add_seals(struct file *file, unsigned int seals) · line 240

Quoted 10 lines
mm/memfd.c +10 -0
+
+               if (test_seals != (F_SEAL_GROW | F_SEAL_SHRINK)) {
+                       error = -EINVAL;
+                       goto unlock;
+               }
+
+               spin_lock(&file->f_lock);
+               file->f_mode &= ~(FMODE_WRITE | FMODE_PWRITE);
+               spin_unlock(&file->f_lock);
+       }

So you're fiddling around with the file, but not the inode? How are you preventing code like the following from re-opening the file as writable?

$ cat memfd.c
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <printf.h>
#include <fcntl.h>
#include <err.h>
#include <stdio.h>

int main(void) {
int fd = syscall(__NR_memfd_create, "testfd", 0); if (fd == -1) err(1, "memfd");
char path[100];
sprintf(path, "/proc/self/fd/%d", fd); int fd2 = open(path, O_RDWR);
if (fd2 == -1) err(1, "reopen"); printf("reopen successful: %d\n", fd2);
}

$ gcc -o memfd memfd.c
$ ./memfd
reopen successful: 4
$
Quoted 8 lines
Quoted 3 lines

That aside: I wonder whether a better API would be something that allows you to create a new readonly file descriptor, instead of fiddling with the writability of an existing fd.

My favorite approach would be to forbid open() on memfds, hope that nobody notices the tiny API break, and then add an ioctl for "reopen this memfd with reduced permissions" - but that's just my personal opinion.

I did something along these lines and it fixes the issue, but I forbid open of memfd only when the F_SEAL_FUTURE_WRITE seal is in place. So then its not an ABI break because this is a brand new seal. That seems the least intrusive solution and it works. Do you mind testing it and I'll add your and Tested-by to the new fix? The patch is based on top of this series.

---8<-----------
From: "Joel Fernandes (Google)" <[email protected]>
Subject: [PATCH] mm/memfd: Fix possible promotion to writeable of sealed memfd

Jann Horn found that reopening an F_SEAL_FUTURE_WRITE sealed memfd through /proc/self/fd/N symlink as writeable succeeds. The simplest fix without causing ABI breakages and ugly VFS hacks is to simply deny all opens on F_SEAL_FUTURE_WRITE sealed fds.

---
mm/shmem.c | 18 ++++++++++++++++++

1 file changed, 18 insertions(+)
mm/shmem.c +10 -0
index 446942677cd4..5b378c486b8f 100644
@@ -3611,7 +3611,25 @@ static const struct address_space_operations shmem_aops = {
   .error_remove_page = generic_error_remove_page,
 };
 
+/* Could arrive here for memfds opened through /proc/ */
+int shmem_open(struct inode *inode, struct file *file)
+{
+    struct shmem_inode_info *info = SHMEM_I(inode);
+
+    /*
+     * memfds for which future writes have been prevented
+     * should not be reopened, say, through /proc/pid/fd/N
+     * symlinks otherwise it can cause a sealed memfd to be
+     * promoted to writable.
Quoted 9 lines

mm/shmem.c static const struct address_space_operations shmem_aops = { · line 3629

Quoted 6 lines
mm/shmem.c +6 -0
+     */
+    if (info->seals & F_SEAL_FUTURE_WRITE)
+        return -EACCES;
+
+    return 0;
+}

The result of this series is very warty. We have a concept of seals, and they all work similarly, except the new future write seal. That one:

I don't see it as warty, different seals will work differently. It works quite well for our usecase, and since Linux is all about solving real problems in the real work, it would be useful to have it.

Quoted 1 line

- causes a probably-observable effect in the file mode in F_GETFL.

Wouldn't that be the right thing to observe anyway?

Quoted 1 line

- causes reopen to fail.

So this concern isn't true anymore if we make reopen fail only for WRITE opens as Daniel suggested. I will make this change so that the security fix is a clean one.

Quoted 1 line

- does *not* affect other struct files that may already exist on the same inode.

TBH if you really want to block all writes to the file, then you want F_SEAL_WRITE, not this seal. The usecase we have is the fd is sent over IPC to another process and we want to prevent any new writes in the receiver side. There is no way this other receiving process can have an existing fd unless it was already sent one without the seal applied. The proposed seal could be renamed to F_SEAL_FD_WRITE if that is preferred.

Quoted 3 lines

- mysteriously malfunctions if you try to set it again on another struct file that already exists

I didn't follow this, could you explain more?

Quoted 1 line

- probably is insecure when used on hugetlbfs.

The usecase is not expected to prevent all writes, indeed the usecase requires existing mmaps to continue to be able to write into the memory map. So would you call that a security issue too? The use of the seal wants to allow existing mmap regions to be continue to be written into (I mentioned more details in the cover letter).

Quoted 4 lines

I see two reasonable solutions:

1. Don’t fiddle with the struct file at all. Instead make the inode flag work by itself.

Currently, the various VFS paths check only the struct file's f_mode to deny writes of already opened files. This would mean more checking in all those paths (and modification of all those paths).

Anyway going with that idea, we could
1. call deny_write_access(file) from the memfd's seal path which decrements the inode::i_writecount.
2. call get_write_access(inode) in the various VFS paths in addition to checking for FMODE_*WRITE and deny the write (incase i_writecount is negative)

Quoted 3 lines

That will prevent both reopens, and writes from succeeding. However I worry a bit about 2 not being too familiar with VFS internals, about what the consequences of doing that may be.

IMHO, modifying both the inode and the struct file separately is fine, since they mean different things. In regular filesystems, it's fine to have a read-write open file description for a file whose inode grants write permission to nobody. Speaking of which: is fchmod enough to prevent this attack?

Quoted 11 lines
Quoted 4 lines

2. Don’t call it a “seal”. Instead fix the /proc hole and add an API to drop write access on an existing struct file.

I personally prefer #2.

So I don't think proc has a hole looking at the code yesterday. As I was saying in other thread, its just how symlinks work. If we were to apply this API to files in general, and we had symlinks to files and we tried to reopen the file, we would run into the same issue - that's why I believe it has nothing to do with proc, and the fix has to be in the underlying inode being pointed to. Does that make sense or did I miss something?

+1. Another point to consider is that even if we did somehow fix the "proc hole", any other means (perhaps in the future) of obtaining an inode reference would then be insecure, perhaps silently. For example --- is there a way to use open_by_handle_at(2) to open a memfd file?

#12 lore raw
Quoted 2 lines · Daniel Colascione
Quoted 1 line · Joel Fernandes

Thanks Andy for your thoughts, my comments below:

[snip]

Quoted 56 lines
Quoted 52 lines

I don't see it as warty, different seals will work differently. It works quite well for our usecase, and since Linux is all about solving real problems in the real work, it would be useful to have it.

Quoted 1 line

- causes a probably-observable effect in the file mode in F_GETFL.

Wouldn't that be the right thing to observe anyway?

Quoted 1 line

- causes reopen to fail.

So this concern isn't true anymore if we make reopen fail only for WRITE opens as Daniel suggested. I will make this change so that the security fix is a clean one.

Quoted 1 line

- does *not* affect other struct files that may already exist on the same inode.

TBH if you really want to block all writes to the file, then you want F_SEAL_WRITE, not this seal. The usecase we have is the fd is sent over IPC to another process and we want to prevent any new writes in the receiver side. There is no way this other receiving process can have an existing fd unless it was already sent one without the seal applied. The proposed seal could be renamed to F_SEAL_FD_WRITE if that is preferred.

Quoted 3 lines

- mysteriously malfunctions if you try to set it again on another struct file that already exists

I didn't follow this, could you explain more?

Quoted 1 line

- probably is insecure when used on hugetlbfs.

The usecase is not expected to prevent all writes, indeed the usecase requires existing mmaps to continue to be able to write into the memory map. So would you call that a security issue too? The use of the seal wants to allow existing mmap regions to be continue to be written into (I mentioned more details in the cover letter).

Quoted 4 lines

I see two reasonable solutions:

1. Don’t fiddle with the struct file at all. Instead make the inode flag work by itself.

Currently, the various VFS paths check only the struct file's f_mode to deny writes of already opened files. This would mean more checking in all those paths (and modification of all those paths).

Anyway going with that idea, we could
1. call deny_write_access(file) from the memfd's seal path which decrements the inode::i_writecount.
2. call get_write_access(inode) in the various VFS paths in addition to checking for FMODE_*WRITE and deny the write (incase i_writecount is negative)

Quoted 3 lines

That will prevent both reopens, and writes from succeeding. However I worry a bit about 2 not being too familiar with VFS internals, about what the consequences of doing that may be.

Quoted 5 lines

IMHO, modifying both the inode and the struct file separately is fine, since they mean different things. In regular filesystems, it's fine to have a read-write open file description for a file whose inode grants write permission to nobody. Speaking of which: is fchmod enough to prevent this attack?

Well, yes and no. fchmod does prevent reopening the file RW, but anyone with permissions (owner, CAP_FOWNER) can just fchmod it back. A seal is supposed to be irrevocable, so fchmod-as-inode-seal probably isn't sufficient by itself. While it might be good enough for Android (in the sense that it'll prevent RW-reopens from other security contexts to which we send an open memfd file), it's still conceptually ugly, IMHO. Let's go with the original approach of just tweaking the inode so that open-for-write is permanently blocked.

#13 lore raw
Quoted 69 lines · Daniel Colascione
Quoted 4 lines · Daniel Colascione
Quoted 2 lines · Joel Fernandes

Thanks Andy for your thoughts, my comments below:

[snip]

Quoted 56 lines
Quoted 52 lines

I don't see it as warty, different seals will work differently. It works quite well for our usecase, and since Linux is all about solving real problems in the real work, it would be useful to have it.

Quoted 1 line

- causes a probably-observable effect in the file mode in F_GETFL.

Wouldn't that be the right thing to observe anyway?

Quoted 1 line

- causes reopen to fail.

So this concern isn't true anymore if we make reopen fail only for WRITE opens as Daniel suggested. I will make this change so that the security fix is a clean one.

Quoted 1 line

- does *not* affect other struct files that may already exist on the same inode.

TBH if you really want to block all writes to the file, then you want F_SEAL_WRITE, not this seal. The usecase we have is the fd is sent over IPC to another process and we want to prevent any new writes in the receiver side. There is no way this other receiving process can have an existing fd unless it was already sent one without the seal applied. The proposed seal could be renamed to F_SEAL_FD_WRITE if that is preferred.

Quoted 3 lines

- mysteriously malfunctions if you try to set it again on another struct file that already exists

I didn't follow this, could you explain more?

Quoted 1 line

- probably is insecure when used on hugetlbfs.

The usecase is not expected to prevent all writes, indeed the usecase requires existing mmaps to continue to be able to write into the memory map. So would you call that a security issue too? The use of the seal wants to allow existing mmap regions to be continue to be written into (I mentioned more details in the cover letter).

Quoted 4 lines

I see two reasonable solutions:

1. Don’t fiddle with the struct file at all. Instead make the inode flag work by itself.

Currently, the various VFS paths check only the struct file's f_mode to deny writes of already opened files. This would mean more checking in all those paths (and modification of all those paths).

Anyway going with that idea, we could
1. call deny_write_access(file) from the memfd's seal path which decrements the inode::i_writecount.
2. call get_write_access(inode) in the various VFS paths in addition to checking for FMODE_*WRITE and deny the write (incase i_writecount is negative)

Quoted 3 lines

That will prevent both reopens, and writes from succeeding. However I worry a bit about 2 not being too familiar with VFS internals, about what the consequences of doing that may be.

Quoted 5 lines

IMHO, modifying both the inode and the struct file separately is fine, since they mean different things. In regular filesystems, it's fine to have a read-write open file description for a file whose inode grants write permission to nobody. Speaking of which: is fchmod enough to prevent this attack?

Quoted 8 lines

Well, yes and no. fchmod does prevent reopening the file RW, but anyone with permissions (owner, CAP_FOWNER) can just fchmod it back. A seal is supposed to be irrevocable, so fchmod-as-inode-seal probably isn't sufficient by itself. While it might be good enough for Android (in the sense that it'll prevent RW-reopens from other security contexts to which we send an open memfd file), it's still conceptually ugly, IMHO. Let's go with the original approach of just tweaking the inode so that open-for-write is permanently blocked.

This should be straightforward. Just add a new seal type and wire it up. It should be considerably simpler than SEAL_WRITE.

#14 lore raw
In reply to Daniel Colascione
Quoted 66 lines · Daniel Colascione
Quoted 2 lines · Daniel Colascione
Quoted 1 line · Joel Fernandes

Thanks Andy for your thoughts, my comments below:

[snip]

Quoted 56 lines
Quoted 52 lines

I don't see it as warty, different seals will work differently. It works quite well for our usecase, and since Linux is all about solving real problems in the real work, it would be useful to have it.

Quoted 1 line

- causes a probably-observable effect in the file mode in F_GETFL.

Wouldn't that be the right thing to observe anyway?

Quoted 1 line

- causes reopen to fail.

So this concern isn't true anymore if we make reopen fail only for WRITE opens as Daniel suggested. I will make this change so that the security fix is a clean one.

Quoted 1 line

- does *not* affect other struct files that may already exist on the same inode.

TBH if you really want to block all writes to the file, then you want F_SEAL_WRITE, not this seal. The usecase we have is the fd is sent over IPC to another process and we want to prevent any new writes in the receiver side. There is no way this other receiving process can have an existing fd unless it was already sent one without the seal applied. The proposed seal could be renamed to F_SEAL_FD_WRITE if that is preferred.

Quoted 3 lines

- mysteriously malfunctions if you try to set it again on another struct file that already exists

I didn't follow this, could you explain more?

Quoted 1 line

- probably is insecure when used on hugetlbfs.

The usecase is not expected to prevent all writes, indeed the usecase requires existing mmaps to continue to be able to write into the memory map. So would you call that a security issue too? The use of the seal wants to allow existing mmap regions to be continue to be written into (I mentioned more details in the cover letter).

Quoted 4 lines

I see two reasonable solutions:

1. Don’t fiddle with the struct file at all. Instead make the inode flag work by itself.

Currently, the various VFS paths check only the struct file's f_mode to deny writes of already opened files. This would mean more checking in all those paths (and modification of all those paths).

Anyway going with that idea, we could
1. call deny_write_access(file) from the memfd's seal path which decrements the inode::i_writecount.
2. call get_write_access(inode) in the various VFS paths in addition to checking for FMODE_*WRITE and deny the write (incase i_writecount is negative)

Quoted 3 lines

That will prevent both reopens, and writes from succeeding. However I worry a bit about 2 not being too familiar with VFS internals, about what the consequences of doing that may be.

Quoted 5 lines

IMHO, modifying both the inode and the struct file separately is fine, since they mean different things. In regular filesystems, it's fine to have a read-write open file description for a file whose inode grants write permission to nobody. Speaking of which: is fchmod enough to prevent this attack?

Quoted 8 lines

Well, yes and no. fchmod does prevent reopening the file RW, but anyone with permissions (owner, CAP_FOWNER) can just fchmod it back. A seal is supposed to be irrevocable, so fchmod-as-inode-seal probably isn't sufficient by itself. While it might be good enough for Android (in the sense that it'll prevent RW-reopens from other security contexts to which we send an open memfd file), it's still conceptually ugly, IMHO. Let's go with the original approach of just tweaking the inode so that open-for-write is permanently blocked.

Agreed with the idea of modifying both file and inode flags. I was thinking modifying i_mode may do the trick but as you pointed it probably could be reverted by chmod or some other attribute setting calls.

OTOH, I don't think deny_write_access(file) can be reverted from any user-facing path so we could do that from the seal to prevent the future opens in write mode. I'll double check and test that out tomorrow.

thanks,

- Joel

#15 lore raw
Quoted 79 lines · Joel Fernandes
Quoted 68 lines · Daniel Colascione
Quoted 3 lines · Daniel Colascione
Quoted 2 lines · Joel Fernandes

Thanks Andy for your thoughts, my comments below:

[snip]

Quoted 56 lines
Quoted 52 lines

I don't see it as warty, different seals will work differently. It works quite well for our usecase, and since Linux is all about solving real problems in the real work, it would be useful to have it.

Quoted 1 line

- causes a probably-observable effect in the file mode in F_GETFL.

Wouldn't that be the right thing to observe anyway?

Quoted 1 line

- causes reopen to fail.

So this concern isn't true anymore if we make reopen fail only for WRITE opens as Daniel suggested. I will make this change so that the security fix is a clean one.

Quoted 1 line

- does *not* affect other struct files that may already exist on the same inode.

TBH if you really want to block all writes to the file, then you want F_SEAL_WRITE, not this seal. The usecase we have is the fd is sent over IPC to another process and we want to prevent any new writes in the receiver side. There is no way this other receiving process can have an existing fd unless it was already sent one without the seal applied. The proposed seal could be renamed to F_SEAL_FD_WRITE if that is preferred.

Quoted 3 lines

- mysteriously malfunctions if you try to set it again on another struct file that already exists

I didn't follow this, could you explain more?

Quoted 1 line

- probably is insecure when used on hugetlbfs.

The usecase is not expected to prevent all writes, indeed the usecase requires existing mmaps to continue to be able to write into the memory map. So would you call that a security issue too? The use of the seal wants to allow existing mmap regions to be continue to be written into (I mentioned more details in the cover letter).

Quoted 4 lines

I see two reasonable solutions:

1. Don’t fiddle with the struct file at all. Instead make the inode flag work by itself.

Currently, the various VFS paths check only the struct file's f_mode to deny writes of already opened files. This would mean more checking in all those paths (and modification of all those paths).

Anyway going with that idea, we could
1. call deny_write_access(file) from the memfd's seal path which decrements the inode::i_writecount.
2. call get_write_access(inode) in the various VFS paths in addition to checking for FMODE_*WRITE and deny the write (incase i_writecount is negative)

Quoted 3 lines

That will prevent both reopens, and writes from succeeding. However I worry a bit about 2 not being too familiar with VFS internals, about what the consequences of doing that may be.

Quoted 5 lines

IMHO, modifying both the inode and the struct file separately is fine, since they mean different things. In regular filesystems, it's fine to have a read-write open file description for a file whose inode grants write permission to nobody. Speaking of which: is fchmod enough to prevent this attack?

Quoted 8 lines

Well, yes and no. fchmod does prevent reopening the file RW, but anyone with permissions (owner, CAP_FOWNER) can just fchmod it back. A seal is supposed to be irrevocable, so fchmod-as-inode-seal probably isn't sufficient by itself. While it might be good enough for Android (in the sense that it'll prevent RW-reopens from other security contexts to which we send an open memfd file), it's still conceptually ugly, IMHO. Let's go with the original approach of just tweaking the inode so that open-for-write is permanently blocked.

Quoted 9 lines

Agreed with the idea of modifying both file and inode flags. I was thinking modifying i_mode may do the trick but as you pointed it probably could be reverted by chmod or some other attribute setting calls.

OTOH, I don't think deny_write_access(file) can be reverted from any user-facing path so we could do that from the seal to prevent the future opens in write mode. I'll double check and test that out tomorrow.

This seems considerably more complicated and more fragile than needed. Just add a new F_SEAL_WRITE_FUTURE. Grep for F_SEAL_WRITE and make the _FUTURE variant work exactly like it with two exceptions:

- shmem_mmap and maybe its hugetlbfs equivalent should check for it and act accordingly.

- add_seals won’t need the wait_for_pins and mapping_deny_write logic.

That really should be all that’s needed.

#16 lore raw
Quoted 89 lines · Andy Lutomirski
Quoted 79 lines · Joel Fernandes
Quoted 68 lines · Daniel Colascione
Quoted 3 lines · Daniel Colascione
Quoted 2 lines · Joel Fernandes

Thanks Andy for your thoughts, my comments below:

[snip]

Quoted 56 lines
Quoted 52 lines

I don't see it as warty, different seals will work differently. It works quite well for our usecase, and since Linux is all about solving real problems in the real work, it would be useful to have it.

Quoted 1 line

- causes a probably-observable effect in the file mode in F_GETFL.

Wouldn't that be the right thing to observe anyway?

Quoted 1 line

- causes reopen to fail.

So this concern isn't true anymore if we make reopen fail only for WRITE opens as Daniel suggested. I will make this change so that the security fix is a clean one.

Quoted 1 line

- does *not* affect other struct files that may already exist on the same inode.

TBH if you really want to block all writes to the file, then you want F_SEAL_WRITE, not this seal. The usecase we have is the fd is sent over IPC to another process and we want to prevent any new writes in the receiver side. There is no way this other receiving process can have an existing fd unless it was already sent one without the seal applied. The proposed seal could be renamed to F_SEAL_FD_WRITE if that is preferred.

Quoted 3 lines

- mysteriously malfunctions if you try to set it again on another struct file that already exists

I didn't follow this, could you explain more?

Quoted 1 line

- probably is insecure when used on hugetlbfs.

The usecase is not expected to prevent all writes, indeed the usecase requires existing mmaps to continue to be able to write into the memory map. So would you call that a security issue too? The use of the seal wants to allow existing mmap regions to be continue to be written into (I mentioned more details in the cover letter).

Quoted 4 lines

I see two reasonable solutions:

1. Don’t fiddle with the struct file at all. Instead make the inode flag work by itself.

Currently, the various VFS paths check only the struct file's f_mode to deny writes of already opened files. This would mean more checking in all those paths (and modification of all those paths).

Anyway going with that idea, we could
1. call deny_write_access(file) from the memfd's seal path which decrements the inode::i_writecount.
2. call get_write_access(inode) in the various VFS paths in addition to checking for FMODE_*WRITE and deny the write (incase i_writecount is negative)

Quoted 3 lines

That will prevent both reopens, and writes from succeeding. However I worry a bit about 2 not being too familiar with VFS internals, about what the consequences of doing that may be.

Quoted 5 lines

IMHO, modifying both the inode and the struct file separately is fine, since they mean different things. In regular filesystems, it's fine to have a read-write open file description for a file whose inode grants write permission to nobody. Speaking of which: is fchmod enough to prevent this attack?

Quoted 8 lines

Well, yes and no. fchmod does prevent reopening the file RW, but anyone with permissions (owner, CAP_FOWNER) can just fchmod it back. A seal is supposed to be irrevocable, so fchmod-as-inode-seal probably isn't sufficient by itself. While it might be good enough for Android (in the sense that it'll prevent RW-reopens from other security contexts to which we send an open memfd file), it's still conceptually ugly, IMHO. Let's go with the original approach of just tweaking the inode so that open-for-write is permanently blocked.

Quoted 9 lines

Agreed with the idea of modifying both file and inode flags. I was thinking modifying i_mode may do the trick but as you pointed it probably could be reverted by chmod or some other attribute setting calls.

OTOH, I don't think deny_write_access(file) can be reverted from any user-facing path so we could do that from the seal to prevent the future opens in write mode. I'll double check and test that out tomorrow.

Quoted 6 lines

This seems considerably more complicated and more fragile than needed. Just add a new F_SEAL_WRITE_FUTURE. Grep for F_SEAL_WRITE and make the _FUTURE variant work exactly like it with two exceptions:

- shmem_mmap and maybe its hugetlbfs equivalent should check for it and act accordingly.

There's more to it than that, we also need to block future writes through write syscall, so we have to hook into the write path too once the seal is set, not just the mmap. That means we have to add code in mm/shmem.c to do that in all those handlers, to check for the seal (and hope we didn't miss a file_operations handler). Is that what you are proposing?

Also, it means we have to keep CONFIG_TMPFS enabled so that the shmem_file_operations write handlers like write_iter are hooked up. Currently memfd works even with !CONFIG_TMPFS.

Quoted 3 lines

- add_seals won’t need the wait_for_pins and mapping_deny_write logic.

That really should be all that’s needed.

It seems a fair idea what you're saying. But I don't see how its less complex.. IMO its far more simple to have VFS do the denial of the operations based on the flags of its datastructures.. and if it works (which I will test to be sure it will), then we should be good.

Btw by any chance, are you also coming by LPC conference next week?

thanks!

- Joel

#17 lore raw
Quoted 98 lines · Joel Fernandes
Quoted 95 lines · Andy Lutomirski
Quoted 79 lines
Quoted 70 lines · Joel Fernandes
Quoted 5 lines · Daniel Colascione
Quoted 3 lines · Daniel Colascione

On Sat, Nov 10, 2018 at 10:24 AM, Joel Fernandes <[email protected]> wrote:
Thanks Andy for your thoughts, my comments below:

[snip]

Quoted 56 lines
Quoted 52 lines

I don't see it as warty, different seals will work differently. It works quite well for our usecase, and since Linux is all about solving real problems in the real work, it would be useful to have it.

Quoted 1 line

- causes a probably-observable effect in the file mode in F_GETFL.

Wouldn't that be the right thing to observe anyway?

Quoted 1 line

- causes reopen to fail.

So this concern isn't true anymore if we make reopen fail only for WRITE opens as Daniel suggested. I will make this change so that the security fix is a clean one.

Quoted 1 line

- does *not* affect other struct files that may already exist on the same inode.

TBH if you really want to block all writes to the file, then you want F_SEAL_WRITE, not this seal. The usecase we have is the fd is sent over IPC to another process and we want to prevent any new writes in the receiver side. There is no way this other receiving process can have an existing fd unless it was already sent one without the seal applied. The proposed seal could be renamed to F_SEAL_FD_WRITE if that is preferred.

Quoted 3 lines

- mysteriously malfunctions if you try to set it again on another struct file that already exists

I didn't follow this, could you explain more?

Quoted 1 line

- probably is insecure when used on hugetlbfs.

The usecase is not expected to prevent all writes, indeed the usecase requires existing mmaps to continue to be able to write into the memory map. So would you call that a security issue too? The use of the seal wants to allow existing mmap regions to be continue to be written into (I mentioned more details in the cover letter).

Quoted 4 lines

I see two reasonable solutions:

1. Don’t fiddle with the struct file at all. Instead make the inode flag work by itself.

Currently, the various VFS paths check only the struct file's f_mode to deny writes of already opened files. This would mean more checking in all those paths (and modification of all those paths).

Anyway going with that idea, we could
1. call deny_write_access(file) from the memfd's seal path which decrements the inode::i_writecount.
2. call get_write_access(inode) in the various VFS paths in addition to checking for FMODE_*WRITE and deny the write (incase i_writecount is negative)

Quoted 3 lines

That will prevent both reopens, and writes from succeeding. However I worry a bit about 2 not being too familiar with VFS internals, about what the consequences of doing that may be.

Quoted 5 lines

IMHO, modifying both the inode and the struct file separately is fine, since they mean different things. In regular filesystems, it's fine to have a read-write open file description for a file whose inode grants write permission to nobody. Speaking of which: is fchmod enough to prevent this attack?

Quoted 8 lines

Well, yes and no. fchmod does prevent reopening the file RW, but anyone with permissions (owner, CAP_FOWNER) can just fchmod it back. A seal is supposed to be irrevocable, so fchmod-as-inode-seal probably isn't sufficient by itself. While it might be good enough for Android (in the sense that it'll prevent RW-reopens from other security contexts to which we send an open memfd file), it's still conceptually ugly, IMHO. Let's go with the original approach of just tweaking the inode so that open-for-write is permanently blocked.

Quoted 9 lines

Agreed with the idea of modifying both file and inode flags. I was thinking modifying i_mode may do the trick but as you pointed it probably could be reverted by chmod or some other attribute setting calls.

OTOH, I don't think deny_write_access(file) can be reverted from any user-facing path so we could do that from the seal to prevent the future opens in write mode. I'll double check and test that out tomorrow.

This seems considerably more complicated and more fragile than needed. Just add a new F_SEAL_WRITE_FUTURE. Grep for F_SEAL_WRITE and make the _FUTURE variant work exactly like it with two exceptions:

Quoted 8 lines
Quoted 2 lines

- shmem_mmap and maybe its hugetlbfs equivalent should check for it and act accordingly.

There's more to it than that, we also need to block future writes through write syscall, so we have to hook into the write path too once the seal is set, not just the mmap. That means we have to add code in mm/shmem.c to do that in all those handlers, to check for the seal (and hope we didn't miss a file_operations handler). Is that what you are proposing?

The existing code already does this. That’s why I suggested grepping :)

Quoted 4 lines

Also, it means we have to keep CONFIG_TMPFS enabled so that the shmem_file_operations write handlers like write_iter are hooked up. Currently memfd works even with !CONFIG_TMPFS.

If so, that sounds like it may already be a bug.

Quoted 9 lines
Quoted 4 lines

- add_seals won’t need the wait_for_pins and mapping_deny_write logic.

That really should be all that’s needed.

It seems a fair idea what you're saying. But I don't see how its less complex.. IMO its far more simple to have VFS do the denial of the operations based on the flags of its datastructures.. and if it works (which I will test to be sure it will), then we should be good.

I agree it’s complicated, but the code is already written. You should just need to adjust some masks.

Quoted 3 lines

Btw by any chance, are you also coming by LPC conference next week?

No. I’d like to, but I can’t make the trip this year.

Quoted 4 lines

thanks!

- Joel

#18 lore raw
Quoted 101 lines · Andy Lutomirski
Quoted 101 lines · Joel Fernandes
Quoted 97 lines · Andy Lutomirski
Quoted 79 lines
Quoted 70 lines · Joel Fernandes
Quoted 5 lines · Daniel Colascione
Quoted 3 lines · Daniel Colascione

On Sat, Nov 10, 2018 at 10:24 AM, Joel Fernandes <[email protected]> wrote:
Thanks Andy for your thoughts, my comments below:

[snip]

Quoted 56 lines
Quoted 52 lines

I don't see it as warty, different seals will work differently. It works quite well for our usecase, and since Linux is all about solving real problems in the real work, it would be useful to have it.

Quoted 1 line

- causes a probably-observable effect in the file mode in F_GETFL.

Wouldn't that be the right thing to observe anyway?

Quoted 1 line

- causes reopen to fail.

So this concern isn't true anymore if we make reopen fail only for WRITE opens as Daniel suggested. I will make this change so that the security fix is a clean one.

Quoted 1 line

- does *not* affect other struct files that may already exist on the same inode.

TBH if you really want to block all writes to the file, then you want F_SEAL_WRITE, not this seal. The usecase we have is the fd is sent over IPC to another process and we want to prevent any new writes in the receiver side. There is no way this other receiving process can have an existing fd unless it was already sent one without the seal applied. The proposed seal could be renamed to F_SEAL_FD_WRITE if that is preferred.

Quoted 3 lines

- mysteriously malfunctions if you try to set it again on another struct file that already exists

I didn't follow this, could you explain more?

Quoted 1 line

- probably is insecure when used on hugetlbfs.

The usecase is not expected to prevent all writes, indeed the usecase requires existing mmaps to continue to be able to write into the memory map. So would you call that a security issue too? The use of the seal wants to allow existing mmap regions to be continue to be written into (I mentioned more details in the cover letter).

Quoted 4 lines

I see two reasonable solutions:

1. Don’t fiddle with the struct file at all. Instead make the inode flag work by itself.

Currently, the various VFS paths check only the struct file's f_mode to deny writes of already opened files. This would mean more checking in all those paths (and modification of all those paths).

Anyway going with that idea, we could
1. call deny_write_access(file) from the memfd's seal path which decrements the inode::i_writecount.
2. call get_write_access(inode) in the various VFS paths in addition to checking for FMODE_*WRITE and deny the write (incase i_writecount is negative)

Quoted 3 lines

That will prevent both reopens, and writes from succeeding. However I worry a bit about 2 not being too familiar with VFS internals, about what the consequences of doing that may be.

Quoted 5 lines

IMHO, modifying both the inode and the struct file separately is fine, since they mean different things. In regular filesystems, it's fine to have a read-write open file description for a file whose inode grants write permission to nobody. Speaking of which: is fchmod enough to prevent this attack?

Quoted 8 lines

Well, yes and no. fchmod does prevent reopening the file RW, but anyone with permissions (owner, CAP_FOWNER) can just fchmod it back. A seal is supposed to be irrevocable, so fchmod-as-inode-seal probably isn't sufficient by itself. While it might be good enough for Android (in the sense that it'll prevent RW-reopens from other security contexts to which we send an open memfd file), it's still conceptually ugly, IMHO. Let's go with the original approach of just tweaking the inode so that open-for-write is permanently blocked.

Quoted 9 lines

Agreed with the idea of modifying both file and inode flags. I was thinking modifying i_mode may do the trick but as you pointed it probably could be reverted by chmod or some other attribute setting calls.

OTOH, I don't think deny_write_access(file) can be reverted from any user-facing path so we could do that from the seal to prevent the future opens in write mode. I'll double check and test that out tomorrow.

This seems considerably more complicated and more fragile than needed. Just add a new F_SEAL_WRITE_FUTURE. Grep for F_SEAL_WRITE and make the _FUTURE variant work exactly like it with two exceptions:

- shmem_mmap and maybe its hugetlbfs equivalent should check for it and act accordingly.

Quoted 7 lines
Quoted 5 lines

There's more to it than that, we also need to block future writes through write syscall, so we have to hook into the write path too once the seal is set, not just the mmap. That means we have to add code in mm/shmem.c to do that in all those handlers, to check for the seal (and hope we didn't miss a file_operations handler). Is that what you are proposing?

The existing code already does this. That’s why I suggested grepping :)

Ahh sorry I see your point now. Ok let me try this approach. Thank you! Probably we can make this work this way and it is sufficient.

Quoted 6 lines
Quoted 4 lines

Also, it means we have to keep CONFIG_TMPFS enabled so that the shmem_file_operations write handlers like write_iter are hooked up. Currently memfd works even with !CONFIG_TMPFS.

If so, that sounds like it may already be a bug.

Actually, its not a bug. If CONFIG_TMPFS is disabled, then IIRC write syscall will be prevented anyway and then the mmap is the only way. I'll double check that once I work on this idea.

Quoted 5 lines
Quoted 5 lines
Quoted 4 lines

- add_seals won’t need the wait_for_pins and mapping_deny_write logic.

That really should be all that’s needed.

Quoted 8 lines
Quoted 4 lines

It seems a fair idea what you're saying. But I don't see how its less complex.. IMO its far more simple to have VFS do the denial of the operations based on the flags of its datastructures.. and if it works (which I will test to be sure it will), then we should be good.

I agree it’s complicated, but the code is already written. You should just need to adjust some masks.

Right.

Quoted 5 lines
Quoted 3 lines

Btw by any chance, are you also coming by LPC conference next week?

No. I’d like to, but I can’t make the trip this year.

Ok, no worries.

thanks,

- Joel

#19 lore raw
In reply to Andy Lutomirski

On Sat, Nov 10, 2018 at 07:40:10PM -0800, Andy Lutomirski wrote:
[...]

Quoted 71 lines
Quoted 48 lines
Quoted 48 lines
Quoted 34 lines
Quoted 25 lines
Quoted 19 lines
Quoted 15 lines
Quoted 4 lines

I see two reasonable solutions:

1. Don’t fiddle with the struct file at all. Instead make the inode flag work by itself.

Currently, the various VFS paths check only the struct file's f_mode to deny writes of already opened files. This would mean more checking in all those paths (and modification of all those paths).

Anyway going with that idea, we could
1. call deny_write_access(file) from the memfd's seal path which decrements the inode::i_writecount.
2. call get_write_access(inode) in the various VFS paths in addition to checking for FMODE_*WRITE and deny the write (incase i_writecount is negative)

Quoted 3 lines

That will prevent both reopens, and writes from succeeding. However I worry a bit about 2 not being too familiar with VFS internals, about what the consequences of doing that may be.

Quoted 5 lines

IMHO, modifying both the inode and the struct file separately is fine, since they mean different things. In regular filesystems, it's fine to have a read-write open file description for a file whose inode grants write permission to nobody. Speaking of which: is fchmod enough to prevent this attack?

Quoted 8 lines

Well, yes and no. fchmod does prevent reopening the file RW, but anyone with permissions (owner, CAP_FOWNER) can just fchmod it back. A seal is supposed to be irrevocable, so fchmod-as-inode-seal probably isn't sufficient by itself. While it might be good enough for Android (in the sense that it'll prevent RW-reopens from other security contexts to which we send an open memfd file), it's still conceptually ugly, IMHO. Let's go with the original approach of just tweaking the inode so that open-for-write is permanently blocked.

Quoted 9 lines

Agreed with the idea of modifying both file and inode flags. I was thinking modifying i_mode may do the trick but as you pointed it probably could be reverted by chmod or some other attribute setting calls.

OTOH, I don't think deny_write_access(file) can be reverted from any user-facing path so we could do that from the seal to prevent the future opens in write mode. I'll double check and test that out tomorrow.

This seems considerably more complicated and more fragile than needed. Just add a new F_SEAL_WRITE_FUTURE. Grep for F_SEAL_WRITE and make the _FUTURE variant work exactly like it with two exceptions:

Quoted 8 lines
Quoted 2 lines

- shmem_mmap and maybe its hugetlbfs equivalent should check for it and act accordingly.

There's more to it than that, we also need to block future writes through write syscall, so we have to hook into the write path too once the seal is set, not just the mmap. That means we have to add code in mm/shmem.c to do that in all those handlers, to check for the seal (and hope we didn't miss a file_operations handler). Is that what you are proposing?

The existing code already does this. That’s why I suggested grepping :)

Quoted 4 lines

Also, it means we have to keep CONFIG_TMPFS enabled so that the shmem_file_operations write handlers like write_iter are hooked up. Currently memfd works even with !CONFIG_TMPFS.

If so, that sounds like it may already be a bug.

Quoted 5 lines
Quoted 4 lines

- add_seals won’t need the wait_for_pins and mapping_deny_write logic.

That really should be all that’s needed.

Quoted 8 lines
Quoted 4 lines

It seems a fair idea what you're saying. But I don't see how its less complex.. IMO its far more simple to have VFS do the denial of the operations based on the flags of its datastructures.. and if it works (which I will test to be sure it will), then we should be good.

I agree it’s complicated, but the code is already written. You should just need to adjust some masks.

Its actually not that bad and a great idea, I did something like the following and it works pretty well. I would say its cleaner than the old approach for sure (and I also added a /proc/pid/fd/N reopen test to the selftest and made sure that issue goes away).

Side note: One subtelty I discovered from the existing selftests is once the F_SEAL_WRITE are active, an mmap of PROT_READ and MAP_SHARED region is expected to fail. This is also evident from this code in mmap_region:

		if (vm_flags & VM_SHARED) {
			error = mapping_map_writable(file->f_mapping);
			if (error)
				goto allow_write_and_free_vma;
		}

---8<-----------------------

From: "Joel Fernandes (Google)" <[email protected]>
Subject: [PATCH] mm/memfd: implement future write seal using shmem ops

---
 fs/hugetlbfs/inode.c |  2 +-
 mm/memfd.c           | 19 -------------------
 mm/shmem.c           | 13 ++++++++++---
 3 files changed, 11 insertions(+), 23 deletions(-)
fs/hugetlbfs/inode.c +1 -1
index 32920a10100e..1978581abfdf 100644
@@ -530,7 +530,7 @@ static long hugetlbfs_punch_hole(struct inode *inode, loff_t offset, loff_t len)
 		inode_lock(inode);
 
 		/* protected by i_mutex */
-		if (info->seals & F_SEAL_WRITE) {
+		if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE)) {
 			inode_unlock(inode);
 			return -EPERM;
 		}
mm/memfd.c +0 -19
index 5ba9804e9515..a9ece5fab439 100644
@@ -220,25 +220,6 @@ static int memfd_add_seals(struct file *file, unsigned int seals)
 		}
 	}
 
-	if ((seals & F_SEAL_FUTURE_WRITE) &&
-	    !(*file_seals & F_SEAL_FUTURE_WRITE)) {
-		/*
-		 * The FUTURE_WRITE seal also prevents growing and shrinking
-		 * so we need them to be already set, or requested now.
-		 */
-		int test_seals = (seals | *file_seals) &
-				 (F_SEAL_GROW | F_SEAL_SHRINK);
-
-		if (test_seals != (F_SEAL_GROW | F_SEAL_SHRINK)) {
-			error = -EINVAL;
-			goto unlock;
-		}
-
-		spin_lock(&file->f_lock);
-		file->f_mode &= ~(FMODE_WRITE | FMODE_PWRITE);
-		spin_unlock(&file->f_lock);
-	}
-
 	*file_seals |= seals;
 	error = 0;
 
mm/shmem.c +10 -3
index 446942677cd4..7dad7efd8b99 100644
@@ -2163,6 +2163,12 @@ int shmem_lock(struct file *file, int lock, struct user_struct *user)
 
 static int shmem_mmap(struct file *file, struct vm_area_struct *vma)
 {
+	struct shmem_inode_info *info = SHMEM_I(file_inode(file));
+
+	/* New shared mmaps are not allowed when "future write" seal active. */
+	if ((vma->vm_flags & VM_SHARED) && (info->seals & F_SEAL_FUTURE_WRITE))
+		return -EPERM;
+
 	file_accessed(file);
 	vma->vm_ops = &shmem_vm_ops;
 	if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE) &&
@@ -2391,8 +2397,9 @@ shmem_write_begin(struct file *file, struct address_space *mapping,
 	pgoff_t index = pos >> PAGE_SHIFT;
 
 	/* i_mutex is held by caller */
-	if (unlikely(info->seals & (F_SEAL_WRITE | F_SEAL_GROW))) {
-		if (info->seals & F_SEAL_WRITE)
+	if (unlikely(info->seals & (F_SEAL_GROW |
+				   F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))) {
+		if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))
 			return -EPERM;
 		if ((info->seals & F_SEAL_GROW) && pos + len > inode->i_size)
 			return -EPERM;
@@ -2657,7 +2664,7 @@ static long shmem_fallocate(struct file *file, int mode, loff_t offset,
 		DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq);
 
 		/* protected by i_mutex */
-		if (info->seals & F_SEAL_WRITE) {
+		if (info->seals & F_SEAL_WRITE || info->seals & F_SEAL_FUTURE_WRITE) {
 			error = -EPERM;
 			goto out;
 		}
Signature · 1 line
2.19.1.930.g4563a0d9d0-goog
#20 lore raw
Quoted 67 lines · Joel Fernandes

On Sat, Nov 10, 2018 at 07:40:10PM -0800, Andy Lutomirski wrote:
[...]

Quoted 65 lines
Quoted 48 lines
Quoted 48 lines
Quoted 34 lines
Quoted 25 lines
Quoted 19 lines
Quoted 15 lines
Quoted 4 lines

I see two reasonable solutions:

1. Don’t fiddle with the struct file at all. Instead make the inode flag work by itself.

Currently, the various VFS paths check only the struct file's f_mode to deny writes of already opened files. This would mean more checking in all those paths (and modification of all those paths).

Anyway going with that idea, we could
1. call deny_write_access(file) from the memfd's seal path which decrements the inode::i_writecount.
2. call get_write_access(inode) in the various VFS paths in addition to checking for FMODE_*WRITE and deny the write (incase i_writecount is negative)

Quoted 3 lines

That will prevent both reopens, and writes from succeeding. However I worry a bit about 2 not being too familiar with VFS internals, about what the consequences of doing that may be.

Quoted 5 lines

IMHO, modifying both the inode and the struct file separately is fine, since they mean different things. In regular filesystems, it's fine to have a read-write open file description for a file whose inode grants write permission to nobody. Speaking of which: is fchmod enough to prevent this attack?

Quoted 8 lines

Well, yes and no. fchmod does prevent reopening the file RW, but anyone with permissions (owner, CAP_FOWNER) can just fchmod it back. A seal is supposed to be irrevocable, so fchmod-as-inode-seal probably isn't sufficient by itself. While it might be good enough for Android (in the sense that it'll prevent RW-reopens from other security contexts to which we send an open memfd file), it's still conceptually ugly, IMHO. Let's go with the original approach of just tweaking the inode so that open-for-write is permanently blocked.

Quoted 9 lines

Agreed with the idea of modifying both file and inode flags. I was thinking modifying i_mode may do the trick but as you pointed it probably could be reverted by chmod or some other attribute setting calls.

OTOH, I don't think deny_write_access(file) can be reverted from any user-facing path so we could do that from the seal to prevent the future opens in write mode. I'll double check and test that out tomorrow.

This seems considerably more complicated and more fragile than needed. Just add a new F_SEAL_WRITE_FUTURE. Grep for F_SEAL_WRITE and make the _FUTURE variant work exactly like it with two exceptions:

Quoted 8 lines
Quoted 2 lines

- shmem_mmap and maybe its hugetlbfs equivalent should check for it and act accordingly.

There's more to it than that, we also need to block future writes through write syscall, so we have to hook into the write path too once the seal is set, not just the mmap. That means we have to add code in mm/shmem.c to do that in all those handlers, to check for the seal (and hope we didn't miss a file_operations handler). Is that what you are proposing?

The existing code already does this. That’s why I suggested grepping :)

Quoted 4 lines

Also, it means we have to keep CONFIG_TMPFS enabled so that the shmem_file_operations write handlers like write_iter are hooked up. Currently memfd works even with !CONFIG_TMPFS.

If so, that sounds like it may already be a bug.

Why shouldn't memfd work independently of CONFIG_TMPFS? In particular, write(2) on tmpfs FDs shouldn't work differently. If it does, that's a kernel implementation detail leaking out into userspace.

Quoted 18 lines
Quoted 4 lines
Quoted 4 lines
Quoted 3 lines

- add_seals won’t need the wait_for_pins and mapping_deny_write logic.

That really should be all that’s needed.

Quoted 8 lines
Quoted 4 lines

It seems a fair idea what you're saying. But I don't see how its less complex.. IMO its far more simple to have VFS do the denial of the operations based on the flags of its datastructures.. and if it works (which I will test to be sure it will), then we should be good.

I agree it’s complicated, but the code is already written. You should just need to adjust some masks.

Its actually not that bad and a great idea, I did something like the following and it works pretty well. I would say its cleaner than the old approach for sure (and I also added a /proc/pid/fd/N reopen test to the selftest and made sure that issue goes away).

Quoted 9 lines

Side note: One subtelty I discovered from the existing selftests is once the F_SEAL_WRITE are active, an mmap of PROT_READ and MAP_SHARED region is expected to fail. This is also evident from this code in mmap_region:

                if (vm_flags & VM_SHARED) {
                        error = mapping_map_writable(file->f_mapping);
                        if (error)
                                goto allow_write_and_free_vma;
                }

This behavior seems like a bug. Why should MAP_SHARED writes be denied here? There's no semantic incompatibility between shared mappings and the seal. And I think this change would represent an ABI break using memfd seals for ashmem, since ashmem currently allows MAP_SHARED mappings after changing prot_mask.

Quoted 17 lines

---8<-----------------------

From: "Joel Fernandes (Google)" <[email protected]>
Subject: [PATCH] mm/memfd: implement future write seal using shmem ops

---
 fs/hugetlbfs/inode.c |  2 +-
 mm/memfd.c           | 19 -------------------
 mm/shmem.c           | 13 ++++++++++---
 3 files changed, 11 insertions(+), 23 deletions(-)
fs/hugetlbfs/inode.c +0 -0
index 32920a10100e..1978581abfdf 100644

fs/hugetlbfs/inode.c static long hugetlbfs_punch_hole(struct inode *inode, loff_t offset, loff_t len) · line 536

Quoted 8 lines
fs/hugetlbfs/inode.c +1 -1
@@ -530,7 +530,7 @@ static long hugetlbfs_punch_hole(struct inode *inode, loff_t offset, loff_t len)
                inode_lock(inode);
 
                /* protected by i_mutex */
-               if (info->seals & F_SEAL_WRITE) {
+               if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE)) {
                        inode_unlock(inode);
                        return -EPERM;
                }

Maybe we can always set F_SEAL_FUTURE_WRITE when F_SEAL_WRITE so we can just test one bit except where the F_SEAL_WRITE behavior differs from F_SEAL_FUTURE_WRITE.

#21 lore raw
Quoted 106 lines · Daniel Colascione
Quoted 69 lines · Joel Fernandes

On Sat, Nov 10, 2018 at 07:40:10PM -0800, Andy Lutomirski wrote:
[...]

Quoted 65 lines
Quoted 48 lines
Quoted 48 lines
Quoted 34 lines
Quoted 25 lines
Quoted 19 lines
Quoted 15 lines
Quoted 4 lines

I see two reasonable solutions:

1. Don’t fiddle with the struct file at all. Instead make the inode flag work by itself.

Currently, the various VFS paths check only the struct file's f_mode to deny writes of already opened files. This would mean more checking in all those paths (and modification of all those paths).

Anyway going with that idea, we could
1. call deny_write_access(file) from the memfd's seal path which decrements the inode::i_writecount.
2. call get_write_access(inode) in the various VFS paths in addition to checking for FMODE_*WRITE and deny the write (incase i_writecount is negative)

Quoted 3 lines

That will prevent both reopens, and writes from succeeding. However I worry a bit about 2 not being too familiar with VFS internals, about what the consequences of doing that may be.

Quoted 5 lines

IMHO, modifying both the inode and the struct file separately is fine, since they mean different things. In regular filesystems, it's fine to have a read-write open file description for a file whose inode grants write permission to nobody. Speaking of which: is fchmod enough to prevent this attack?

Quoted 8 lines

Well, yes and no. fchmod does prevent reopening the file RW, but anyone with permissions (owner, CAP_FOWNER) can just fchmod it back. A seal is supposed to be irrevocable, so fchmod-as-inode-seal probably isn't sufficient by itself. While it might be good enough for Android (in the sense that it'll prevent RW-reopens from other security contexts to which we send an open memfd file), it's still conceptually ugly, IMHO. Let's go with the original approach of just tweaking the inode so that open-for-write is permanently blocked.

Quoted 9 lines

Agreed with the idea of modifying both file and inode flags. I was thinking modifying i_mode may do the trick but as you pointed it probably could be reverted by chmod or some other attribute setting calls.

OTOH, I don't think deny_write_access(file) can be reverted from any user-facing path so we could do that from the seal to prevent the future opens in write mode. I'll double check and test that out tomorrow.

This seems considerably more complicated and more fragile than needed. Just add a new F_SEAL_WRITE_FUTURE. Grep for F_SEAL_WRITE and make the _FUTURE variant work exactly like it with two exceptions:

Quoted 8 lines
Quoted 2 lines

- shmem_mmap and maybe its hugetlbfs equivalent should check for it and act accordingly.

There's more to it than that, we also need to block future writes through write syscall, so we have to hook into the write path too once the seal is set, not just the mmap. That means we have to add code in mm/shmem.c to do that in all those handlers, to check for the seal (and hope we didn't miss a file_operations handler). Is that what you are proposing?

The existing code already does this. That’s why I suggested grepping :)

Quoted 4 lines

Also, it means we have to keep CONFIG_TMPFS enabled so that the shmem_file_operations write handlers like write_iter are hooked up. Currently memfd works even with !CONFIG_TMPFS.

If so, that sounds like it may already be a bug.

Why shouldn't memfd work independently of CONFIG_TMPFS? In particular, write(2) on tmpfs FDs shouldn't work differently. If it does, that's a kernel implementation detail leaking out into userspace.

Quoted 18 lines
Quoted 4 lines
Quoted 4 lines
Quoted 3 lines

- add_seals won’t need the wait_for_pins and mapping_deny_write logic.

That really should be all that’s needed.

Quoted 8 lines
Quoted 4 lines

It seems a fair idea what you're saying. But I don't see how its less complex.. IMO its far more simple to have VFS do the denial of the operations based on the flags of its datastructures.. and if it works (which I will test to be sure it will), then we should be good.

I agree it’s complicated, but the code is already written. You should just need to adjust some masks.

Its actually not that bad and a great idea, I did something like the following and it works pretty well. I would say its cleaner than the old approach for sure (and I also added a /proc/pid/fd/N reopen test to the selftest and made sure that issue goes away).

Quoted 9 lines

Side note: One subtelty I discovered from the existing selftests is once the F_SEAL_WRITE are active, an mmap of PROT_READ and MAP_SHARED region is expected to fail. This is also evident from this code in mmap_region:

               if (vm_flags & VM_SHARED) {
                       error = mapping_map_writable(file->f_mapping);
                       if (error)
                               goto allow_write_and_free_vma;
               }
Quoted 5 lines

This behavior seems like a bug. Why should MAP_SHARED writes be denied here? There's no semantic incompatibility between shared mappings and the seal. And I think this change would represent an ABI break using memfd seals for ashmem, since ashmem currently allows MAP_SHARED mappings after changing prot_mask.

Hmm. I’m guessing the intent is that the mmap count should track writable mappings in addition to mappings that could be made writable using mprotect. I think you could address this for SEAL_FUTURE in two ways:

1. In shmem_mmap, mask off VM_MAYWRITE if SEAL_FUTURE is set, or

2. Add a new vm operation that allows a vma to reject an mprotect attempt, like security_file_mprotect but per vma. Then give it reasonable semantics for shmem.

(1) probably gives the semantics you want for SEAL_FUTURE: old maps can be mprotected, but new maps can’t.

Quoted 20 lines
Quoted 20 lines

---8<-----------------------

From: "Joel Fernandes (Google)" <[email protected]>
Subject: [PATCH] mm/memfd: implement future write seal using shmem ops

---

fs/hugetlbfs/inode.c |  2 +-
mm/memfd.c           | 19 -------------------
mm/shmem.c           | 13 ++++++++++---
3 files changed, 11 insertions(+), 23 deletions(-)
fs/hugetlbfs/inode.c +0 -0
index 32920a10100e..1978581abfdf 100644
@@ -530,7 +530,7 @@ static long hugetlbfs_punch_hole(struct inode *inode, loff_t offset, loff_t len)
               inode_lock(inode);
 
Quoted 10 lines

fs/hugetlbfs/inode.c static long hugetlbfs_punch_hole(struct inode *inode, loff_t offset, loff_t len) · line 536

Quoted 6 lines
fs/hugetlbfs/inode.c +1 -1
               /* protected by i_mutex */
-               if (info->seals & F_SEAL_WRITE) {
+               if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE)) {
                       inode_unlock(inode);
                       return -EPERM;
               }

Maybe we can always set F_SEAL_FUTURE_WRITE when F_SEAL_WRITE so we can just test one bit except where the F_SEAL_WRITE behavior differs from F_SEAL_FUTURE_WRITE.

This could plausibly confuse existing users that read the seal mask.

#22 lore raw

On Sun, Nov 11, 2018 at 07:14:33AM -0800, Andy Lutomirski wrote:
[...]

Quoted 108 lines
Quoted 98 lines
Quoted 57 lines
Quoted 57 lines
Quoted 56 lines
Quoted 44 lines
Quoted 34 lines
Quoted 25 lines
Quoted 19 lines
Quoted 15 lines
Quoted 4 lines

I see two reasonable solutions:

1. Don’t fiddle with the struct file at all. Instead make the inode flag work by itself.

Currently, the various VFS paths check only the struct file's f_mode to deny writes of already opened files. This would mean more checking in all those paths (and modification of all those paths).

Anyway going with that idea, we could
1. call deny_write_access(file) from the memfd's seal path which decrements the inode::i_writecount.
2. call get_write_access(inode) in the various VFS paths in addition to checking for FMODE_*WRITE and deny the write (incase i_writecount is negative)

Quoted 3 lines

That will prevent both reopens, and writes from succeeding. However I worry a bit about 2 not being too familiar with VFS internals, about what the consequences of doing that may be.

Quoted 5 lines

IMHO, modifying both the inode and the struct file separately is fine, since they mean different things. In regular filesystems, it's fine to have a read-write open file description for a file whose inode grants write permission to nobody. Speaking of which: is fchmod enough to prevent this attack?

Quoted 8 lines

Well, yes and no. fchmod does prevent reopening the file RW, but anyone with permissions (owner, CAP_FOWNER) can just fchmod it back. A seal is supposed to be irrevocable, so fchmod-as-inode-seal probably isn't sufficient by itself. While it might be good enough for Android (in the sense that it'll prevent RW-reopens from other security contexts to which we send an open memfd file), it's still conceptually ugly, IMHO. Let's go with the original approach of just tweaking the inode so that open-for-write is permanently blocked.

Quoted 9 lines

Agreed with the idea of modifying both file and inode flags. I was thinking modifying i_mode may do the trick but as you pointed it probably could be reverted by chmod or some other attribute setting calls.

OTOH, I don't think deny_write_access(file) can be reverted from any user-facing path so we could do that from the seal to prevent the future opens in write mode. I'll double check and test that out tomorrow.

Quoted 6 lines

This seems considerably more complicated and more fragile than needed. Just add a new F_SEAL_WRITE_FUTURE. Grep for F_SEAL_WRITE and make the _FUTURE variant work exactly like it with two exceptions:

- shmem_mmap and maybe its hugetlbfs equivalent should check for it and act accordingly.

There's more to it than that, we also need to block future writes through write syscall, so we have to hook into the write path too once the seal is set, not just the mmap. That means we have to add code in mm/shmem.c to do that in all those handlers, to check for the seal (and hope we didn't miss a file_operations handler). Is that what you are proposing?

Quoted 8 lines
Quoted 8 lines

The existing code already does this. That’s why I suggested grepping :)

Quoted 4 lines

Also, it means we have to keep CONFIG_TMPFS enabled so that the shmem_file_operations write handlers like write_iter are hooked up. Currently memfd works even with !CONFIG_TMPFS.

If so, that sounds like it may already be a bug.

Why shouldn't memfd work independently of CONFIG_TMPFS? In particular, write(2) on tmpfs FDs shouldn't work differently. If it does, that's a kernel implementation detail leaking out into userspace.

Quoted 18 lines
Quoted 4 lines
Quoted 4 lines
Quoted 3 lines

- add_seals won’t need the wait_for_pins and mapping_deny_write logic.

That really should be all that’s needed.

Quoted 8 lines
Quoted 4 lines

It seems a fair idea what you're saying. But I don't see how its less complex.. IMO its far more simple to have VFS do the denial of the operations based on the flags of its datastructures.. and if it works (which I will test to be sure it will), then we should be good.

I agree it’s complicated, but the code is already written. You should just need to adjust some masks.

Its actually not that bad and a great idea, I did something like the following and it works pretty well. I would say its cleaner than the old approach for sure (and I also added a /proc/pid/fd/N reopen test to the selftest and made sure that issue goes away).

Quoted 9 lines

Side note: One subtelty I discovered from the existing selftests is once the F_SEAL_WRITE are active, an mmap of PROT_READ and MAP_SHARED region is expected to fail. This is also evident from this code in mmap_region:

               if (vm_flags & VM_SHARED) {
                       error = mapping_map_writable(file->f_mapping);
                       if (error)
                               goto allow_write_and_free_vma;
               }
Quoted 5 lines

This behavior seems like a bug. Why should MAP_SHARED writes be denied here? There's no semantic incompatibility between shared mappings and the seal. And I think this change would represent an ABI break using memfd seals for ashmem, since ashmem currently allows MAP_SHARED mappings after changing prot_mask.

Hmm. I’m guessing the intent is that the mmap count should track writable mappings in addition to mappings that could be made writable using mprotect. I think you could address this for SEAL_FUTURE in two ways:

Quoted 8 lines

1. In shmem_mmap, mask off VM_MAYWRITE if SEAL_FUTURE is set, or

2. Add a new vm operation that allows a vma to reject an mprotect attempt, like security_file_mprotect but per vma. Then give it reasonable semantics for shmem.

(1) probably gives the semantics you want for SEAL_FUTURE: old maps can be mprotected, but new maps can’t.

Thanks Andy and Daniel! This occured to me too and I like the solution in (1). I tested that now PROT_READ + MAP_SHARED works and the mrprotect is not able to revert the protection. In fact (1) is exactly what we do in the ashmem driver.

The updated patch now looks like the following:

---8<-----------------------

From: "Joel Fernandes" <[email protected]>
Subject: [PATCH] mm/memfd: implement future write seal using shmem ops

---
 fs/hugetlbfs/inode.c |  2 +-
 mm/memfd.c           | 19 -------------------
 mm/shmem.c           | 24 +++++++++++++++++++++---
 3 files changed, 22 insertions(+), 23 deletions(-)
fs/hugetlbfs/inode.c +1 -1
index 32920a10100e..1978581abfdf 100644
@@ -530,7 +530,7 @@ static long hugetlbfs_punch_hole(struct inode *inode, loff_t offset, loff_t len)
 		inode_lock(inode);
 
 		/* protected by i_mutex */
-		if (info->seals & F_SEAL_WRITE) {
+		if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE)) {
 			inode_unlock(inode);
 			return -EPERM;
 		}
mm/memfd.c +0 -19
index 5ba9804e9515..a9ece5fab439 100644
@@ -220,25 +220,6 @@ static int memfd_add_seals(struct file *file, unsigned int seals)
 		}
 	}
 
-	if ((seals & F_SEAL_FUTURE_WRITE) &&
-	    !(*file_seals & F_SEAL_FUTURE_WRITE)) {
-		/*
-		 * The FUTURE_WRITE seal also prevents growing and shrinking
-		 * so we need them to be already set, or requested now.
-		 */
-		int test_seals = (seals | *file_seals) &
-				 (F_SEAL_GROW | F_SEAL_SHRINK);
-
-		if (test_seals != (F_SEAL_GROW | F_SEAL_SHRINK)) {
-			error = -EINVAL;
-			goto unlock;
-		}
-
-		spin_lock(&file->f_lock);
-		file->f_mode &= ~(FMODE_WRITE | FMODE_PWRITE);
-		spin_unlock(&file->f_lock);
-	}
-
 	*file_seals |= seals;
 	error = 0;
 
mm/shmem.c +21 -3
index 446942677cd4..ef6039f1ea2a 100644
@@ -2163,6 +2163,23 @@ int shmem_lock(struct file *file, int lock, struct user_struct *user)
 
 static int shmem_mmap(struct file *file, struct vm_area_struct *vma)
 {
+	struct shmem_inode_info *info = SHMEM_I(file_inode(file));
+
+	/*
+	 * New PROT_READ and MAP_SHARED mmaps are not allowed when "future
+	 * write" seal active.
+	 */
+	if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_WRITE) &&
+	    (info->seals & F_SEAL_FUTURE_WRITE))
+		return -EPERM;
+
+	/*
+	 * Since the F_SEAL_FUTURE_WRITE seals allow for a MAP_SHARED read-only
+	 * mapping, take care to not allow mprotect to revert protections.
+	 */
+	if (info->seals & F_SEAL_FUTURE_WRITE)
+		vma->vm_flags &= ~(VM_MAYWRITE);
+
 	file_accessed(file);
 	vma->vm_ops = &shmem_vm_ops;
 	if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE) &&
@@ -2391,8 +2408,9 @@ shmem_write_begin(struct file *file, struct address_space *mapping,
 	pgoff_t index = pos >> PAGE_SHIFT;
 
 	/* i_mutex is held by caller */
-	if (unlikely(info->seals & (F_SEAL_WRITE | F_SEAL_GROW))) {
-		if (info->seals & F_SEAL_WRITE)
+	if (unlikely(info->seals & (F_SEAL_GROW |
+				   F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))) {
+		if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))
 			return -EPERM;
 		if ((info->seals & F_SEAL_GROW) && pos + len > inode->i_size)
 			return -EPERM;
@@ -2657,7 +2675,7 @@ static long shmem_fallocate(struct file *file, int mode, loff_t offset,
 		DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq);
 
 		/* protected by i_mutex */
-		if (info->seals & F_SEAL_WRITE) {
+		if (info->seals & F_SEAL_WRITE || info->seals & F_SEAL_FUTURE_WRITE) {
 			error = -EPERM;
 			goto out;
 		}
Signature · 1 line
2.19.1.930.g4563a0d9d0-goog
#23 lore raw
In reply to Joel Fernandes
Quoted 113 lines · Joel Fernandes
Quoted 4 lines · Jann Horn
Quoted 3 lines · Jann Horn
Quoted 1 line · Joel Fernandes (Google)

Android uses ashmem for sharing memory regions. We are looking

forward

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

to migrating all usecases of ashmem to memfd so that we can possibly remove the ashmem driver in the future from staging while also benefiting from using memfd and contributing to it. Note staging

drivers

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

are also not ABI and generally can be removed at anytime.

One of the main usecases Android has is the ability to create a

region

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines

and mmap it as writeable, then add protection against making any "future" writes while keeping the existing already mmap'ed writeable-region active. This allows us to implement a usecase where receivers of the shared memory buffer can get a read-only view, while the sender continues to write to the buffer.
See CursorWindow documentation in Android for more details:
https://developer.android.com/reference/android/database/

CursorWindow

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

This usecase cannot be implemented with the existing F_SEAL_WRITE

seal.

Quoted 1 line
Quoted 1 line
Quoted 1 line

To support the usecase, this patch adds a new F_SEAL_FUTURE_WRITE

seal

Quoted 1 line
Quoted 1 line
Quoted 1 line

which prevents any future mmap and write syscalls from succeeding

while

Quoted 16 lines
Quoted 16 lines
Quoted 1 line

keeping the existing mmap active.

Please CC linux-api@ on patches like this. If you had done that, I might have criticized your v1 patch instead of your v3 patch...

Quoted 2 lines

The following program shows the seal
working in action:

[...]

Quoted 8 lines

---

Quoted 7 lines
Quoted 7 lines

[...]

Quoted 4 lines
mm/memfd.c +0 -0
index 2bb5e257080e..5ba9804e9515 100644

[...]

mm/memfd.c static int memfd_add_seals(struct file *file,

Quoted 1 line
mm/memfd.c +0 -0
@@ -219,6 +220,25 @@ static int memfd_add_seals(struct file *file,

unsigned int seals)

Quoted 7 lines
Quoted 7 lines

mm/memfd.c static int memfd_add_seals(struct file *file, · line 226

Quoted 7 lines
mm/memfd.c +4 -0
                }
        }
 
+       if ((seals & F_SEAL_FUTURE_WRITE) &&
+           !(*file_seals & F_SEAL_FUTURE_WRITE)) {
+               /*
+                * The FUTURE_WRITE seal also prevents growing and

shrinking

Quoted 1 line
Quoted 1 line

mm/memfd.c static int memfd_add_seals(struct file *file, · line 227

Quoted 1 line
mm/memfd.c +1 -0
+                * so we need them to be already set, or requested

now.

Quoted 41 lines
Quoted 41 lines

mm/memfd.c static int memfd_add_seals(struct file *file, · line 240

Quoted 13 lines
mm/memfd.c +13 -0
+                */
+               int test_seals = (seals | *file_seals) &
+                                (F_SEAL_GROW | F_SEAL_SHRINK);
+
+               if (test_seals != (F_SEAL_GROW | F_SEAL_SHRINK)) {
+                       error = -EINVAL;
+                       goto unlock;
+               }
+
+               spin_lock(&file->f_lock);
+               file->f_mode &= ~(FMODE_WRITE | FMODE_PWRITE);
+               spin_unlock(&file->f_lock);
+       }

So you're fiddling around with the file, but not the inode? How are you preventing code like the following from re-opening the file as writable?

$ cat memfd.c
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <printf.h>
#include <fcntl.h>
#include <err.h>
#include <stdio.h>

int main(void) {
int fd = syscall(__NR_memfd_create, "testfd", 0); if (fd == -1) err(1, "memfd");
char path[100];
sprintf(path, "/proc/self/fd/%d", fd); int fd2 = open(path, O_RDWR);
if (fd2 == -1) err(1, "reopen"); printf("reopen successful: %d\n", fd2);
}

$ gcc -o memfd memfd.c
$ ./memfd
reopen successful: 4
$
Quoted 8 lines
Quoted 3 lines

That aside: I wonder whether a better API would be something that allows you to create a new readonly file descriptor, instead of fiddling with the writability of an existing fd.

My favorite approach would be to forbid open() on memfds, hope that nobody notices the tiny API break, and then add an ioctl for "reopen this memfd with reduced permissions" - but that's just my personal opinion.

Quoted 9 lines

I did something along these lines and it fixes the issue, but I forbid open of memfd only when the F_SEAL_FUTURE_WRITE seal is in place. So then its not
an ABI break because this is a brand new seal. That seems the least intrusive
solution and it works. Do you mind testing it and I'll add your and Tested-by
to the new fix? The patch is based on top of this series.

Please don't forbid reopens entirely. You're taking a feature that works generally (reopens) and breaking it in one specific case (memfd write sealed files). The open modes are available in .open in the struct file:
you can deny *only* opens for write instead of denying reopens generally.

#24 lore raw
Quoted 125 lines · Daniel Colascione
Quoted 113 lines · Joel Fernandes
Quoted 4 lines · Jann Horn
Quoted 3 lines · Jann Horn
Quoted 1 line · Joel Fernandes (Google)

Android uses ashmem for sharing memory regions. We are looking

forward

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

to migrating all usecases of ashmem to memfd so that we can possibly remove the ashmem driver in the future from staging while also benefiting from using memfd and contributing to it. Note staging

drivers

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

are also not ABI and generally can be removed at anytime.

One of the main usecases Android has is the ability to create a

region

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines

and mmap it as writeable, then add protection against making any "future" writes while keeping the existing already mmap'ed writeable-region active. This allows us to implement a usecase where receivers of the shared memory buffer can get a read-only view, while the sender continues to write to the buffer.
See CursorWindow documentation in Android for more details:
https://developer.android.com/reference/android/database/

CursorWindow

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

This usecase cannot be implemented with the existing F_SEAL_WRITE

seal.

Quoted 1 line
Quoted 1 line
Quoted 1 line

To support the usecase, this patch adds a new F_SEAL_FUTURE_WRITE

seal

Quoted 1 line
Quoted 1 line
Quoted 1 line

which prevents any future mmap and write syscalls from succeeding

while

Quoted 16 lines
Quoted 16 lines
Quoted 1 line

keeping the existing mmap active.

Please CC linux-api@ on patches like this. If you had done that, I might have criticized your v1 patch instead of your v3 patch...

Quoted 2 lines

The following program shows the seal
working in action:

[...]

Quoted 8 lines

---

Quoted 7 lines
Quoted 7 lines

[...]

Quoted 4 lines
mm/memfd.c +0 -0
index 2bb5e257080e..5ba9804e9515 100644

[...]

mm/memfd.c static int memfd_add_seals(struct file *file,

Quoted 1 line
mm/memfd.c +0 -0
@@ -219,6 +220,25 @@ static int memfd_add_seals(struct file *file,

unsigned int seals)

Quoted 7 lines
Quoted 7 lines

mm/memfd.c static int memfd_add_seals(struct file *file, · line 226

Quoted 7 lines
mm/memfd.c +4 -0
                }
        }
 
+       if ((seals & F_SEAL_FUTURE_WRITE) &&
+           !(*file_seals & F_SEAL_FUTURE_WRITE)) {
+               /*
+                * The FUTURE_WRITE seal also prevents growing and

shrinking

Quoted 1 line
Quoted 1 line

mm/memfd.c static int memfd_add_seals(struct file *file, · line 227

Quoted 1 line
mm/memfd.c +1 -0
+                * so we need them to be already set, or requested

now.

Quoted 41 lines
Quoted 41 lines

mm/memfd.c static int memfd_add_seals(struct file *file, · line 240

Quoted 13 lines
mm/memfd.c +13 -0
+                */
+               int test_seals = (seals | *file_seals) &
+                                (F_SEAL_GROW | F_SEAL_SHRINK);
+
+               if (test_seals != (F_SEAL_GROW | F_SEAL_SHRINK)) {
+                       error = -EINVAL;
+                       goto unlock;
+               }
+
+               spin_lock(&file->f_lock);
+               file->f_mode &= ~(FMODE_WRITE | FMODE_PWRITE);
+               spin_unlock(&file->f_lock);
+       }

So you're fiddling around with the file, but not the inode? How are you preventing code like the following from re-opening the file as writable?

$ cat memfd.c
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <printf.h>
#include <fcntl.h>
#include <err.h>
#include <stdio.h>

int main(void) {
int fd = syscall(__NR_memfd_create, "testfd", 0); if (fd == -1) err(1, "memfd");
char path[100];
sprintf(path, "/proc/self/fd/%d", fd); int fd2 = open(path, O_RDWR);
if (fd2 == -1) err(1, "reopen"); printf("reopen successful: %d\n", fd2);
}

$ gcc -o memfd memfd.c
$ ./memfd
reopen successful: 4
$
Quoted 8 lines
Quoted 3 lines

That aside: I wonder whether a better API would be something that allows you to create a new readonly file descriptor, instead of fiddling with the writability of an existing fd.

My favorite approach would be to forbid open() on memfds, hope that nobody notices the tiny API break, and then add an ioctl for "reopen this memfd with reduced permissions" - but that's just my personal opinion.

Quoted 9 lines

I did something along these lines and it fixes the issue, but I forbid open of memfd only when the F_SEAL_FUTURE_WRITE seal is in place. So then its not
an ABI break because this is a brand new seal. That seems the least intrusive
solution and it works. Do you mind testing it and I'll add your and Tested-by
to the new fix? The patch is based on top of this series.

Quoted 4 lines

Please don't forbid reopens entirely. You're taking a feature that works generally (reopens) and breaking it in one specific case (memfd write sealed files). The open modes are available in .open in the struct file:
you can deny *only* opens for write instead of denying reopens generally.

Yes, as we discussed over chat already, I will implement it that way.

Also lets continue to discuss Andy's concerns he raised on the other thread.

thanks,

- Joel

#25 lore raw
In reply to Jann Horn
Quoted 64 lines · Jann Horn
(quoted diff) +2 -0
+linux-api for API addition
+hughd as FYI since this is somewhat related to mm/shmem
Quoted 15 lines · Joel Fernandes (Google)

Android uses ashmem for sharing memory regions. We are looking forward to migrating all usecases of ashmem to memfd so that we can possibly remove the ashmem driver in the future from staging while also benefiting from using memfd and contributing to it. Note staging drivers are also not ABI and generally can be removed at anytime.

One of the main usecases Android has is the ability to create a region and mmap it as writeable, then add protection against making any "future" writes while keeping the existing already mmap'ed writeable-region active. This allows us to implement a usecase where receivers of the shared memory buffer can get a read-only view, while the sender continues to write to the buffer.
See CursorWindow documentation in Android for more details:
https://developer.android.com/reference/android/database/CursorWindow

Quoted 4 lines

This usecase cannot be implemented with the existing F_SEAL_WRITE seal. To support the usecase, this patch adds a new F_SEAL_FUTURE_WRITE seal which prevents any future mmap and write syscalls from succeeding while keeping the existing mmap active.

Please CC linux-api@ on patches like this. If you had done that, I might have criticized your v1 patch instead of your v3 patch...

Quoted 2 lines

The following program shows the seal
working in action:

[...]

Quoted 8 lines

---

[...]

Quoted 4 lines
mm/memfd.c +0 -0
index 2bb5e257080e..5ba9804e9515 100644

[...]

Quoted 18 lines
mm/memfd.c +14 -0
@@ -219,6 +220,25 @@ static int memfd_add_seals(struct file *file, unsigned int seals)
                }
        }
 
+       if ((seals & F_SEAL_FUTURE_WRITE) &&
+           !(*file_seals & F_SEAL_FUTURE_WRITE)) {
+               /*
+                * The FUTURE_WRITE seal also prevents growing and shrinking
+                * so we need them to be already set, or requested now.
+                */
+               int test_seals = (seals | *file_seals) &
+                                (F_SEAL_GROW | F_SEAL_SHRINK);
+
+               if (test_seals != (F_SEAL_GROW | F_SEAL_SHRINK)) {
+                       error = -EINVAL;
+                       goto unlock;
+               }
+
Quoted 8 lines

mm/memfd.c static int memfd_add_seals(struct file *file, unsigned int seals) · line 240

Quoted 4 lines
mm/memfd.c +4 -0
+               spin_lock(&file->f_lock);
+               file->f_mode &= ~(FMODE_WRITE | FMODE_PWRITE);
+               spin_unlock(&file->f_lock);
+       }

So you're fiddling around with the file, but not the inode? How are you preventing code like the following from re-opening the file as writable?

Good catch. That's fixable too though, isn't it, just by fiddling with the inode, right?

Another, more general fix might be to prevent /proc/pid/fd/N opens from "upgrading" access modes. But that'd be a bigger ABI break.

Quoted 3 lines

That aside: I wonder whether a better API would be something that allows you to create a new readonly file descriptor, instead of fiddling with the writability of an existing fd.

That doesn't work, unfortunately. The ashmem API we're replacing with memfd requires file descriptor continuity. I also looked into opening a new FD and dup2(2)ing atop the old one, but this approach doesn't work in the case that the old FD has already leaked to some other context (e.g., another dup, SCM_RIGHTS). See
https://developer.android.com/ndk/reference/group/memory. We can't break ASharedMemory_setProt.

#26 lore raw
Quoted 78 lines · Daniel Colascione
Quoted 66 lines · Jann Horn
(quoted diff) +2 -0
+linux-api for API addition
+hughd as FYI since this is somewhat related to mm/shmem
Quoted 15 lines · Joel Fernandes (Google)

Android uses ashmem for sharing memory regions. We are looking forward to migrating all usecases of ashmem to memfd so that we can possibly remove the ashmem driver in the future from staging while also benefiting from using memfd and contributing to it. Note staging drivers are also not ABI and generally can be removed at anytime.

One of the main usecases Android has is the ability to create a region and mmap it as writeable, then add protection against making any "future" writes while keeping the existing already mmap'ed writeable-region active. This allows us to implement a usecase where receivers of the shared memory buffer can get a read-only view, while the sender continues to write to the buffer.
See CursorWindow documentation in Android for more details:
https://developer.android.com/reference/android/database/CursorWindow

Quoted 4 lines

This usecase cannot be implemented with the existing F_SEAL_WRITE seal. To support the usecase, this patch adds a new F_SEAL_FUTURE_WRITE seal which prevents any future mmap and write syscalls from succeeding while keeping the existing mmap active.

Please CC linux-api@ on patches like this. If you had done that, I might have criticized your v1 patch instead of your v3 patch...

Quoted 2 lines

The following program shows the seal
working in action:

[...]

Quoted 8 lines

---

[...]

Quoted 4 lines
mm/memfd.c +0 -0
index 2bb5e257080e..5ba9804e9515 100644

[...]

Quoted 18 lines
mm/memfd.c +14 -0
@@ -219,6 +220,25 @@ static int memfd_add_seals(struct file *file, unsigned int seals)
               }
       }
 
+       if ((seals & F_SEAL_FUTURE_WRITE) &&
+           !(*file_seals & F_SEAL_FUTURE_WRITE)) {
+               /*
+                * The FUTURE_WRITE seal also prevents growing and shrinking
+                * so we need them to be already set, or requested now.
+                */
+               int test_seals = (seals | *file_seals) &
+                                (F_SEAL_GROW | F_SEAL_SHRINK);
+
+               if (test_seals != (F_SEAL_GROW | F_SEAL_SHRINK)) {
+                       error = -EINVAL;
+                       goto unlock;
+               }
+
Quoted 8 lines

mm/memfd.c static int memfd_add_seals(struct file *file, unsigned int seals) · line 240

Quoted 4 lines
mm/memfd.c +4 -0
+               spin_lock(&file->f_lock);
+               file->f_mode &= ~(FMODE_WRITE | FMODE_PWRITE);
+               spin_unlock(&file->f_lock);
+       }

So you're fiddling around with the file, but not the inode? How are you preventing code like the following from re-opening the file as writable?

Quoted 2 lines

Good catch. That's fixable too though, isn't it, just by fiddling with the inode, right?

True.

Quoted 3 lines

Another, more general fix might be to prevent /proc/pid/fd/N opens from "upgrading" access modes. But that'd be a bigger ABI break.

I think we should fix that, too. I consider it a bug fix, not an ABI break, personally.

Quoted 5 lines
Quoted 4 lines

That aside: I wonder whether a better API would be something that allows you to create a new readonly file descriptor, instead of fiddling with the writability of an existing fd.

Quoted 7 lines

That doesn't work, unfortunately. The ashmem API we're replacing with memfd requires file descriptor continuity. I also looked into opening a new FD and dup2(2)ing atop the old one, but this approach doesn't work in the case that the old FD has already leaked to some other context (e.g., another dup, SCM_RIGHTS). See
https://developer.android.com/ndk/reference/group/memory. We can't break ASharedMemory_setProt.

Hmm. If we fix the general reopen bug, a way to drop write access from an existing struct file would do what Android needs, right? I don’t know if there are general VFS issues with that.

#27 lore raw
Quoted 4 lines · Andy Lutomirski
Quoted 2 lines

Another, more general fix might be to prevent /proc/pid/fd/N opens from "upgrading" access modes. But that'd be a bigger ABI break.

I think we should fix that, too. I consider it a bug fix, not an ABI break, personally.

Someone, somewhere is probably relying on it though, and that means that we probably can't change it unless it's actually causing problems.

<mumble>spacebar heating</mumble>

Quoted 13 lines
Quoted 11 lines
Quoted 3 lines

That aside: I wonder whether a better API would be something that allows you to create a new readonly file descriptor, instead of fiddling with the writability of an existing fd.

That doesn't work, unfortunately. The ashmem API we're replacing with memfd requires file descriptor continuity. I also looked into opening a new FD and dup2(2)ing atop the old one, but this approach doesn't work in the case that the old FD has already leaked to some other context (e.g., another dup, SCM_RIGHTS). See
https://developer.android.com/ndk/reference/group/memory. We can't break ASharedMemory_setProt.

Quoted 1 line

Hmm. If we fix the general reopen bug, a way to drop write access from an existing struct file would do what Android needs, right? I don’t know if there are general VFS issues with that.

I also proposed that. :-) Maybe it'd work best as a special case of the perennial revoke(2) that people keep proposing. You'd be able to selectively revoke all access or just write access.

#28 lore raw
Quoted 8 lines · Daniel Colascione
Quoted 3 lines · Andy Lutomirski
Quoted 2 lines

Another, more general fix might be to prevent /proc/pid/fd/N opens from "upgrading" access modes. But that'd be a bigger ABI break.

Quoted 7 lines
Quoted 1 line

I think we should fix that, too. I consider it a bug fix, not an ABI break, personally.

Someone, somewhere is probably relying on it though, and that means that we probably can't change it unless it's actually causing problems.

<mumble>spacebar heating</mumble>

I think it has caused problems in the past. It’s certainly extremely surprising behavior. I’d say it should be fixed and, if needed, a sysctl to unfix it might be okay.

Quoted 14 lines
Quoted 14 lines
Quoted 12 lines
Quoted 4 lines

That aside: I wonder whether a better API would be something that allows you to create a new readonly file descriptor, instead of fiddling with the writability of an existing fd.

That doesn't work, unfortunately. The ashmem API we're replacing with memfd requires file descriptor continuity. I also looked into opening a new FD and dup2(2)ing atop the old one, but this approach doesn't work in the case that the old FD has already leaked to some other context (e.g., another dup, SCM_RIGHTS). See
https://developer.android.com/ndk/reference/group/memory. We can't break ASharedMemory_setProt.

Quoted 5 lines
Quoted 1 line

Hmm. If we fix the general reopen bug, a way to drop write access from an existing struct file would do what Android needs, right? I don’t know if there are general VFS issues with that.

I also proposed that. :-) Maybe it'd work best as a special case of the perennial revoke(2) that people keep proposing. You'd be able to selectively revoke all access or just write access.

Sounds good to me, modulo possible races, but that shouldn’t be too hard to deal with.

#29 lore raw
Quoted 13 lines · Andy Lutomirski
Quoted 13 lines
Quoted 13 lines
Quoted 11 lines
Quoted 3 lines

That aside: I wonder whether a better API would be something that allows you to create a new readonly file descriptor, instead of fiddling with the writability of an existing fd.

That doesn't work, unfortunately. The ashmem API we're replacing with memfd requires file descriptor continuity. I also looked into opening a new FD and dup2(2)ing atop the old one, but this approach doesn't work in the case that the old FD has already leaked to some other context (e.g., another dup, SCM_RIGHTS). See
https://developer.android.com/ndk/reference/group/memory. We can't break ASharedMemory_setProt.

Quoted 4 lines
Quoted 4 lines
Quoted 3 lines

Hmm. If we fix the general reopen bug, a way to drop write access from an existing struct file would do what Android needs, right? I don’t know if there are general VFS issues with that.

I don't think there is a way to fix this in /proc/pid/fd. At the proc level, the /proc/pid/fd/N files are just soft symlinks that follow through to the actual file. The open is actually done on that inode/file. I think changing it the way being discussed here means changing the way symlinks work in Linux.

I think the right way to fix this is at the memfd inode level. I am working on a follow up patch on top of this patch, and will send that out in a few days (along with the man page updates).

thanks!

- Joel

#30 lore raw
In reply to Jann Horn
Quoted 20 lines · Jann Horn
(quoted diff) +2 -0
+linux-api for API addition
+hughd as FYI since this is somewhat related to mm/shmem
Quoted 15 lines · Joel Fernandes (Google)

Android uses ashmem for sharing memory regions. We are looking forward to migrating all usecases of ashmem to memfd so that we can possibly remove the ashmem driver in the future from staging while also benefiting from using memfd and contributing to it. Note staging drivers are also not ABI and generally can be removed at anytime.

One of the main usecases Android has is the ability to create a region and mmap it as writeable, then add protection against making any "future" writes while keeping the existing already mmap'ed writeable-region active. This allows us to implement a usecase where receivers of the shared memory buffer can get a read-only view, while the sender continues to write to the buffer.
See CursorWindow documentation in Android for more details:
https://developer.android.com/reference/android/database/CursorWindow

Quoted 7 lines
Quoted 4 lines

This usecase cannot be implemented with the existing F_SEAL_WRITE seal. To support the usecase, this patch adds a new F_SEAL_FUTURE_WRITE seal which prevents any future mmap and write syscalls from succeeding while keeping the existing mmap active.

Please CC linux-api@ on patches like this. If you had done that, I might have criticized your v1 patch instead of your v3 patch...

Ok, will do from next time.

Quoted 62 lines
Quoted 2 lines

The following program shows the seal
working in action:

[...]

Quoted 8 lines

---

[...]

Quoted 4 lines
mm/memfd.c +0 -0
index 2bb5e257080e..5ba9804e9515 100644

[...]

Quoted 12 lines
mm/memfd.c +8 -0
@@ -219,6 +220,25 @@ static int memfd_add_seals(struct file *file, unsigned int seals)
                }
        }
 
+       if ((seals & F_SEAL_FUTURE_WRITE) &&
+           !(*file_seals & F_SEAL_FUTURE_WRITE)) {
+               /*
+                * The FUTURE_WRITE seal also prevents growing and shrinking
+                * so we need them to be already set, or requested now.
+                */
+               int test_seals = (seals | *file_seals) &
+                                (F_SEAL_GROW | F_SEAL_SHRINK);

mm/memfd.c static int memfd_add_seals(struct file *file, unsigned int seals) · line 240

Quoted 10 lines
mm/memfd.c +10 -0
+
+               if (test_seals != (F_SEAL_GROW | F_SEAL_SHRINK)) {
+                       error = -EINVAL;
+                       goto unlock;
+               }
+
+               spin_lock(&file->f_lock);
+               file->f_mode &= ~(FMODE_WRITE | FMODE_PWRITE);
+               spin_unlock(&file->f_lock);
+       }

So you're fiddling around with the file, but not the inode? How are you preventing code like the following from re-opening the file as writable?

$ cat memfd.c
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <printf.h>
#include <fcntl.h>
#include <err.h>
#include <stdio.h>

int main(void) {
int fd = syscall(__NR_memfd_create, "testfd", 0); if (fd == -1) err(1, "memfd");
char path[100];
sprintf(path, "/proc/self/fd/%d", fd); int fd2 = open(path, O_RDWR);
if (fd2 == -1) err(1, "reopen"); printf("reopen successful: %d\n", fd2);
}

Quoted 3 lines
$ gcc -o memfd memfd.c
$ ./memfd
reopen successful: 4

Great catch and this is indeed an issue :-(. I verified it too.

Quoted 3 lines

That aside: I wonder whether a better API would be something that allows you to create a new readonly file descriptor, instead of fiddling with the writability of an existing fd.

Android usecases cannot deal with a new fd number because it breaks the continuity of having the same old fd, as Dan also pointed out.

Also such API will have the same issues you brought up?

thanks,

- Joel

maintainer
#31 lore raw
In reply to Joel Fernandes (Google)
Quoted 6 lines · On Wed, 7 Nov 2018 20:15:36 -0800 "Joel Fernandes (Google)"…

Android uses ashmem for sharing memory regions. We are looking forward to migrating all usecases of ashmem to memfd so that we can possibly remove the ashmem driver in the future from staging while also benefiting from using memfd and contributing to it. Note staging drivers are also not ABI and generally can be removed at anytime.

Quoted 8 lines

One of the main usecases Android has is the ability to create a region and mmap it as writeable, then add protection against making any "future" writes while keeping the existing already mmap'ed writeable-region active. This allows us to implement a usecase where receivers of the shared memory buffer can get a read-only view, while the sender continues to write to the buffer.
See CursorWindow documentation in Android for more details:
https://developer.android.com/reference/android/database/CursorWindow

It appears that the memfd_create and fcntl manpages will require updating. Please attend to this at the appropriate time?

Actually, it would help the review process if those updates were available now.

#32 lore raw
Quoted 17 lines · Andrew Morton
Quoted 6 lines · On Wed, 7 Nov 2018 20:15:36 -0800 "Joel Fernandes (Google)"…

Android uses ashmem for sharing memory regions. We are looking forward to migrating all usecases of ashmem to memfd so that we can possibly remove the ashmem driver in the future from staging while also benefiting from using memfd and contributing to it. Note staging drivers are also not ABI and generally can be removed at anytime.

Quoted 8 lines

One of the main usecases Android has is the ability to create a region and mmap it as writeable, then add protection against making any "future" writes while keeping the existing already mmap'ed writeable-region active. This allows us to implement a usecase where receivers of the shared memory buffer can get a read-only view, while the sender continues to write to the buffer.
See CursorWindow documentation in Android for more details:
https://developer.android.com/reference/android/database/CursorWindow

Quoted 2 lines

It appears that the memfd_create and fcntl manpages will require updating. Please attend to this at the appropriate time?

Yes, I am planning to send those out shortly. I finished working on them.

Also just to let you know, I posted a fix for the security issue Jann Horn reported and requested him to test it:
https://lore.kernel.org/lkml/[email protected]/T/#m8d9d185e6480d095f0ab8f84bcb103892181f77d

This fix along with the 2 other patches I posted in v3 are all that's needed. thanks!

- Joel