Skip to contentSkip to conversation

landlock: add LANDLOCK_SCOPE_MEMFD_EXEC execution

RFC PATCH In review Abhinav Saxena 4 participants 13 messages Jul 19, 2025 – Nov 20, 2025

Subsystems (3)
lore
Share & tools
lore
#0 lore raw

cover landlock: add LANDLOCK_SCOPE_MEMFD_EXEC execution

This patch series introduces LANDLOCK_SCOPE_MEMFD_EXEC, a new Landlock scoping mechanism that restricts execution of anonymous memory file descriptors (memfd) created via memfd_create(2). This addresses security gaps where processes can bypass W^X policies and execute arbitrary code through anonymous memory objects.

SECURITY PROBLEM
================

Current Landlock filesystem restrictions do not cover memfd objects, allowing processes to:

1. Read-to-execute bypass: Create writable memfd, inject code, then execute via mmap(PROT_EXEC) or direct execve()
2. Anonymous execution: Execute code without touching the filesystem via execve("/proc/self/fd/N") where N is a memfd descriptor
3. Cross-domain access violations: Pass memfd between processes to bypass domain restrictions

These scenarios can occur in sandboxed environments where filesystem access is restricted but memfd creation remains possible.

IMPLEMENTATION
==============

The implementation adds hierarchical execution control through domain scoping:

Core Components:
- is_memfd_file(): Reliable memfd detection via "memfd:" dentry prefix
- domain_is_scoped(): Cross-domain hierarchy checking (moved to domain.c)
- LSM hooks: mmap_file, file_mprotect, bprm_creds_for_exec
- Creation-time restrictions: hook_file_alloc_security

Security Matrix:
Execution decisions follow domain hierarchy rules preventing both same-domain bypass attempts and cross-domain access violations while preserving legitimate hierarchical access patterns.

Domain Hierarchy with LANDLOCK_SCOPE_MEMFD_EXEC:
===============================================

Root (no domain) - No restrictions
|

  +-- Domain A [SCOPE_MEMFD_EXEC] Layer 1
  |     +-- memfd_A (tagged with Domain A as creator)
  |     |
  |     +-- Domain A1 (child) [NO SCOPE] Layer 2
  |     |     +-- Inherits Layer 1 restrictions from parent
  |     |     +-- memfd_A1 (can create, inherits restrictions)
  |     |     +-- Domain A1a [SCOPE_MEMFD_EXEC] Layer 3
  |     |           +-- memfd_A1a (tagged with Domain A1a)
  |     |
  |     +-- Domain A2 (child) [SCOPE_MEMFD_EXEC] Layer 2
  |           +-- memfd_A2 (tagged with Domain A2 as creator)
  |           +-- CANNOT access memfd_A1 (different subtree)
  |
  +-- Domain B [SCOPE_MEMFD_EXEC] Layer 1
        +-- memfd_B (tagged with Domain B as creator)
        +-- CANNOT access ANY memfd from Domain A subtree

Execution Decision Matrix:
========================

Executor->  |  A  | A1 | A1a | A2 | B  | Root
Creator     |     |    |     |    |    |
------------|-----|----|-----|----|----|-----
Domain A    |  X  | X  | X   | X  | X  |  Y
Domain A1   |  Y  | X  | X   | X  | X  |  Y
Domain A1a  |  Y  | Y  | X   | X  | X  |  Y
Domain A2   |  Y  | X  | X   | X  | X  |  Y
Domain B    |  X  | X  | X   | X  | X  |  Y
Root        |  Y  | Y  | Y   | Y  | Y  |  Y

Legend: Y = Execution allowed, X = Execution denied

Scenarios Covered:
- Direct mmap(PROT_EXEC) on memfd files
- Two-stage mmap(PROT_READ) + mprotect(PROT_EXEC) bypass attempts
- execve("/proc/self/fd/N") anonymous execution
- execveat() and fexecve() file descriptor execution
- Cross-process memfd inheritance and IPC passing

TESTING
=======

All patches have been validated with:
- scripts/checkpatch.pl --strict (clean)
- Selftests covering same-domain restrictions, cross-domain hierarchy enforcement, and regular file isolation
- KUnit tests for memfd detection edge cases

DISCLAIMER
==========

My understanding of Landlock scoping semantics may be limited, but this implementation reflects my current understanding based on available documentation and code analysis. I welcome feedback and corrections regarding the scoping logic and domain hierarchy enforcement.

---
Abhinav Saxena (4):
landlock: add LANDLOCK_SCOPE_MEMFD_EXEC scope
landlock: implement memfd detection
landlock: add memfd exec LSM hooks and scoping selftests/landlock: add memfd execution tests

 include/uapi/linux/landlock.h                      |   5 +
 security/landlock/.kunitconfig                     |   1 +
 security/landlock/audit.c                          |   4 +
 security/landlock/audit.h                          |   1 +
 security/landlock/cred.c                           |  14 -
 security/landlock/domain.c                         |  67 ++++
 security/landlock/domain.h                         |   4 +
 security/landlock/fs.c                             | 405 ++++++++++++++++++++-
 security/landlock/limits.h                         |   2 +-
 security/landlock/task.c                           |  67 ----
 .../selftests/landlock/scoped_memfd_exec_test.c    | 325 +++++++++++++++++
 11 files changed, 812 insertions(+), 83 deletions(-)

---
base-commit: 5b74b2eff1eeefe43584e5b7b348c8cd3b723d38
change-id: 20250716-memfd-exec-ac0d582018c3

Best regards,

Signature · 1 line
Abhinav Saxena <[email protected]>
#1 lore raw

RFC PATCH 1/4 landlock: add LANDLOCK_SCOPE_MEMFD_EXEC scope

Add new scope LANDLOCK_SCOPE_MEMFD_EXEC to restrict execution of anonymous memory file descriptors (memfd). This scope prevents execution of code through memfd files via execve() family syscalls and executable memory mappings.

Update UAPI headers, limits, audit infrastructure, and kunit config to support the new scope. The scope follows existing Landlock scoping patterns for hierarchical domain enforcement.

---
 include/uapi/linux/landlock.h  | 5 +++++
 security/landlock/.kunitconfig | 1 +
 security/landlock/audit.c      | 4 ++++
 security/landlock/audit.h      | 1 +
 security/landlock/limits.h     | 2 +-
 5 files changed, 12 insertions(+), 1 deletion(-)
