xref: /linux/security/landlock/syscalls.c (revision 67f8bc848ee31831336bd478e57d2f993551902e)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Landlock - System call implementations and user space interfaces
4  *
5  * Copyright © 2016-2020 Mickaël Salaün <mic@digikod.net>
6  * Copyright © 2018-2020 ANSSI
7  * Copyright © 2021-2025 Microsoft Corporation
8  */
9 
10 #include <asm/current.h>
11 #include <linux/anon_inodes.h>
12 #include <linux/bitops.h>
13 #include <linux/build_bug.h>
14 #include <linux/capability.h>
15 #include <linux/cleanup.h>
16 #include <linux/compiler_types.h>
17 #include <linux/dcache.h>
18 #include <linux/err.h>
19 #include <linux/errno.h>
20 #include <linux/fs.h>
21 #include <linux/limits.h>
22 #include <linux/mount.h>
23 #include <linux/path.h>
24 #include <linux/sched.h>
25 #include <linux/sched/signal.h>
26 #include <linux/security.h>
27 #include <linux/stddef.h>
28 #include <linux/syscalls.h>
29 #include <linux/types.h>
30 #include <linux/uaccess.h>
31 #include <uapi/linux/landlock.h>
32 
33 #include "cred.h"
34 #include "domain.h"
35 #include "fs.h"
36 #include "limits.h"
37 #include "net.h"
38 #include "ruleset.h"
39 #include "setup.h"
40 #include "tsync.h"
41 
42 #include <trace/events/landlock.h>
43 
44 static bool is_initialized(void)
45 {
46 	if (likely(landlock_initialized))
47 		return true;
48 
49 	pr_warn_once(
50 		"Disabled but requested by user space. "
51 		"You should enable Landlock at boot time: "
52 		"https://docs.kernel.org/userspace-api/landlock.html#boot-time-configuration\n");
53 	return false;
54 }
55 
56 /**
57  * copy_min_struct_from_user - Safe future-proof argument copying
58  *
59  * Extend copy_struct_from_user() to check for consistent user buffer.
60  *
61  * @dst: Kernel space pointer or NULL.
62  * @ksize: Actual size of the data pointed to by @dst.
63  * @ksize_min: Minimal required size to be copied.
64  * @src: User space pointer or NULL.
65  * @usize: (Alleged) size of the data pointed to by @src.
66  *
67  * Return: 0 on success, -errno on failure.
68  */
69 static __always_inline int
70 copy_min_struct_from_user(void *const dst, const size_t ksize,
71 			  const size_t ksize_min, const void __user *const src,
72 			  const size_t usize)
73 {
74 	/* Checks buffer inconsistencies. */
75 	BUILD_BUG_ON(!dst);
76 	if (!src)
77 		return -EFAULT;
78 
79 	/* Checks size ranges. */
80 	BUILD_BUG_ON(ksize <= 0);
81 	BUILD_BUG_ON(ksize < ksize_min);
82 	if (usize < ksize_min)
83 		return -EINVAL;
84 	if (usize > PAGE_SIZE)
85 		return -E2BIG;
86 
87 	/* Copies user buffer and fills with zeros. */
88 	return copy_struct_from_user(dst, ksize, src, usize);
89 }
90 
91 /*
92  * This function only contains arithmetic operations with constants, leading to
93  * BUILD_BUG_ON().  The related code is evaluated and checked at build time,
94  * but it is then ignored thanks to compiler optimizations.
95  */
96 static void build_check_abi(void)
97 {
98 	struct landlock_ruleset_attr ruleset_attr;
99 	struct landlock_path_beneath_attr path_beneath_attr;
100 	struct landlock_net_port_attr net_port_attr;
101 	size_t ruleset_size, path_beneath_size, net_port_size;
102 
103 	/*
104 	 * For each user space ABI structures, first checks that there is no
105 	 * hole in them, then checks that all architectures have the same
106 	 * struct size.
107 	 */
108 	ruleset_size = sizeof(ruleset_attr.handled_access_fs);
109 	ruleset_size += sizeof(ruleset_attr.handled_access_net);
110 	ruleset_size += sizeof(ruleset_attr.scoped);
111 	ruleset_size += sizeof(ruleset_attr.quiet_access_fs);
112 	ruleset_size += sizeof(ruleset_attr.quiet_access_net);
113 	ruleset_size += sizeof(ruleset_attr.quiet_scoped);
114 	BUILD_BUG_ON(sizeof(ruleset_attr) != ruleset_size);
115 	BUILD_BUG_ON(sizeof(ruleset_attr) != 48);
116 
117 	path_beneath_size = sizeof(path_beneath_attr.allowed_access);
118 	path_beneath_size += sizeof(path_beneath_attr.parent_fd);
119 	BUILD_BUG_ON(sizeof(path_beneath_attr) != path_beneath_size);
120 	BUILD_BUG_ON(sizeof(path_beneath_attr) != 12);
121 
122 	net_port_size = sizeof(net_port_attr.allowed_access);
123 	net_port_size += sizeof(net_port_attr.port);
124 	BUILD_BUG_ON(sizeof(net_port_attr) != net_port_size);
125 	BUILD_BUG_ON(sizeof(net_port_attr) != 16);
126 }
127 
128 /* Ruleset handling */
129 
130 static int fop_ruleset_release(struct inode *const inode,
131 			       struct file *const filp)
132 {
133 	struct landlock_ruleset *ruleset = filp->private_data;
134 
135 	landlock_put_ruleset(ruleset);
136 	return 0;
137 }
138 
139 static ssize_t fop_dummy_read(struct file *const filp, char __user *const buf,
140 			      const size_t size, loff_t *const ppos)
141 {
142 	/* Dummy handler to enable FMODE_CAN_READ. */
143 	return -EINVAL;
144 }
145 
146 static ssize_t fop_dummy_write(struct file *const filp,
147 			       const char __user *const buf, const size_t size,
148 			       loff_t *const ppos)
149 {
150 	/* Dummy handler to enable FMODE_CAN_WRITE. */
151 	return -EINVAL;
152 }
153 
154 /*
155  * A ruleset file descriptor enables to build a ruleset by adding (i.e.
156  * writing) rule after rule, without relying on the task's context.  This
157  * reentrant design is also used in a read way to enforce the ruleset on the
158  * current task.
159  */
160 static const struct file_operations ruleset_fops = {
161 	.release = fop_ruleset_release,
162 	.read = fop_dummy_read,
163 	.write = fop_dummy_write,
164 };
165 
166 /*
167  * The Landlock ABI version should be incremented for each new Landlock-related
168  * user space visible change (e.g. Landlock syscalls).  This version should
169  * only be incremented once per Linux release.  When incrementing, the date in
170  * Documentation/userspace-api/landlock.rst should be updated to reflect the
171  * UAPI change.
172  * If the change involves a fix that requires userspace awareness, also update
173  * the errata documentation in Documentation/userspace-api/landlock.rst .
174  */
175 const int landlock_abi_version = 11;
176 
177 /**
178  * sys_landlock_create_ruleset - Create a new ruleset
179  *
180  * @attr: Pointer to a &struct landlock_ruleset_attr identifying the scope of
181  *        the new ruleset.
182  * @size: Size of the pointed &struct landlock_ruleset_attr (needed for
183  *        backward and forward compatibility).
184  * @flags: Supported values:
185  *
186  *         - %LANDLOCK_CREATE_RULESET_VERSION
187  *         - %LANDLOCK_CREATE_RULESET_ERRATA
188  *
189  * This system call enables to create a new Landlock ruleset.
190  *
191  * If %LANDLOCK_CREATE_RULESET_VERSION or %LANDLOCK_CREATE_RULESET_ERRATA is
192  * set, then @attr must be NULL and @size must be 0.
193  *
194  * Return: The ruleset file descriptor on success, the Landlock ABI version if
195  * %LANDLOCK_CREATE_RULESET_VERSION is set, the errata value if
196  * %LANDLOCK_CREATE_RULESET_ERRATA is set, or -errno on failure.  Possible
197  * returned errors are:
198  *
199  * - %EOPNOTSUPP: Landlock is supported by the kernel but disabled at boot time;
200  * - %EINVAL: unknown @flags, or unknown access, or unknown scope, or too small
201  *   @size;
202  * - %EINVAL: quiet_access_fs, quiet_access_net, or quiet_scoped is not a
203  *   subset of the corresponding handled_access_fs, handled_access_net, or
204  *   scoped;
205  * - %E2BIG: @attr or @size inconsistencies;
206  * - %EFAULT: @attr or @size inconsistencies;
207  * - %ENOMSG: empty &landlock_ruleset_attr.handled_access_fs.
208  *
209  * .. kernel-doc:: include/uapi/linux/landlock.h
210  *     :identifiers: landlock_create_ruleset_flags
211  */
212 SYSCALL_DEFINE3(landlock_create_ruleset,
213 		const struct landlock_ruleset_attr __user *const, attr,
214 		const size_t, size, const __u32, flags)
215 {
216 	struct landlock_ruleset_attr ruleset_attr;
217 	struct landlock_ruleset *ruleset;
218 	int err, ruleset_fd;
219 
220 	/* Build-time checks. */
221 	build_check_abi();
222 
223 	if (!is_initialized())
224 		return -EOPNOTSUPP;
225 
226 	if (flags) {
227 		if (attr || size)
228 			return -EINVAL;
229 
230 		if (flags == LANDLOCK_CREATE_RULESET_VERSION)
231 			return landlock_abi_version;
232 
233 		if (flags == LANDLOCK_CREATE_RULESET_ERRATA)
234 			return landlock_errata;
235 
236 		return -EINVAL;
237 	}
238 
239 	/* Copies raw user space buffer. */
240 	err = copy_min_struct_from_user(&ruleset_attr, sizeof(ruleset_attr),
241 					offsetofend(typeof(ruleset_attr),
242 						    handled_access_fs),
243 					attr, size);
244 	if (err)
245 		return err;
246 
247 	/* Checks content (and 32-bits cast). */
248 	if ((ruleset_attr.handled_access_fs | LANDLOCK_MASK_ACCESS_FS) !=
249 	    LANDLOCK_MASK_ACCESS_FS)
250 		return -EINVAL;
251 
252 	/* Checks network content (and 32-bits cast). */
253 	if ((ruleset_attr.handled_access_net | LANDLOCK_MASK_ACCESS_NET) !=
254 	    LANDLOCK_MASK_ACCESS_NET)
255 		return -EINVAL;
256 
257 	/* Checks IPC scoping content (and 32-bits cast). */
258 	if ((ruleset_attr.scoped | LANDLOCK_MASK_SCOPE) != LANDLOCK_MASK_SCOPE)
259 		return -EINVAL;
260 
261 	/*
262 	 * Check that quiet masks are subsets of the respective handled masks.
263 	 * Because of the checks above this is sufficient to also ensure that
264 	 * the quiet masks are valid access masks.
265 	 */
266 	if ((ruleset_attr.quiet_access_fs | ruleset_attr.handled_access_fs) !=
267 	    ruleset_attr.handled_access_fs)
268 		return -EINVAL;
269 	if ((ruleset_attr.quiet_access_net | ruleset_attr.handled_access_net) !=
270 	    ruleset_attr.handled_access_net)
271 		return -EINVAL;
272 	if ((ruleset_attr.quiet_scoped | ruleset_attr.scoped) !=
273 	    ruleset_attr.scoped)
274 		return -EINVAL;
275 
276 	/* Checks arguments and transforms to kernel struct. */
277 	ruleset = landlock_create_ruleset(ruleset_attr.handled_access_fs,
278 					  ruleset_attr.handled_access_net,
279 					  ruleset_attr.scoped);
280 	if (IS_ERR(ruleset))
281 		return PTR_ERR(ruleset);
282 
283 	ruleset->quiet_masks.fs = ruleset_attr.quiet_access_fs;
284 	ruleset->quiet_masks.net = ruleset_attr.quiet_access_net;
285 	ruleset->quiet_masks.scope = ruleset_attr.quiet_scoped;
286 
287 	/*
288 	 * Emits before anon_inode_getfd() installs the file descriptor, while
289 	 * the ruleset is still private to this thread: no lock is needed, and
290 	 * the event cannot race a concurrent close() freeing the ruleset under
291 	 * the tracepoint's BTF read.  This is the last point at which the
292 	 * ruleset is guaranteed alive and unshared.
293 	 */
294 	trace_landlock_create_ruleset(ruleset);
295 
296 	/* Creates anonymous FD referring to the ruleset. */
297 	ruleset_fd = anon_inode_getfd("[landlock-ruleset]", &ruleset_fops,
298 				      ruleset, O_RDWR | O_CLOEXEC);
299 	if (ruleset_fd < 0)
300 		landlock_put_ruleset(ruleset);
301 	return ruleset_fd;
302 }
303 
304 /*
305  * Returns an owned ruleset from a FD. It is thus needed to call
306  * landlock_put_ruleset() on the return value.
307  */
308 static struct landlock_ruleset *get_ruleset_from_fd(const int fd,
309 						    const fmode_t mode)
310 {
311 	CLASS(fd, ruleset_f)(fd);
312 	struct landlock_ruleset *ruleset;
313 
314 	if (fd_empty(ruleset_f))
315 		return ERR_PTR(-EBADF);
316 
317 	/* Checks FD type and access right. */
318 	if (fd_file(ruleset_f)->f_op != &ruleset_fops)
319 		return ERR_PTR(-EBADFD);
320 	if (!(fd_file(ruleset_f)->f_mode & mode))
321 		return ERR_PTR(-EPERM);
322 	ruleset = fd_file(ruleset_f)->private_data;
323 	landlock_get_ruleset(ruleset);
324 	return ruleset;
325 }
326 
327 /* Path handling */
328 
329 /*
330  * @path: Must call put_path(@path) after the call if it succeeded.
331  */
332 static int get_path_from_fd(const s32 fd, struct path *const path)
333 {
334 	CLASS(fd_raw, f)(fd);
335 
336 	BUILD_BUG_ON(!__same_type(
337 		fd, ((struct landlock_path_beneath_attr *)NULL)->parent_fd));
338 
339 	if (fd_empty(f))
340 		return -EBADF;
341 	/*
342 	 * Forbids ruleset FDs, internal filesystems (e.g. nsfs), including
343 	 * pseudo filesystems that will never be mountable (e.g. sockfs,
344 	 * pipefs).
345 	 */
346 	if ((fd_file(f)->f_op == &ruleset_fops) ||
347 	    (fd_file(f)->f_path.mnt->mnt_flags & MNT_INTERNAL) ||
348 	    (fd_file(f)->f_path.dentry->d_sb->s_flags & SB_NOUSER) ||
349 	    IS_PRIVATE(d_backing_inode(fd_file(f)->f_path.dentry)))
350 		return -EBADFD;
351 
352 	*path = fd_file(f)->f_path;
353 	path_get(path);
354 	return 0;
355 }
356 
357 static int add_rule_path_beneath(struct landlock_ruleset *const ruleset,
358 				 const void __user *const rule_attr, u32 flags)
359 {
360 	struct landlock_path_beneath_attr path_beneath_attr;
361 	struct path path;
362 	int res, err;
363 	access_mask_t mask;
364 
365 	/* Copies raw user space buffer. */
366 	res = copy_from_user(&path_beneath_attr, rule_attr,
367 			     sizeof(path_beneath_attr));
368 	if (res)
369 		return -EFAULT;
370 
371 	/*
372 	 * Informs about useless rule: empty allowed_access (i.e. deny rules)
373 	 * are ignored in path walks.  However, the rule is not useless if it is
374 	 * there to hold a quiet flag.
375 	 */
376 	if (!flags && !path_beneath_attr.allowed_access)
377 		return -ENOMSG;
378 
379 	/* Checks that allowed_access matches the @ruleset constraints. */
380 	mask = ruleset->handled_masks.fs;
381 	if ((path_beneath_attr.allowed_access | mask) != mask)
382 		return -EINVAL;
383 
384 	/* Checks for useless quiet flag. */
385 	if (flags & LANDLOCK_ADD_RULE_QUIET && !ruleset->quiet_masks.fs)
386 		return -EINVAL;
387 
388 	/* Gets and checks the new rule. */
389 	err = get_path_from_fd(path_beneath_attr.parent_fd, &path);
390 	if (err)
391 		return err;
392 
393 	/* Imports the new rule. */
394 	err = landlock_append_fs_rule(ruleset, &path,
395 				      path_beneath_attr.allowed_access, flags);
396 	path_put(&path);
397 	return err;
398 }
399 
400 static int add_rule_net_port(struct landlock_ruleset *ruleset,
401 			     const void __user *const rule_attr, u32 flags)
402 {
403 	struct landlock_net_port_attr net_port_attr;
404 	int res;
405 	access_mask_t mask;
406 
407 	/* Copies raw user space buffer. */
408 	res = copy_from_user(&net_port_attr, rule_attr, sizeof(net_port_attr));
409 	if (res)
410 		return -EFAULT;
411 
412 	/*
413 	 * Informs about useless rule: empty allowed_access (i.e. deny rules)
414 	 * are ignored by network actions.  However, the rule is not useless if
415 	 * it is there to hold a quiet flag.
416 	 */
417 	if (!flags && !net_port_attr.allowed_access)
418 		return -ENOMSG;
419 
420 	/* Checks that allowed_access matches the @ruleset constraints. */
421 	mask = ruleset->handled_masks.net;
422 	if ((net_port_attr.allowed_access | mask) != mask)
423 		return -EINVAL;
424 
425 	/* Checks for useless quiet flag. */
426 	if (flags & LANDLOCK_ADD_RULE_QUIET && !ruleset->quiet_masks.net)
427 		return -EINVAL;
428 
429 	/* Denies inserting a rule with port greater than 65535. */
430 	if (net_port_attr.port > U16_MAX)
431 		return -EINVAL;
432 
433 	/* Imports the new rule. */
434 	return landlock_append_net_rule(ruleset, net_port_attr.port,
435 					net_port_attr.allowed_access, flags);
436 }
437 
438 /**
439  * sys_landlock_add_rule - Add a new rule to a ruleset
440  *
441  * @ruleset_fd: File descriptor tied to the ruleset that should be extended
442  *		with the new rule.
443  * @rule_type: Identify the structure type pointed to by @rule_attr:
444  *             %LANDLOCK_RULE_PATH_BENEATH or %LANDLOCK_RULE_NET_PORT.
445  * @rule_attr: Pointer to a rule (matching the @rule_type).
446  * @flags: Must be 0 or %LANDLOCK_ADD_RULE_QUIET.
447  *
448  * This system call enables to define a new rule and add it to an existing
449  * ruleset.
450  *
451  * Return: 0 on success, or -errno on failure.  Possible returned errors are:
452  *
453  * - %EOPNOTSUPP: Landlock is supported by the kernel but disabled at boot time;
454  * - %EAFNOSUPPORT: @rule_type is %LANDLOCK_RULE_NET_PORT but TCP/IP is not
455  *   supported by the running kernel;
456  * - %EINVAL: @flags is not valid;
457  * - %EINVAL: The rule accesses are inconsistent (i.e.
458  *   &landlock_path_beneath_attr.allowed_access or
459  *   &landlock_net_port_attr.allowed_access is not a subset of the ruleset
460  *   handled accesses)
461  * - %EINVAL: &landlock_net_port_attr.port is greater than 65535;
462  * - %EINVAL: LANDLOCK_ADD_RULE_QUIET is passed but the ruleset has no
463  *   quiet access bits set for the corresponding rule type.
464  * - %ENOMSG: Empty accesses (e.g. &landlock_path_beneath_attr.allowed_access is
465  *   0) and no flags;
466  * - %EBADF: @ruleset_fd is not a file descriptor for the current thread, or a
467  *   member of @rule_attr is not a file descriptor as expected;
468  * - %EBADFD: @ruleset_fd is not a ruleset file descriptor, or a member of
469  *   @rule_attr is not the expected file descriptor type;
470  * - %EPERM: @ruleset_fd has no write access to the underlying ruleset;
471  * - %EFAULT: @rule_attr was not a valid address.
472  *
473  * .. kernel-doc:: include/uapi/linux/landlock.h
474  *     :identifiers: landlock_add_rule_flags
475  */
476 SYSCALL_DEFINE4(landlock_add_rule, const int, ruleset_fd,
477 		const enum landlock_rule_type, rule_type,
478 		const void __user *const, rule_attr, const __u32, flags)
479 {
480 	struct landlock_ruleset *ruleset __free(landlock_put_ruleset) = NULL;
481 
482 	if (!is_initialized())
483 		return -EOPNOTSUPP;
484 
485 	if (flags && flags != LANDLOCK_ADD_RULE_QUIET)
486 		return -EINVAL;
487 
488 	/* Gets and checks the ruleset. */
489 	ruleset = get_ruleset_from_fd(ruleset_fd, FMODE_CAN_WRITE);
490 	if (IS_ERR(ruleset))
491 		return PTR_ERR(ruleset);
492 
493 	switch (rule_type) {
494 	case LANDLOCK_RULE_PATH_BENEATH:
495 		return add_rule_path_beneath(ruleset, rule_attr, flags);
496 	case LANDLOCK_RULE_NET_PORT:
497 		return add_rule_net_port(ruleset, rule_attr, flags);
498 	default:
499 		return -EINVAL;
500 	}
501 }
502 
503 /* Enforcement */
504 
505 /**
506  * sys_landlock_restrict_self - Enforce a ruleset on the calling thread
507  *
508  * @ruleset_fd: File descriptor tied to the ruleset to merge with the target.
509  * @flags: Supported values:
510  *
511  *         - %LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF
512  *         - %LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON
513  *         - %LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF
514  *         - %LANDLOCK_RESTRICT_SELF_TSYNC
515  *         - %LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS
516  *
517  * This system call enforces a Landlock ruleset on the current thread.
518  * Enforcing a ruleset requires that the task has %CAP_SYS_ADMIN in its
519  * namespace or is running with no_new_privs.  This avoids scenarios where
520  * unprivileged tasks can affect the behavior of privileged children.
521  *
522  * With %LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS, the no_new_privs attribute of the
523  * calling thread is set only once the enforcement of the ruleset succeeded,
524  * which fulfills the above requirement: no_new_privs is set if and only if the
525  * call succeeds.
526  *
527  * Return: 0 on success, or -errno on failure.  Possible returned errors are:
528  *
529  * - %EOPNOTSUPP: Landlock is supported by the kernel but disabled at boot time;
530  * - %EINVAL: @flags contains an unknown bit.
531  * - %EBADF: @ruleset_fd is not a file descriptor for the current thread;
532  * - %EBADFD: @ruleset_fd is not a ruleset file descriptor;
533  * - %EPERM: @ruleset_fd has no read access to the underlying ruleset, or
534  *   %LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS is not set while the current thread
535  *   is not running with no_new_privs and doesn't have %CAP_SYS_ADMIN in its
536  *   namespace.
537  * - %E2BIG: The maximum number of stacked rulesets is reached for the current
538  *   thread.
539  *
540  * .. kernel-doc:: include/uapi/linux/landlock.h
541  *     :identifiers: landlock_restrict_self_flags
542  */
543 SYSCALL_DEFINE2(landlock_restrict_self, const int, ruleset_fd, const __u32,
544 		flags)
545 {
546 	struct landlock_ruleset *ruleset __free(landlock_put_ruleset) = NULL;
547 	struct landlock_domain *new_dom = NULL;
548 	struct cred *new_cred;
549 	struct landlock_cred_security *new_llcred;
550 	bool process_wide;
551 	bool __maybe_unused log_same_exec, log_new_exec, log_subdomains,
552 		prev_log_subdomains;
553 
554 	if (!is_initialized())
555 		return -EOPNOTSUPP;
556 
557 	if ((flags | LANDLOCK_MASK_RESTRICT_SELF) !=
558 	    LANDLOCK_MASK_RESTRICT_SELF)
559 		return -EINVAL;
560 
561 	/*
562 	 * Similar checks as for seccomp(2), except that an -EPERM may be
563 	 * returned.  LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS fulfills this
564 	 * requirement.
565 	 */
566 	if (!(flags & LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS) &&
567 	    !task_no_new_privs(current) &&
568 	    !ns_capable_noaudit(current_user_ns(), CAP_SYS_ADMIN))
569 		return -EPERM;
570 
571 	/* Translates "off" flag to boolean. */
572 	log_same_exec = !(flags & LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF);
573 	/* Translates "on" flag to boolean. */
574 	log_new_exec = !!(flags & LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON);
575 	/* Translates "off" flag to boolean. */
576 	log_subdomains = !(flags & LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF);
577 
578 	/*
579 	 * It is allowed to set LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF with
580 	 * -1 as ruleset_fd, optionally combined with
581 	 * LANDLOCK_RESTRICT_SELF_TSYNC to propagate this configuration to all
582 	 * threads.  No other flag must be set.
583 	 */
584 	if (!(ruleset_fd == -1 &&
585 	      (flags & ~LANDLOCK_RESTRICT_SELF_TSYNC) ==
586 		      LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF)) {
587 		/* Gets and checks the ruleset. */
588 		ruleset = get_ruleset_from_fd(ruleset_fd, FMODE_CAN_READ);
589 		if (IS_ERR(ruleset))
590 			return PTR_ERR(ruleset);
591 	}
592 
593 	/* Prepares new credentials. */
594 	new_cred = prepare_creds();
595 	if (!new_cred)
596 		return -ENOMEM;
597 
598 	new_llcred = landlock_cred(new_cred);
599 
600 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
601 	prev_log_subdomains = !new_llcred->log_subdomains_off;
602 	new_llcred->log_subdomains_off = !prev_log_subdomains ||
603 					 !log_subdomains;
604 #endif /* CONFIG_SECURITY_LANDLOCK_LOG */
605 
606 	/*
607 	 * The only case when a ruleset may not be set is if
608 	 * LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF is set (optionally with
609 	 * LANDLOCK_RESTRICT_SELF_TSYNC) and ruleset_fd is -1.  We could
610 	 * optimize this case by not calling commit_creds() if this flag was
611 	 * already set, but it is not worth the complexity.
612 	 */
613 	if (ruleset) {
614 		/*
615 		 * There is no possible race condition while copying and
616 		 * manipulating the current credentials because they are
617 		 * dedicated per thread.
618 		 */
619 		mutex_lock(&ruleset->lock);
620 		new_dom = landlock_merge_ruleset(new_llcred->domain, ruleset);
621 		if (IS_ERR(new_dom)) {
622 			mutex_unlock(&ruleset->lock);
623 			abort_creds(new_cred);
624 			return PTR_ERR(new_dom);
625 		}
626 		/*
627 		 * Emits the domain-creation event while @ruleset->lock is still
628 		 * held, right after the merge, so an eBPF program attached to
629 		 * the tracepoint reads the exact ruleset that was merged into
630 		 * the domain: a consistent snapshot that a concurrent
631 		 * landlock_add_rule() (which holds the same lock) cannot
632 		 * modify.
633 		 *
634 		 * This must come before the thread-sync wait below.  Holding
635 		 * @ruleset->lock across landlock_restrict_sibling_threads()
636 		 * would hang: a sibling thread blocked in landlock_add_rule()
637 		 * on the same @ruleset->lock cannot run the task_work that
638 		 * thread-sync waits for (the lock wait is uninterruptible).
639 		 * Emitting here keeps the lock off the thread-sync path.
640 		 *
641 		 * The trade-off is that the event fires for a domain that a
642 		 * later (rare) thread-sync failure aborts.  That path emits the
643 		 * matching free_domain event so the create/free pair stays
644 		 * balanced (see the thread-sync error path below).
645 		 */
646 		trace_landlock_create_domain(new_dom, ruleset);
647 		mutex_unlock(&ruleset->lock);
648 
649 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
650 		new_dom->hierarchy->log_same_exec = log_same_exec;
651 		new_dom->hierarchy->log_new_exec = log_new_exec;
652 		/*
653 		 * The creation event fired above, so move the domain out of
654 		 * LANDLOCK_LOG_UNCOMMITTED: its free_domain event must fire
655 		 * too, even if a thread-sync failure aborts it below.  Audit
656 		 * logging may still be disabled (DISABLED); tracing observes it
657 		 * anyway.
658 		 */
659 		if ((!log_same_exec && !log_new_exec) || !prev_log_subdomains)
660 			new_dom->hierarchy->log_status = LANDLOCK_LOG_DISABLED;
661 		else
662 			new_dom->hierarchy->log_status = LANDLOCK_LOG_PENDING;
663 #endif /* CONFIG_SECURITY_LANDLOCK_LOG */
664 
665 		/* Replaces the old (prepared) domain. */
666 		landlock_put_domain(new_llcred->domain);
667 		new_llcred->domain = new_dom;
668 
669 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
670 		new_llcred->domain_exec |= BIT(new_dom->num_layers - 1);
671 #endif /* CONFIG_SECURITY_LANDLOCK_LOG */
672 	}
673 
674 	if (flags & LANDLOCK_RESTRICT_SELF_TSYNC) {
675 		const int err = landlock_restrict_sibling_threads(
676 			current_cred(), new_cred, flags);
677 		if (err) {
678 			/*
679 			 * Thread-sync failed (rare), so the new domain is
680 			 * aborted instead of committed.  Its creation event
681 			 * already fired above, so the imminent free must emit
682 			 * the matching free_domain event to keep the
683 			 * create/free pair balanced; no special log_status is
684 			 * set here.
685 			 */
686 			abort_creds(new_cred);
687 			return err;
688 		}
689 	}
690 
691 	/* Sets no_new_privs past the last point of failure. */
692 	if (flags & LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS)
693 		task_set_no_new_privs(current);
694 
695 	/* Whole process: thread-sync swept siblings, or single-threaded. */
696 	process_wide = (flags & LANDLOCK_RESTRICT_SELF_TSYNC) ||
697 		       get_nr_threads(current) == 1;
698 	commit_creds(new_cred);
699 
700 	/* The caller commits last, so its event concludes the operation. */
701 	if (ruleset)
702 		trace_landlock_enforce_domain(new_dom, true, process_wide,
703 					      task_no_new_privs(current));
704 
705 	return 0;
706 }
707