include/uapi/linux/landlock.h +5 -0
index f030adc462ee..5fa439b65aa6 100644
@@ -364,10 +364,15 @@ struct landlock_net_port_attr {
  *   related Landlock domain (e.g., a parent domain or a non-sandboxed process).
  * - %LANDLOCK_SCOPE_SIGNAL: Restrict a sandboxed process from sending a signal
  *   to another process outside the domain.
+ * - %LANDLOCK_SCOPE_MEMFD_EXEC: Restrict a sandboxed process from executing
+ *   anonymous memory file descriptors (memfd). This prevents execution of
+ *   code through memfd files via execve() family syscalls and executable
+ *   memory mappings.
  */
 /* clang-format off */
 #define LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET		(1ULL << 0)
 #define LANDLOCK_SCOPE_SIGNAL		                (1ULL << 1)
+#define LANDLOCK_SCOPE_MEMFD_EXEC			(1ULL << 2)
 /* clang-format on*/
 
 #endif /* _UAPI_LINUX_LANDLOCK_H */
security/landlock/.kunitconfig +1 -0
index f9423f01ac5b..a989785df65d 100644
@@ -1,6 +1,7 @@
 CONFIG_AUDIT=y
 CONFIG_KUNIT=y
 CONFIG_NET=y
+CONFIG_MEMFD_CREATE=y
 CONFIG_SECURITY=y
 CONFIG_SECURITY_LANDLOCK=y
 CONFIG_SECURITY_LANDLOCK_KUNIT_TEST=y
security/landlock/audit.c +4 -0
index c52d079cdb77..a439461d1b28 100644
@@ -78,6 +78,10 @@ get_blocker(const enum landlock_request_type type,
 	case LANDLOCK_REQUEST_SCOPE_SIGNAL:
 		WARN_ON_ONCE(access_bit != -1);
 		return "scope.signal";
+
+	case LANDLOCK_REQUEST_SCOPE_MEMFD_EXEC:
+		WARN_ON_ONCE(access_bit != -1);
+		return "scope.memfd_exec";
 	}
 
 	WARN_ON_ONCE(1);
security/landlock/audit.h +1 -0
index 92428b7fc4d8..5a822bc50c4a 100644
@@ -21,6 +21,7 @@ enum landlock_request_type {
 	LANDLOCK_REQUEST_NET_ACCESS,
 	LANDLOCK_REQUEST_SCOPE_ABSTRACT_UNIX_SOCKET,
 	LANDLOCK_REQUEST_SCOPE_SIGNAL,
+	LANDLOCK_REQUEST_SCOPE_MEMFD_EXEC,
 };
 
 /*
security/landlock/limits.h +1 -1
index 65b5ff051674..130f925283fa 100644
@@ -27,7 +27,7 @@
 #define LANDLOCK_MASK_ACCESS_NET	((LANDLOCK_LAST_ACCESS_NET << 1) - 1)
 #define LANDLOCK_NUM_ACCESS_NET		__const_hweight64(LANDLOCK_MASK_ACCESS_NET)
 
-#define LANDLOCK_LAST_SCOPE		LANDLOCK_SCOPE_SIGNAL
+#define LANDLOCK_LAST_SCOPE		LANDLOCK_SCOPE_MEMFD_EXEC
 #define LANDLOCK_MASK_SCOPE		((LANDLOCK_LAST_SCOPE << 1) - 1)
 #define LANDLOCK_NUM_SCOPE		__const_hweight64(LANDLOCK_MASK_SCOPE)
 
Signature · 1 line
2.43.0
#2 lore raw

RFC PATCH 2/4 landlock: implement memfd detection

In reply to Abhinav Saxena

Add is_memfd_file() function to reliably detect memfd files by checking for "memfd:" prefix in dentry names on shmem-backed files. This distinguishes true memfd files from regular shmem files.

Move domain_is_scoped() to domain.c for reuse across subsystems. Add comprehensive kunit tests for memfd detection edge cases.

---
 security/landlock/domain.c |  67 +++++++++++++++
 security/landlock/domain.h |   4 +
 security/landlock/fs.c     | 210 +++++++++++++++++++++++++++++++++++++++++++++
 security/landlock/task.c   |  67 ---------------
 4 files changed, 281 insertions(+), 67 deletions(-)
security/landlock/domain.c +67 -0
index a647b68e8d06..993c299ca263 100644
@@ -262,3 +262,70 @@ kunit_test_suite(test_suite);
 #endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
 
 #endif /* CONFIG_AUDIT */
+
+/**
+ * domain_is_scoped - Checks if the client domain is scoped in the same
+ *		      domain as the server.
+ *
+ * @client: IPC sender domain.
+ * @server: IPC receiver domain.
+ * @scope: The scope restriction criteria.
+ *
+ * Returns: True if the @client domain is scoped to access the @server,
+ * unless the @server is also scoped in the same domain as @client.
+ */
+bool domain_is_scoped(const struct landlock_ruleset *const client,
+		      const struct landlock_ruleset *const server,
+		      access_mask_t scope)
+{
+	int client_layer, server_layer;
+	const struct landlock_hierarchy *client_walker, *server_walker;
+
+	/* Quick return if client has no domain */
+	if (WARN_ON_ONCE(!client))
+		return false;
+
+	client_layer = client->num_layers - 1;
+	client_walker = client->hierarchy;
+	/*
+	 * client_layer must be a signed integer with greater capacity
+	 * than client->num_layers to ensure the following loop stops.
+	 */
+	BUILD_BUG_ON(sizeof(client_layer) > sizeof(client->num_layers));
+
+	server_layer = server ? (server->num_layers - 1) : -1;
+	server_walker = server ? server->hierarchy : NULL;
+
+	/*
+	 * Walks client's parent domains down to the same hierarchy level
+	 * as the server's domain, and checks that none of these client's
+	 * parent domains are scoped.
+	 */
+	for (; client_layer > server_layer; client_layer--) {
+		if (landlock_get_scope_mask(client, client_layer) & scope)
+			return true;
+
+		client_walker = client_walker->parent;
+	}
+	/*
+	 * Walks server's parent domains down to the same hierarchy level as
+	 * the client's domain.
+	 */
+	for (; server_layer > client_layer; server_layer--)
+		server_walker = server_walker->parent;
+
+	for (; client_layer >= 0; client_layer--) {
+		if (landlock_get_scope_mask(client, client_layer) & scope) {
+			/*
+			 * Client and server are at the same level in the
+			 * hierarchy. If the client is scoped, the request is
+			 * only allowed if this domain is also a server's
+			 * ancestor.
+			 */
+			return server_walker != client_walker;
+		}
+		client_walker = client_walker->parent;
+		server_walker = server_walker->parent;
+	}
+	return false;
+}
security/landlock/domain.h +4 -0
index 7fb70b25f85a..21a9eea644bd 100644
@@ -171,4 +171,8 @@ static inline void landlock_put_hierarchy(struct landlock_hierarchy *hierarchy)
 	}
 }
 
+bool domain_is_scoped(const struct landlock_ruleset *const client,
+		      const struct landlock_ruleset *const server,
+		      access_mask_t scope);
+
 #endif /* _SECURITY_LANDLOCK_DOMAIN_H */
security/landlock/fs.c +210 -0

247 lines not on this page · raw message

security/landlock/task.c +0 -67

73 lines not on this page · raw message

Signature · 1 line
2.43.0
#8 lore raw

RFC PATCH 3/4 landlock: add memfd exec LSM hooks and scoping

In reply to Abhinav Saxena

Implement LSM hooks to enforce memfd execution restrictions:

- hook_mmap_file: Prevent executable mapping of memfd files
- hook_file_mprotect: Block mprotect() adding PROT_EXEC to memfd mappings
- hook_bprm_creds_for_exec: Prevent direct execution via execve() family
- hook_file_alloc_security: Initialize memfd files with proper access masks

All hooks use domain hierarchy checking to enforce scoped restrictions with proper audit logging. This prevents multiple attack vectors:
- Direct mmap(PROT_EXEC) on memfd
- Two-stage mmap(PROT_READ) + mprotect(PROT_EXEC) bypass
- execve("/proc/self/fd/N") anonymous execution

Implement memfd execution access control in check_memfd_execute_access() using hierarchy-aware domain checking

---
 security/landlock/cred.c |  14 ----
 security/landlock/fs.c   | 195 ++++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 194 insertions(+), 15 deletions(-)
security/landlock/cred.c +0 -14
index 0cb3edde4d18..356dad0b7e9b 100644
@@ -43,25 +43,11 @@ static void hook_cred_free(struct cred *const cred)
 		landlock_put_ruleset_deferred(dom);
 }
 
-#ifdef CONFIG_AUDIT
-
-static int hook_bprm_creds_for_exec(struct linux_binprm *const bprm)
-{
-	/* Resets for each execution. */
-	landlock_cred(bprm->cred)->domain_exec = 0;
-	return 0;
-}
-
-#endif /* CONFIG_AUDIT */
-
 static struct security_hook_list landlock_hooks[] __ro_after_init = {
 	LSM_HOOK_INIT(cred_prepare, hook_cred_prepare),
 	LSM_HOOK_INIT(cred_transfer, hook_cred_transfer),
 	LSM_HOOK_INIT(cred_free, hook_cred_free),
 
-#ifdef CONFIG_AUDIT
-	LSM_HOOK_INIT(bprm_creds_for_exec, hook_bprm_creds_for_exec),
-#endif /* CONFIG_AUDIT */
 };
 
 __init void landlock_add_cred_hooks(void)
security/landlock/fs.c +194 -1

213 lines not on this page · raw message

Signature · 1 line
2.43.0
#9 lore raw

RFC PATCH 4/4 selftests/landlock: add memfd execution tests

In reply to Abhinav Saxena

Add core test suite for LANDLOCK_SCOPE_MEMFD_EXEC covering:

- Same-domain execution restriction (prevent read-to-execute bypass)
- execve() family syscall restrictions via /proc/self/fd/ path
- Regular filesystem files remain unaffected by memfd scoping

Tests validate that memfd execution restrictions are properly enforced while ensuring surgical targeting that doesn't impact legitimate file operations. Covers key attack vectors including anonymous execution and W^X policy bypass attempts.

---
 .../selftests/landlock/scoped_memfd_exec_test.c    | 325 +++++++++++++++++++++
 1 file changed, 325 insertions(+)
tools/testing/selftests/landlock/scoped_memfd_exec_test.c new file +325 -0
new file mode 100644
index 000000000000..2513a44d8320
@@ -0,0 +1,325 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Landlock tests for LANDLOCK_SCOPE_MEMFD_EXEC domain restrictions
+ *
+ * These tests validate Landlock's hierarchical execution control for memfd
+ * objects. The scoping mechanism prevents processes from executing memfd
+ * created in different domain contexts.
+ *
+ * Copyright © 2025 Abhinav Saxena <[email protected]>
+ */
+
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/landlock.h>
+#include <linux/memfd.h>
+#include <signal.h>
+#include <sys/mman.h>
+#include <sys/prctl.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/syscall.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include "common.h"
+#include "scoped_common.h"
+
+static int create_test_memfd(struct __test_metadata *const _metadata)
+{
+	int memfd;
+	static const char test_data[] = "#!/bin/sh\nexit 42\n";
+
+	memfd = memfd_create("test_exec", 0);
+	ASSERT_LE(0, memfd)
+	{
+		TH_LOG("Failed to create memfd: %s", strerror(errno));
+	}
+
+	ASSERT_EQ(fchmod(memfd, 0700), 0);
+
+	ASSERT_EQ(0, ftruncate(memfd, sizeof(test_data)));
+	ASSERT_EQ(sizeof(test_data),
+		  write(memfd, test_data, sizeof(test_data)));
+	ASSERT_EQ(0, lseek(memfd, 0, SEEK_SET));
+
+	return memfd;
+}
+
+static bool test_mmap_exec_restriction(int memfd, bool expect_denied)
+{
+	void *addr;
+	const size_t page_size = getpagesize();
+
+	addr = mmap(NULL, page_size, PROT_READ | PROT_EXEC, MAP_PRIVATE, memfd,
+		    0);
+
+	if (expect_denied) {
+		bool correctly_denied = (addr == MAP_FAILED && errno == EACCES);
+
+		if (addr != MAP_FAILED)
+			munmap(addr, page_size);
+		return correctly_denied;
+	}
+
+	if (addr == MAP_FAILED)
+		return false;
+
+	munmap(addr, page_size);
+	return true;
+}
+
+/* clang-format off */
+FIXTURE(scoped_domains) {};
+/* clang-format on */
+
+#include "scoped_base_variants.h"
+
+FIXTURE_SETUP(scoped_domains)
+{
+	drop_caps(_metadata);
+}
+
+FIXTURE_TEARDOWN(scoped_domains)
+{
+}
+
+/*
+ * Test that regular filesystem files are unaffected by memfd restrictions
+ *
+ * This test ensures that LANDLOCK_SCOPE_MEMFD_EXEC scoping only affects
+ * memfd objects and does not interfere with normal file execution or
+ * memory mapping of regular filesystem files.
+ *
+ * Security scenarios tested:
+ * - Scope isolation: memfd restrictions don't affect regular files
+ * - Proper targeting: only anonymous memory objects are restricted
+ *
+ * Scenarios considered (while allowing legitimate use):
+ * - Malicious process creates executable memfd -> BLOCKED
+ * - Same process maps legitimate executable file ->ALLOWED
+ * - Ensures restrictions are surgical, not broad
+ *
+ * Test flow:
+ * 1. Parent optionally creates scoped domain
+ * 2. Parent forks child process
+ * 3. Child optionally creates scoped domain
+ * 4. Child creates regular temporary file with executable content
+ * 5. Child creates memfd with same content
+ * 6. Test memfd execution ->should follow scoping rules
+ * 7. Test regular file execution ->should always work regardless of memfd
+ * scoping
+ * 8. Verify differential behavior confirms proper targeting
+ */
+TEST_F(scoped_domains, regular_file_unaffected)
+{
+	int tmp_fd, memfd;
+	char tmp_path[] = "/tmp/landlock_test_XXXXXX";
+	void *addr;
+	const size_t page_size = getpagesize();
+	bool memfd_should_be_denied;
+
+	memfd_should_be_denied = variant->domain_child ||
+				 variant->domain_parent;
+
+	if (variant->domain_parent)
+		create_scoped_domain(_metadata, LANDLOCK_SCOPE_MEMFD_EXEC);
+
+	pid_t child = fork();
+
+	ASSERT_LE(0, child);
+
+	if (child == 0) {
+		/* Child process */
+		if (variant->domain_child)
+			create_scoped_domain(_metadata,
+					     LANDLOCK_SCOPE_MEMFD_EXEC);
+
+		/* Create regular file with executable test content */
+		tmp_fd = mkstemp(tmp_path);
+		ASSERT_LE(0, tmp_fd);
+		ASSERT_EQ(0, fchmod(tmp_fd, 0755));
+
+		static const char test_data[] = "#!/bin/sh\nexit 42\n";
+
+		ASSERT_EQ(sizeof(test_data),
+			  write(tmp_fd, test_data, sizeof(test_data)));
+		ASSERT_EQ(0, lseek(tmp_fd, 0, SEEK_SET));
+
+		/* Create memfd with identical content for comparison */
+		memfd = create_test_memfd(_metadata);
+
+		/* Test memfd execution - should follow scoping restrictions */
+		bool memfd_correctly_handled = test_mmap_exec_restriction(
+			memfd, memfd_should_be_denied);
+		EXPECT_TRUE(memfd_correctly_handled);
+
+		/*
+		 * Test regular file execution - should always work regardless
+		 * of memfd scoping
+		 */
+		addr = mmap(NULL, page_size, PROT_READ | PROT_EXEC, MAP_PRIVATE,
+			    tmp_fd, 0);
+		EXPECT_NE(MAP_FAILED, addr);
+		if (addr != MAP_FAILED)
+			munmap(addr, page_size);
+
+		/* Cleanup */
+		close(memfd);
+		close(tmp_fd);
+		unlink(tmp_path);
+		_exit(_metadata->exit_code);
+	}
+
+	/* Parent waits for child */
+	int status;
+
+	ASSERT_EQ(child, waitpid(child, &status, 0));
+	if (WIFSIGNALED(status) || !WIFEXITED(status) ||
+	    WEXITSTATUS(status) != EXIT_SUCCESS)
+		_metadata->exit_code = KSFT_FAIL;
+}
+
+/*
+ * Test execve() family syscall restrictions on memfd
+ *
+ * This test validates that direct execution of memfd files via execve(),
+ * execveat(), and fexecve() syscalls is properly blocked when domain
+ * scoping is enabled. Tests the /proc/self/fd/ execution path commonly
+ * used for anonymous execution.
+ *
+ * Security scenarios tested:
+ * - Direct memfd execution via /proc/self/fd/ path
+ * - Anonymous execution prevention
+ * - execve() hook integration with memfd scoping
+ *
+ * Attack scenarios prevented:
+ * 1. execve("/proc/self/fd/N") where N is memfd file descriptor
+ * 2. execveat(memfd_fd, "", args, env, AT_EMPTY_PATH) - anonymous execution
+ * 3. fexecve(memfd_fd, args, env) - file descriptor execution
+ *
+ * Test flow:
+ * 1. Parent optionally creates scoped domain
+ * 2. Parent forks child process
+ * 3. Child optionally creates scoped domain
+ * 4. Child creates memfd with executable script content
+ * 5. Child attempts execve() using /proc/self/fd/N path
+ * 6. Verify: EACCES if scoped, successful execution (exit 42) if not scoped
+ * 7. Parent checks child exit status to determine success/failure
+ */
+TEST_F(scoped_domains, execve_restriction)
+{
+	int memfd;
+	char fd_path[64];
+	bool should_be_denied;
+
+	should_be_denied = variant->domain_child || variant->domain_parent;
+	TH_LOG("execve_restriction: parent=%d, child=%d\n",
+	       variant->domain_parent, variant->domain_child);
+
+	if (variant->domain_parent)
+		create_scoped_domain(_metadata, LANDLOCK_SCOPE_MEMFD_EXEC);
+
+	pid_t child = fork();
+
+	ASSERT_LE(0, child);
+
+	if (child == 0) {
+		/* Child process */
+		if (variant->domain_child) {
+			create_scoped_domain(_metadata,
+					     LANDLOCK_SCOPE_MEMFD_EXEC);
+		}
+
+		memfd = create_test_memfd(_metadata);
+		snprintf(fd_path, sizeof(fd_path), "/proc/self/fd/%d", memfd);
+
+		/* Attempt execve on memfd via /proc/self/fd/ path */
+		char *const argv[] = { "test", NULL };
+		char *const envp[] = { NULL };
+
+		int ret = execve(fd_path, argv, envp);
+
+		ASSERT_EQ(-1, ret);
+
+		/* If we reach here, execve failed */
+		if (should_be_denied) {
+			EXPECT_EQ(EACCES,
+				  errno); /* Should be blocked by Landlock */
+		} else {
+			/* execve should have succeeded but failed for other reason */
+			TH_LOG("execve failed unexpectedly: %s",
+			       strerror(errno));
+		}
+
+		close(memfd);
+		_exit(_metadata->exit_code);
+	}
+
+	/* Parent waits for child and checks exit status */
+	int status;
+
+	ASSERT_EQ(child, waitpid(child, &status, 0));
+
+	if (should_be_denied) {
+		/* Child should exit normally after execve was blocked */
+		EXPECT_TRUE(WIFEXITED(status));
+	} else {
+		/*
+		 * Child should have executed successfully with script's
+		 * exit code
+		 */
+		EXPECT_TRUE(WIFEXITED(status));
+		EXPECT_EQ(42,
+			  WEXITSTATUS(status)); /* Exit code from test script */
+	}
+}
+
+/*
+ * Test same-domain execution restriction (should always be denied when scoped)
+ *
+ * This test validates the "Same domain: DENY" rule from the security matrix.
+ * When a process is in a scoped domain, it should not be able to execute
+ * memfd objects that it created itself, preventing read-to-execute bypass.
+ *
+ * Security scenarios tested:
+ * - Read-to-execute bypass prevention within same domain
+ * - Self-execution blocking for memfd objects
+ *
+ * Attack scenario prevented:
+ * - Attacker process creates writable memfd in current domain
+ * - Writes malicious shellcode to the memfd via write() syscalls
+ * - Attempts to execute the same memfd via mmap(PROT_EXEC)
+ * - Should be BLOCKED by same-domain denial rule
+ * - Prevents bypassing W^X policies via anonymous memory
+ *
+ * Test flow:
+ * 1. Process optionally creates scoped domain
+ * 2. Process creates memfd (inherits current domain context)
+ * 3. Process attempts to mmap its own memfd with PROT_EXEC
+ * 4. Verify: ALLOW if not scoped, DENY if scoped (same domain rule)
+ */
+TEST_F(scoped_domains, same_domain_restriction)
+{
+	int memfd;
+	bool should_be_denied;
+
+	/* Same domain should be denied when scoped, allowed when not scoped */
+	should_be_denied = variant->domain_parent;
+
+	if (variant->domain_parent)
+		create_scoped_domain(_metadata, LANDLOCK_SCOPE_MEMFD_EXEC);
+
+	/* Process creates and tries to execute its own memfd (same domain) */
+	memfd = create_test_memfd(_metadata);
+
+	bool test_passed = test_mmap_exec_restriction(memfd, should_be_denied);
+
+	EXPECT_TRUE(test_passed);
+
+	close(memfd);
+}
+
+TEST_HARNESS_MAIN
Signature · 1 line
2.43.0
#3 lore raw

Re: [PATCH RFC 2/4] landlock: implement memfd detection

In reply to Abhinav Saxena
kernel test robot noticed the following build errors:

Hi Abhinav,

[This is a private test report for your RFC patch.] kernel test robot noticed the following build errors:

[auto build test ERROR on 5b74b2eff1eeefe43584e5b7b348c8cd3b723d38]

url:    https://github.com/intel-lab-lkp/linux/commits/Abhinav-Saxena/landlock-add-LANDLOCK_SCOPE_MEMFD_EXEC-scope/20250719-191556
base:   5b74b2eff1eeefe43584e5b7b348c8cd3b723d38
patch link:    https://lore.kernel.org/r/20250719-memfd-exec-v1-2-0ef7feba5821%40gmail.com
patch subject: [PATCH RFC 2/4] landlock: implement memfd detection
config: i386-buildonly-randconfig-006-20250719 (https://download.01.org/0day-ci/archive/20250719/[email protected]/config)
compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20250719/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

>> ld.lld: error: undefined symbol: domain_is_scoped
   >>> referenced by task.c:176 (security/landlock/task.c:176)
   >>>               security/landlock/task.o:(hook_unix_stream_connect) in archive vmlinux.a
   >>> referenced by task.c:176 (security/landlock/task.c:176)
   >>>               security/landlock/task.o:(hook_unix_may_send) in archive vmlinux.a
   >>> referenced by task.c:304 (security/landlock/task.c:304)
   >>>               security/landlock/task.o:(hook_task_kill) in archive vmlinux.a
   >>> referenced 1 more times
Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#4 lore raw

Re: [PATCH RFC 2/4] landlock: implement memfd detection

In reply to Abhinav Saxena
Quoted 15 lines · Abhinav Saxena

Add is_memfd_file() function to reliably detect memfd files by checking for "memfd:" prefix in dentry names on shmem-backed files. This distinguishes true memfd files from regular shmem files.

Move domain_is_scoped() to domain.c for reuse across subsystems. Add comprehensive kunit tests for memfd detection edge cases.

---
 security/landlock/domain.c |  67 +++++++++++++++
 security/landlock/domain.h |   4 +
 security/landlock/fs.c     | 210 +++++++++++++++++++++++++++++++++++++++++++++
 security/landlock/task.c   |  67 ---------------
 4 files changed, 281 insertions(+), 67 deletions(-)

...

Quoted 34 lines
security/landlock/fs.c +33 -0
+/**
+ * is_memfd_file - Check if file was created via memfd_create()
+ * @file: File to check
+ *
+ * Returns true if @file was created via memfd_create(), false otherwise.
+ *
+ * memfd files are shmem-backed files with "memfd:" prefix in their dentry name.
+ * This is the definitive way to distinguish memfd files from regular shmem
+ * files.
+ */
+static bool is_memfd_file(struct file *file)
+{
+       const struct dentry *dentry;
+       const unsigned char *name;
+       size_t name_len;
+
+       /* Fast path: basic validation */
+       if (unlikely(!file))
+               return false;
+
+       /* Must be shmem-backed first - this is the cheapest definitive check */
+       if (!shmem_file(file))
+               return false;
+
+#ifdef CONFIG_MEMFD_CREATE
+
+       /* Validate dentry and get name info */
+       dentry = file->f_path.dentry;
+       if (unlikely(!dentry))
+               return false;
+
+       name_len = dentry->d_name.len;
+       name = dentry->d_name.name;

security/landlock/fs.c get_required_file_open_access(const struct file *const file) · line 1720

Quoted 10 lines
security/landlock/fs.c +10 -0
+
+       /* memfd files always have "memfd:" prefix (6 characters) */
+       if (name_len < 6 || unlikely(!name))
+               return false;
+
+       /* Check for exact "memfd:" prefix */
+       return memcmp(name, "memfd:", 6) == 0;
+#else
+       return false;
+#endif

I was trying to do something similar early this year but didn't hear feedback from the linux-mm folks.
https://lore.kernel.org/linux-security-module/[email protected]/

I have considered this approach but didn't use it. My concern is, potentially a malicious user can create a file in a shmem fs, e.g. tmpfs , with the "memfd:" prefix, which can be used to bypass security policy.
(Resending this message due to a misconfiguration with my email client. Apologies for any inconvenience.)

-Fan

#5 lore raw

Re: [PATCH RFC 2/4] landlock: implement memfd detection

Quoted 68 lines · Fan Wu
Quoted 15 lines · Abhinav Saxena

Add is_memfd_file() function to reliably detect memfd files by checking for “memfd:” prefix in dentry names on shmem-backed files. This distinguishes true memfd files from regular shmem files.

Move domain_is_scoped() to domain.c for reuse across subsystems. Add comprehensive kunit tests for memfd detection edge cases.

—

 security/landlock/domain.c |  67 +++++++++++++++
 security/landlock/domain.h |   4 +
 security/landlock/fs.c     | 210 +++++++++++++++++++++++++++++++++++++++++++++
 security/landlock/task.c   |  67 —————
 4 files changed, 281 insertions(+), 67 deletions(-)

…

Quoted 34 lines
security/landlock/fs.c +33 -0
+/**
+ * is_memfd_file - Check if file was created via memfd_create()
+ * @file: File to check
+ *
+ * Returns true if @file was created via memfd_create(), false otherwise.
+ *
+ * memfd files are shmem-backed files with “memfd:” prefix in their dentry name.
+ * This is the definitive way to distinguish memfd files from regular shmem
+ * files.
+ */
+static bool is_memfd_file(struct file *file)
+{
+       const struct dentry *dentry;
+       const unsigned char *name;
+       size_t name_len;
+
+       /* Fast path: basic validation */
+       if (unlikely(!file))
+               return false;
+
+       /* Must be shmem-backed first - this is the cheapest definitive check */
+       if (!shmem_file(file))
+               return false;
+
+#ifdef CONFIG_MEMFD_CREATE
+
+       /* Validate dentry and get name info */
+       dentry = file->f_path.dentry;
+       if (unlikely(!dentry))
+               return false;
+
+       name_len = dentry->d_name.len;
+       name = dentry->d_name.name;

security/landlock/fs.c get_required_file_open_access(const struct file *const file) · line 1720

Quoted 10 lines
security/landlock/fs.c +10 -0
+
+       /* memfd files always have “memfd:” prefix (6 characters) */
+       if (name_len < 6 || unlikely(!name))
+               return false;
+
+       /* Check for exact “memfd:” prefix */
+       return memcmp(name, “memfd:”, 6) == 0;
+#else
+       return false;
+#endif

I was trying to do something similar early this year but didn’t hear feedback from the linux-mm folks.
<https://lore.kernel.org/linux-security-module/[email protected]/>

Quoted 8 lines

I have considered this approach but didn’t use it. My concern is, potentially a malicious user can create a file in a shmem fs, e.g. tmpfs , with the “memfd:” prefix, which can be used to bypass security policy.
(Resending this message due to a misconfiguration with my email client. Apologies for any inconvenience.)

-Fan

Hi Fan,

Thanks for your comments.

I agree that an LSM hook into memfd_create() would be a much better solution. In the absence of such a function, do you think adding a d_unlinked(dentry) check could serve as an additional verification?

I say things since I *think* that legitimate memfd files are always unlinked while spoofed tmpfs files remain linked. I could be wrong though.

In any case, we can test this approach using kprobes to validate the behavior.

-Abhinav

maintainer
#6 lore raw

Re: [PATCH RFC 2/4] landlock: implement memfd detection

Quoted 37 lines · Abhinav Saxena
Quoted 35 lines · Fan Wu
Quoted 15 lines · Abhinav Saxena

Add is_memfd_file() function to reliably detect memfd files by checking for “memfd:” prefix in dentry names on shmem-backed files. This distinguishes true memfd files from regular shmem files.

Move domain_is_scoped() to domain.c for reuse across subsystems. Add comprehensive kunit tests for memfd detection edge cases.

—

 security/landlock/domain.c |  67 +++++++++++++++
 security/landlock/domain.h |   4 +
 security/landlock/fs.c     | 210 +++++++++++++++++++++++++++++++++++++++++++++
 security/landlock/task.c   |  67 —————
 4 files changed, 281 insertions(+), 67 deletions(-)

…

Quoted 16 lines
security/landlock/fs.c +15 -0
+/**
+ * is_memfd_file - Check if file was created via memfd_create()
+ * @file: File to check
+ *
+ * Returns true if @file was created via memfd_create(), false otherwise.
+ *
+ * memfd files are shmem-backed files with “memfd:” prefix in their dentry name.
+ * This is the definitive way to distinguish memfd files from regular shmem
+ * files.
+ */
+static bool is_memfd_file(struct file *file)
+{
+       const struct dentry *dentry;
+       const unsigned char *name;
+       size_t name_len;
Quoted 8 lines
Quoted 8 lines

security/landlock/fs.c get_required_file_open_access(const struct file *const file) · line 1700

Quoted 8 lines
security/landlock/fs.c +8 -0
+
+       /* Fast path: basic validation */
+       if (unlikely(!file))
+               return false;
+
+       /* Must be shmem-backed first - this is the cheapest definitive check */
+       if (!shmem_file(file))
+               return false;

In which case a memfd would not be detected by this function? shmem_file_operations or hugetlbfs_file_operations are always set for memfd right?

We could export memfd_get_seals() to stay consistent over time.

Quoted 25 lines
Quoted 25 lines
Quoted 10 lines
security/landlock/fs.c +10 -0
+
+#ifdef CONFIG_MEMFD_CREATE
+
+       /* Validate dentry and get name info */
+       dentry = file->f_path.dentry;
+       if (unlikely(!dentry))
+               return false;
+
+       name_len = dentry->d_name.len;
+       name = dentry->d_name.name;

security/landlock/fs.c get_required_file_open_access(const struct file *const file) · line 1720

Quoted 10 lines
security/landlock/fs.c +10 -0
+
+       /* memfd files always have “memfd:” prefix (6 characters) */
+       if (name_len < 6 || unlikely(!name))
+               return false;
+
+       /* Check for exact “memfd:” prefix */
+       return memcmp(name, “memfd:”, 6) == 0;
+#else
+       return false;
+#endif

I was trying to do something similar early this year but didn’t hear feedback from the linux-mm folks.
<https://lore.kernel.org/linux-security-module/[email protected]/>

Quoted 4 lines
Quoted 4 lines

I have considered this approach but didn’t use it. My concern is, potentially a malicious user can create a file in a shmem fs, e.g. tmpfs , with the “memfd:” prefix, which can be used to bypass security policy.

In the case of Landlock that should not be a security issue but a compatibility issue, which is not better.

Quoted 9 lines
Quoted 4 lines

(Resending this message due to a misconfiguration with my email client. Apologies for any inconvenience.)

-Fan

Hi Fan,

Thanks for your comments.

Quoted 7 lines

I agree that an LSM hook into memfd_create() would be a much better solution. In the absence of such a function, do you think adding a d_unlinked(dentry) check could serve as an additional verification?

I say things since I *think* that legitimate memfd files are always unlinked while spoofed tmpfs files remain linked. I could be wrong though.

We should just use the same checks used by the memfd-related syscalls/operations to detect such file.

Quoted 5 lines

In any case, we can test this approach using kprobes to validate the behavior.

-Abhinav

maintainer
#10 lore raw
In reply to Abhinav Saxena

Thanks for this patch series Abhinav! The code looks good overall, but we should clarify the design. Sorry for the delayed response, it is on my radar now.

CCing Jeff and Daniel

Quoted 14 lines · Abhinav Saxena

This patch series introduces LANDLOCK_SCOPE_MEMFD_EXEC, a new Landlock scoping mechanism that restricts execution of anonymous memory file descriptors (memfd) created via memfd_create(2). This addresses security gaps where processes can bypass W^X policies and execute arbitrary code through anonymous memory objects.

SECURITY PROBLEM
================

Current Landlock filesystem restrictions do not cover memfd objects, allowing processes to:

Quoted 7 lines

1. Read-to-execute bypass: Create writable memfd, inject code, then execute via mmap(PROT_EXEC) or direct execve()
2. Anonymous execution: Execute code without touching the filesystem via execve("/proc/self/fd/N") where N is a memfd descriptor

3. Cross-domain access violations: Pass memfd between processes to bypass domain restrictions

Landlock only restricts access at open time, which is a useful property. This enables to create more restricted sandboxes but still get access to outside resources via trusted processes. If the process passing the FDs is not trusted, the sandboxed process could just ask to execute arbitrary code outside the sandbox anyway.

However, the Landlock scopes are designed to block IPC from within a sandbox to outside the sandbox. We could have a new scope to forbid a sandbox process to receive or inherit file descriptors, but that would be a different and generic feature. For compatibility reasons, this might not be easy to implement and I think there are more important features to implement before that.

Thinking more about it, restricting memfd should not be a "scoped" flag because the semantic is not the same, but we should have a new ruleset property instead, something like "ruleset.denied" with a related LANDLOCK_DENY_EXECUTE_MEMFD flag. This flag will only have an impact on newly created memfd from a sandboxed process with this restriction at creation time. This could be implemented with hook_file_alloc_security() by checking if the file is indeed a memfd and checking inode->i_mode for executability bits (which would imply MFD_NOEXEC_SEAL).

Quoted 55 lines

These scenarios can occur in sandboxed environments where filesystem access is restricted but memfd creation remains possible.

IMPLEMENTATION
==============

The implementation adds hierarchical execution control through domain scoping:

Core Components:
- is_memfd_file(): Reliable memfd detection via "memfd:" dentry prefix
- domain_is_scoped(): Cross-domain hierarchy checking (moved to domain.c)
- LSM hooks: mmap_file, file_mprotect, bprm_creds_for_exec
- Creation-time restrictions: hook_file_alloc_security

Security Matrix:
Execution decisions follow domain hierarchy rules preventing both same-domain bypass attempts and cross-domain access violations while preserving legitimate hierarchical access patterns.

Domain Hierarchy with LANDLOCK_SCOPE_MEMFD_EXEC:
===============================================

Root (no domain) - No restrictions
|

  +-- Domain A [SCOPE_MEMFD_EXEC] Layer 1
  |     +-- memfd_A (tagged with Domain A as creator)
  |     |
  |     +-- Domain A1 (child) [NO SCOPE] Layer 2
  |     |     +-- Inherits Layer 1 restrictions from parent
  |     |     +-- memfd_A1 (can create, inherits restrictions)
  |     |     +-- Domain A1a [SCOPE_MEMFD_EXEC] Layer 3
  |     |           +-- memfd_A1a (tagged with Domain A1a)
  |     |
  |     +-- Domain A2 (child) [SCOPE_MEMFD_EXEC] Layer 2
  |           +-- memfd_A2 (tagged with Domain A2 as creator)
  |           +-- CANNOT access memfd_A1 (different subtree)
  |
  +-- Domain B [SCOPE_MEMFD_EXEC] Layer 1
        +-- memfd_B (tagged with Domain B as creator)
        +-- CANNOT access ANY memfd from Domain A subtree

Execution Decision Matrix:
========================

Executor->  |  A  | A1 | A1a | A2 | B  | Root
Creator     |     |    |     |    |    |
------------|-----|----|-----|----|----|-----
Domain A    |  X  | X  | X   | X  | X  |  Y
Domain A1   |  Y  | X  | X   | X  | X  |  Y
Domain A1a  |  Y  | Y  | X   | X  | X  |  Y
Domain A2   |  Y  | X  | X   | X  | X  |  Y
Domain B    |  X  | X  | X   | X  | X  |  Y
Root        |  Y  | Y  | Y   | Y  | Y  |  Y
Quoted 1 line

Legend: Y = Execution allowed, X = Execution denied

Because checks should not be related to scopes, this will be much simpler.

Quoted 8 lines

Scenarios Covered:
- Direct mmap(PROT_EXEC) on memfd files
- Two-stage mmap(PROT_READ) + mprotect(PROT_EXEC) bypass attempts
- execve("/proc/self/fd/N") anonymous execution
- execveat() and fexecve() file descriptor execution
- Cross-process memfd inheritance and IPC passing

Quoted 8 lines

TESTING
=======

All patches have been validated with:
- scripts/checkpatch.pl --strict (clean)
- Selftests covering same-domain restrictions, cross-domain hierarchy enforcement, and regular file isolation
- KUnit tests for memfd detection edge cases

Thanks for all these tests!

Quoted 38 lines

DISCLAIMER
==========

My understanding of Landlock scoping semantics may be limited, but this implementation reflects my current understanding based on available documentation and code analysis. I welcome feedback and corrections regarding the scoping logic and domain hierarchy enforcement.

---
Abhinav Saxena (4):
landlock: add LANDLOCK_SCOPE_MEMFD_EXEC scope
landlock: implement memfd detection
landlock: add memfd exec LSM hooks and scoping selftests/landlock: add memfd execution tests

 include/uapi/linux/landlock.h                      |   5 +
 security/landlock/.kunitconfig                     |   1 +
 security/landlock/audit.c                          |   4 +
 security/landlock/audit.h                          |   1 +
 security/landlock/cred.c                           |  14 -
 security/landlock/domain.c                         |  67 ++++
 security/landlock/domain.h                         |   4 +
 security/landlock/fs.c                             | 405 ++++++++++++++++++++-
 security/landlock/limits.h                         |   2 +-
 security/landlock/task.c                           |  67 ----
 .../selftests/landlock/scoped_memfd_exec_test.c    | 325 +++++++++++++++++
 11 files changed, 812 insertions(+), 83 deletions(-)

---
base-commit: 5b74b2eff1eeefe43584e5b7b348c8cd3b723d38
change-id: 20250716-memfd-exec-ac0d582018c3

Best regards,

Signature · 1 line
Abhinav Saxena <[email protected]>
maintainer
#7 lore raw

Re: [PATCH RFC 2/4] landlock: implement memfd detection

In reply to Mickaël Salaün
Quoted 78 lines · Mickaël Salaün
Quoted 37 lines · Abhinav Saxena
Quoted 35 lines · Fan Wu
Quoted 15 lines · Abhinav Saxena

Add is_memfd_file() function to reliably detect memfd files by checking for “memfd:” prefix in dentry names on shmem-backed files. This distinguishes true memfd files from regular shmem files.

Move domain_is_scoped() to domain.c for reuse across subsystems. Add comprehensive kunit tests for memfd detection edge cases.

—

 security/landlock/domain.c |  67 +++++++++++++++
 security/landlock/domain.h |   4 +
 security/landlock/fs.c     | 210 +++++++++++++++++++++++++++++++++++++++++++++
 security/landlock/task.c   |  67 —————
 4 files changed, 281 insertions(+), 67 deletions(-)

…

Quoted 16 lines
security/landlock/fs.c +15 -0
+/**
+ * is_memfd_file - Check if file was created via memfd_create()
+ * @file: File to check
+ *
+ * Returns true if @file was created via memfd_create(), false otherwise.
+ *
+ * memfd files are shmem-backed files with “memfd:” prefix in their dentry name.
+ * This is the definitive way to distinguish memfd files from regular shmem
+ * files.
+ */
+static bool is_memfd_file(struct file *file)
+{
+       const struct dentry *dentry;
+       const unsigned char *name;
+       size_t name_len;
Quoted 8 lines
Quoted 8 lines

security/landlock/fs.c get_required_file_open_access(const struct file *const file) · line 1700

Quoted 8 lines
security/landlock/fs.c +8 -0
+
+       /* Fast path: basic validation */
+       if (unlikely(!file))
+               return false;
+
+       /* Must be shmem-backed first - this is the cheapest definitive check */
+       if (!shmem_file(file))
+               return false;

In which case a memfd would not be detected by this function? shmem_file_operations or hugetlbfs_file_operations are always set for memfd right?

We could export memfd_get_seals() to stay consistent over time.

Quoted 25 lines
Quoted 25 lines
Quoted 10 lines
security/landlock/fs.c +10 -0
+
+#ifdef CONFIG_MEMFD_CREATE
+
+       /* Validate dentry and get name info */
+       dentry = file->f_path.dentry;
+       if (unlikely(!dentry))
+               return false;
+
+       name_len = dentry->d_name.len;
+       name = dentry->d_name.name;

security/landlock/fs.c get_required_file_open_access(const struct file *const file) · line 1720

Quoted 10 lines
security/landlock/fs.c +10 -0
+
+       /* memfd files always have “memfd:” prefix (6 characters) */
+       if (name_len < 6 || unlikely(!name))
+               return false;
+
+       /* Check for exact “memfd:” prefix */
+       return memcmp(name, “memfd:”, 6) == 0;
+#else
+       return false;
+#endif

I was trying to do something similar early this year but didn’t hear feedback from the linux-mm folks.
<https://lore.kernel.org/linux-security-module/[email protected]/>

Quoted 19 lines
Quoted 4 lines
Quoted 4 lines

I have considered this approach but didn’t use it. My concern is, potentially a malicious user can create a file in a shmem fs, e.g. tmpfs , with the “memfd:” prefix, which can be used to bypass security policy.

In the case of Landlock that should not be a security issue but a compatibility issue, which is not better.

Quoted 11 lines
Quoted 4 lines

(Resending this message due to a misconfiguration with my email client. Apologies for any inconvenience.)

-Fan

Hi Fan,

Thanks for your comments.

I agree that an LSM hook into memfd_create() would be a much better solution. In the absence of such a function, do you think adding a

Hmm, we cannot use hook_file_alloc_security() to enforce restriction on memfd creation because the inode mode is set after this call by memfd.c:alloc_file(). So we should indeed add a new LSM hook. That would also improve security checks on file creation for other file types.

Quoted 15 lines
Quoted 5 lines

d_unlinked(dentry) check could serve as an additional verification?

I say things since I *think* that legitimate memfd files are always unlinked while spoofed tmpfs files remain linked. I could be wrong though.

We should just use the same checks used by the memfd-related syscalls/operations to detect such file.

Quoted 5 lines

In any case, we can test this approach using kprobes to validate the behavior.

-Abhinav

#11 lore raw
In reply to Mickaël Salaün

Thanks for the detailed reply Mickaël!

Quoted 42 lines · Mickaël Salaün

Thanks for this patch series Abhinav! The code looks good overall, but we should clarify the design. Sorry for the delayed response, it is on my radar now.

CCing Jeff and Daniel

Quoted 14 lines · Abhinav Saxena

This patch series introduces LANDLOCK_SCOPE_MEMFD_EXEC, a new Landlock scoping mechanism that restricts execution of anonymous memory file descriptors (memfd) created via memfd_create(2). This addresses security gaps where processes can bypass W^X policies and execute arbitrary code through anonymous memory objects.

SECURITY PROBLEM
`=============='

Current Landlock filesystem restrictions do not cover memfd objects, allowing processes to:

Quoted 7 lines

1. Read-to-execute bypass: Create writable memfd, inject code, then execute via mmap(PROT_EXEC) or direct execve()
2. Anonymous execution: Execute code without touching the filesystem via execve(“/proc/self/fd/N”) where N is a memfd descriptor

3. Cross-domain access violations: Pass memfd between processes to bypass domain restrictions

Landlock only restricts access at open time, which is a useful property. This enables to create more restricted sandboxes but still get access to outside resources via trusted processes. If the process passing the FDs is not trusted, the sandboxed process could just ask to execute arbitrary code outside the sandbox anyway.

However, the Landlock scopes are designed to block IPC from within a sandbox to outside the sandbox. We could have a new scope to forbid a sandbox process to receive or inherit file descriptors, but that would be a different and generic feature. For compatibility reasons, this might not be easy to implement and I think there are more important features to implement before that.

Quoted 9 lines

Thinking more about it, restricting memfd should not be a “scoped” flag because the semantic is not the same, but we should have a new ruleset property instead, something like “ruleset.denied” with a related LANDLOCK_DENY_EXECUTE_MEMFD flag. This flag will only have an impact on newly created memfd from a sandboxed process with this restriction at creation time. This could be implemented with hook_file_alloc_security() by checking if the file is indeed a memfd and checking inode->i_mode for executability bits (which would imply MFD_NOEXEC_SEAL).

Thanks for the clarification! So if I understood correctly we are proposing adding a denied field to the landlock_ruleset_attr struct

struct landlock_ruleset_attr {
    __u64 handled_access_fs;
    __u64 handled_access_net;
    __u64 scoped;
    __u64 denied;              /* New field */
};

which allows memfd_create() to be allowed by default unless LANDLOCK_DENY_EXECUTE_MEMFD bit is set. Also it seems Thiébaud Weksteen’s patch[1] will land, and maybe we can use security_inode_init_security_anon instead? What do you think?

Apologies for my ignorance, do we have to wait till his patch has landed into Linus’s tree?

Quoted 71 lines
Quoted 55 lines

These scenarios can occur in sandboxed environments where filesystem access is restricted but memfd creation remains possible.

IMPLEMENTATION
`============'

The implementation adds hierarchical execution control through domain scoping:

Core Components:
- is_memfd_file(): Reliable memfd detection via “memfd:” dentry prefix
- domain_is_scoped(): Cross-domain hierarchy checking (moved to domain.c)
- LSM hooks: mmap_file, file_mprotect, bprm_creds_for_exec
- Creation-time restrictions: hook_file_alloc_security

Security Matrix:
Execution decisions follow domain hierarchy rules preventing both same-domain bypass attempts and cross-domain access violations while preserving legitimate hierarchical access patterns.

Domain Hierarchy with LANDLOCK_SCOPE_MEMFD_EXEC:
`============================================='

Root (no domain) - No restrictions
|
+– Domain A [SCOPE_MEMFD_EXEC] Layer 1

  |     +– memfd_A (tagged with Domain A as creator)
  |     |
  |     +– Domain A1 (child) [NO SCOPE] Layer 2
  |     |     +– Inherits Layer 1 restrictions from parent
  |     |     +– memfd_A1 (can create, inherits restrictions)
  |     |     +– Domain A1a [SCOPE_MEMFD_EXEC] Layer 3
  |     |           +– memfd_A1a (tagged with Domain A1a)
  |     |
  |     +– Domain A2 (child) [SCOPE_MEMFD_EXEC] Layer 2
  |           +– memfd_A2 (tagged with Domain A2 as creator)
  |           +– CANNOT access memfd_A1 (different subtree)
  |

+– Domain B [SCOPE_MEMFD_EXEC] Layer 1
+– memfd_B (tagged with Domain B as creator) +– CANNOT access ANY memfd from Domain A subtree

Execution Decision Matrix:
`======================'

Executor->  |  A  | A1 | A1a | A2 | B  | Root
Creator     |     |    |     |    |    |
————|—–|—-|—–|—-|—-|—–
Domain A    |  X  | X  | X   | X  | X  |  Y
Domain A1   |  Y  | X  | X   | X  | X  |  Y
Domain A1a  |  Y  | Y  | X   | X  | X  |  Y
Domain A2   |  Y  | X  | X   | X  | X  |  Y
Domain B    |  X  | X  | X   | X  | X  |  Y
Root        |  Y  | Y  | Y   | Y  | Y  |  Y
Quoted 1 line

Legend: Y = Execution allowed, X = Execution denied

Because checks should not be related to scopes, this will be much simpler.

Quoted 11 lines

Scenarios Covered:
- Direct mmap(PROT_EXEC) on memfd files
- Two-stage mmap(PROT_READ) + mprotect(PROT_EXEC) bypass attempts
- execve("/proc/self/fd/N") anonymous execution
- execveat() and fexecve() file descriptor execution
- Cross-process memfd inheritance and IPC passing

TESTING
`====='

Quoted 46 lines
Quoted 5 lines

All patches have been validated with:
- scripts/checkpatch.pl –strict (clean)
- Selftests covering same-domain restrictions, cross-domain hierarchy enforcement, and regular file isolation
- KUnit tests for memfd detection edge cases

Thanks for all these tests!

Quoted 38 lines

DISCLAIMER
`========'

My understanding of Landlock scoping semantics may be limited, but this implementation reflects my current understanding based on available documentation and code analysis. I welcome feedback and corrections regarding the scoping logic and domain hierarchy enforcement.

—
Abhinav Saxena (4):
landlock: add LANDLOCK_SCOPE_MEMFD_EXEC scope
landlock: implement memfd detection
landlock: add memfd exec LSM hooks and scoping selftests/landlock: add memfd execution tests

 include/uapi/linux/landlock.h                      |   5 +
 security/landlock/.kunitconfig                     |   1 +
 security/landlock/audit.c                          |   4 +
 security/landlock/audit.h                          |   1 +
 security/landlock/cred.c                           |  14 -
 security/landlock/domain.c                         |  67 ++++
 security/landlock/domain.h                         |   4 +
 security/landlock/fs.c                             | 405 ++++++++++++++++++++-
 security/landlock/limits.h                         |   2 +-
 security/landlock/task.c                           |  67 —-
 …/selftests/landlock/scoped_memfd_exec_test.c    | 325 +++++++++++++++++
 11 files changed, 812 insertions(+), 83 deletions(-)

—
base-commit: 5b74b2eff1eeefe43584e5b7b348c8cd3b723d38
change-id: 20250716-memfd-exec-ac0d582018c3

Best regards,
–
Abhinav Saxena <[email protected]>

Best,
Abhinav

[1] - <https://lore.kernel.org/all/[email protected]/>

maintainer
#12 lore raw
Quoted 7 lines · Abhinav Saxena

Thanks for the detailed reply Mickaël!

Quoted 3 lines · Mickaël Salaün

Thanks for this patch series Abhinav! The code looks good overall, but we should clarify the design. Sorry for the delayed response, it is on my radar now.

Please feel free to ping me after two weeks without answer, I might miss some emails.

Quoted 59 lines
Quoted 39 lines

CCing Jeff and Daniel

Quoted 14 lines · Abhinav Saxena

This patch series introduces LANDLOCK_SCOPE_MEMFD_EXEC, a new Landlock scoping mechanism that restricts execution of anonymous memory file descriptors (memfd) created via memfd_create(2). This addresses security gaps where processes can bypass W^X policies and execute arbitrary code through anonymous memory objects.

SECURITY PROBLEM
`=============='

Current Landlock filesystem restrictions do not cover memfd objects, allowing processes to:

Quoted 7 lines

1. Read-to-execute bypass: Create writable memfd, inject code, then execute via mmap(PROT_EXEC) or direct execve()
2. Anonymous execution: Execute code without touching the filesystem via execve(“/proc/self/fd/N”) where N is a memfd descriptor

3. Cross-domain access violations: Pass memfd between processes to bypass domain restrictions

Landlock only restricts access at open time, which is a useful property. This enables to create more restricted sandboxes but still get access to outside resources via trusted processes. If the process passing the FDs is not trusted, the sandboxed process could just ask to execute arbitrary code outside the sandbox anyway.

However, the Landlock scopes are designed to block IPC from within a sandbox to outside the sandbox. We could have a new scope to forbid a sandbox process to receive or inherit file descriptors, but that would be a different and generic feature. For compatibility reasons, this might not be easy to implement and I think there are more important features to implement before that.

Quoted 9 lines

Thinking more about it, restricting memfd should not be a “scoped” flag because the semantic is not the same, but we should have a new ruleset property instead, something like “ruleset.denied” with a related LANDLOCK_DENY_EXECUTE_MEMFD flag. This flag will only have an impact on newly created memfd from a sandboxed process with this restriction at creation time. This could be implemented with hook_file_alloc_security() by checking if the file is indeed a memfd and checking inode->i_mode for executability bits (which would imply MFD_NOEXEC_SEAL).

Thanks for the clarification! So if I understood correctly we are proposing adding a denied field to the landlock_ruleset_attr struct

struct landlock_ruleset_attr {
    __u64 handled_access_fs;
    __u64 handled_access_net;
    __u64 scoped;
    __u64 denied;              /* New field */
};
Quoted 2 lines

which allows memfd_create() to be allowed by default unless LANDLOCK_DENY_EXECUTE_MEMFD bit is set.

Yes

Quoted 3 lines

Also it seems Thiébaud
Weksteen’s patch[1] will land, and maybe we can use security_inode_init_security_anon instead? What do you think?

Definitely, and this patch is now merged in -next.

Quoted 3 lines

Apologies for my ignorance, do we have to wait till his patch has landed into Linus’s tree?

As long as you explain this dependency in the commit message and point to the patch (as a comment, after a "---" line), we're good.

Quoted 123 lines
Quoted 72 lines
Quoted 56 lines

These scenarios can occur in sandboxed environments where filesystem access is restricted but memfd creation remains possible.

IMPLEMENTATION
`============'

The implementation adds hierarchical execution control through domain scoping:

Core Components:
- is_memfd_file(): Reliable memfd detection via “memfd:” dentry prefix
- domain_is_scoped(): Cross-domain hierarchy checking (moved to domain.c)
- LSM hooks: mmap_file, file_mprotect, bprm_creds_for_exec
- Creation-time restrictions: hook_file_alloc_security

Security Matrix:
Execution decisions follow domain hierarchy rules preventing both same-domain bypass attempts and cross-domain access violations while preserving legitimate hierarchical access patterns.

Domain Hierarchy with LANDLOCK_SCOPE_MEMFD_EXEC:
`============================================='

Root (no domain) - No restrictions
|
+– Domain A [SCOPE_MEMFD_EXEC] Layer 1

  |     +– memfd_A (tagged with Domain A as creator)
  |     |
  |     +– Domain A1 (child) [NO SCOPE] Layer 2
  |     |     +– Inherits Layer 1 restrictions from parent
  |     |     +– memfd_A1 (can create, inherits restrictions)
  |     |     +– Domain A1a [SCOPE_MEMFD_EXEC] Layer 3
  |     |           +– memfd_A1a (tagged with Domain A1a)
  |     |
  |     +– Domain A2 (child) [SCOPE_MEMFD_EXEC] Layer 2
  |           +– memfd_A2 (tagged with Domain A2 as creator)
  |           +– CANNOT access memfd_A1 (different subtree)
  |

+– Domain B [SCOPE_MEMFD_EXEC] Layer 1
+– memfd_B (tagged with Domain B as creator) +– CANNOT access ANY memfd from Domain A subtree

Execution Decision Matrix:
`======================'

Executor->  |  A  | A1 | A1a | A2 | B  | Root
Creator     |     |    |     |    |    |
————|—–|—-|—–|—-|—-|—–
Domain A    |  X  | X  | X   | X  | X  |  Y
Domain A1   |  Y  | X  | X   | X  | X  |  Y
Domain A1a  |  Y  | Y  | X   | X  | X  |  Y
Domain A2   |  Y  | X  | X   | X  | X  |  Y
Domain B    |  X  | X  | X   | X  | X  |  Y
Root        |  Y  | Y  | Y   | Y  | Y  |  Y
Quoted 1 line

Legend: Y = Execution allowed, X = Execution denied

Because checks should not be related to scopes, this will be much simpler.

Quoted 11 lines

Scenarios Covered:
- Direct mmap(PROT_EXEC) on memfd files
- Two-stage mmap(PROT_READ) + mprotect(PROT_EXEC) bypass attempts
- execve("/proc/self/fd/N") anonymous execution
- execveat() and fexecve() file descriptor execution
- Cross-process memfd inheritance and IPC passing

TESTING
`====='

Quoted 46 lines
Quoted 5 lines

All patches have been validated with:
- scripts/checkpatch.pl –strict (clean)
- Selftests covering same-domain restrictions, cross-domain hierarchy enforcement, and regular file isolation
- KUnit tests for memfd detection edge cases

Thanks for all these tests!

Quoted 38 lines

DISCLAIMER
`========'

My understanding of Landlock scoping semantics may be limited, but this implementation reflects my current understanding based on available documentation and code analysis. I welcome feedback and corrections regarding the scoping logic and domain hierarchy enforcement.

—
Abhinav Saxena (4):
landlock: add LANDLOCK_SCOPE_MEMFD_EXEC scope
landlock: implement memfd detection
landlock: add memfd exec LSM hooks and scoping selftests/landlock: add memfd execution tests

 include/uapi/linux/landlock.h                      |   5 +
 security/landlock/.kunitconfig                     |   1 +
 security/landlock/audit.c                          |   4 +
 security/landlock/audit.h                          |   1 +
 security/landlock/cred.c                           |  14 -
 security/landlock/domain.c                         |  67 ++++
 security/landlock/domain.h                         |   4 +
 security/landlock/fs.c                             | 405 ++++++++++++++++++++-
 security/landlock/limits.h                         |   2 +-
 security/landlock/task.c                           |  67 —-
 …/selftests/landlock/scoped_memfd_exec_test.c    | 325 +++++++++++++++++
 11 files changed, 812 insertions(+), 83 deletions(-)

—
base-commit: 5b74b2eff1eeefe43584e5b7b348c8cd3b723d38
change-id: 20250716-memfd-exec-ac0d582018c3

Best regards,
–
Abhinav Saxena <[email protected]>

Best,
Abhinav

[1] - <https://lore.kernel.org/all/[email protected]/>