xref: /linux/security/landlock/domain.c (revision 7199989f3f3194d653b024ce8e79cea6b15e38b9)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Landlock - Domain management
4  *
5  * Copyright © 2016-2020 Mickaël Salaün <mic@digikod.net>
6  * Copyright © 2018-2020 ANSSI
7  * Copyright © 2024-2025 Microsoft Corporation
8  * Copyright © 2026 Cloudflare, Inc.
9  */
10 
11 #include <kunit/test.h>
12 #include <linux/bitops.h>
13 #include <linux/bits.h>
14 #include <linux/cleanup.h>
15 #include <linux/cred.h>
16 #include <linux/err.h>
17 #include <linux/file.h>
18 #include <linux/lockdep.h>
19 #include <linux/mm.h>
20 #include <linux/mutex.h>
21 #include <linux/overflow.h>
22 #include <linux/path.h>
23 #include <linux/pid.h>
24 #include <linux/rbtree.h>
25 #include <linux/refcount.h>
26 #include <linux/sched.h>
27 #include <linux/signal.h>
28 #include <linux/slab.h>
29 #include <linux/uidgid.h>
30 #include <linux/workqueue.h>
31 
32 #include "access.h"
33 #include "common.h"
34 #include "domain.h"
35 #include "id.h"
36 #include "limits.h"
37 #include "ruleset.h"
38 
39 static void build_check_domain(void)
40 {
41 	const struct landlock_domain domain = {
42 		.num_layers = ~0,
43 	};
44 
45 	BUILD_BUG_ON(domain.num_layers < LANDLOCK_MAX_NUM_LAYERS);
46 }
47 
48 static struct landlock_domain *create_domain(const u32 num_layers)
49 {
50 	struct landlock_domain *new_domain;
51 
52 	build_check_domain();
53 	new_domain = kzalloc_flex(*new_domain, handled_masks, num_layers,
54 				  GFP_KERNEL_ACCOUNT);
55 	if (!new_domain)
56 		return ERR_PTR(-ENOMEM);
57 
58 	refcount_set(&new_domain->usage, 1);
59 	new_domain->rules.root_inode = RB_ROOT;
60 
61 #if IS_ENABLED(CONFIG_INET)
62 	new_domain->rules.root_net_port = RB_ROOT;
63 #endif /* IS_ENABLED(CONFIG_INET) */
64 
65 	new_domain->num_layers = num_layers;
66 	return new_domain;
67 }
68 
69 static void free_domain(struct landlock_domain *const domain)
70 {
71 	might_sleep();
72 	landlock_free_rules(&domain->rules);
73 	landlock_put_hierarchy(domain->hierarchy);
74 	kfree(domain);
75 }
76 
77 void landlock_put_domain(struct landlock_domain *const domain)
78 {
79 	might_sleep();
80 	if (domain && refcount_dec_and_test(&domain->usage))
81 		free_domain(domain);
82 }
83 
84 static void free_domain_work(struct work_struct *const work)
85 {
86 	struct landlock_domain *domain;
87 
88 	domain = container_of(work, struct landlock_domain, work_free);
89 	free_domain(domain);
90 }
91 
92 void landlock_put_domain_deferred(struct landlock_domain *const domain)
93 {
94 	if (domain && refcount_dec_and_test(&domain->usage)) {
95 		INIT_WORK(&domain->work_free, free_domain_work);
96 		schedule_work(&domain->work_free);
97 	}
98 }
99 
100 /* The returned access has the same lifetime as the domain. */
101 static const struct landlock_rule *
102 find_rule(const struct landlock_domain *const domain,
103 	  const struct landlock_id id)
104 {
105 	const struct rb_root *root;
106 	const struct rb_node *node;
107 
108 	root = landlock_get_rule_root((struct landlock_rules *)&domain->rules,
109 				      id.type);
110 	if (IS_ERR(root))
111 		return NULL;
112 	node = root->rb_node;
113 
114 	while (node) {
115 		struct landlock_rule *this =
116 			rb_entry(node, struct landlock_rule, node);
117 
118 		if (this->key.data == id.key.data)
119 			return this;
120 		if (this->key.data < id.key.data)
121 			node = node->rb_right;
122 		else
123 			node = node->rb_left;
124 	}
125 	return NULL;
126 }
127 
128 /**
129  * landlock_unmask_layers - Remove the access rights in @masks which are
130  *                          granted by a matching rule
131  *
132  * Looks up the rule matching @id in @domain, then updates the set of
133  * (per-layer) unfulfilled access rights @masks so that all the access rights
134  * granted by that rule are removed (because they are now fulfilled).
135  *
136  * @domain: The Landlock domain to search for a matching rule.
137  * @id: Identifier for the rule target (e.g. inode, port).
138  * @masks: A matrix of unfulfilled access rights for each layer.
139  * @matched_rule: Optional output for the matched rule (for tracing); set to
140  *                the matching rule when non-NULL, unchanged otherwise.
141  *
142  * Return: True if the request is allowed (i.e. the access rights granted all
143  * remaining unfulfilled access rights and masks has no leftover set bits).
144  */
145 bool landlock_unmask_layers(const struct landlock_domain *const domain,
146 			    const struct landlock_id id,
147 			    struct layer_masks *masks,
148 			    const struct landlock_rule **matched_rule)
149 {
150 	const struct landlock_rule *rule;
151 
152 	if (!masks)
153 		return true;
154 
155 	rule = find_rule(domain, id);
156 	if (!rule)
157 		return false;
158 
159 	if (matched_rule)
160 		*matched_rule = rule;
161 
162 	/*
163 	 * An access is granted if, for each policy layer, at least one rule
164 	 * encountered on the pathwalk grants the requested access, regardless
165 	 * of its position in the layer stack.  We must then check the remaining
166 	 * layers for each inode, from the first added layer to the last one.
167 	 * When there are multiple requested accesses, for each policy layer,
168 	 * the full set of requested accesses may not be granted by only one
169 	 * rule, but by the union (binary OR) of multiple rules.  For example,
170 	 * /a/b <execute> + /a <read> grants /a/b <execute + read>.
171 	 *
172 	 * This function is called once per matching rule during the pathwalk,
173 	 * progressively clearing bits in @masks.  The overall access decision
174 	 * is per-layer: access is granted iff masks->layers[l].access == 0 for
175 	 * all layers l.  When two independent mechanisms can each grant access
176 	 * within a layer (e.g. a path rule OR a scope exception), the
177 	 * composition must evaluate per-layer: FOR-ALL l (A(l) OR B(l)), not
178 	 * (FOR-ALL l A(l)) OR (FOR-ALL l B(l)), to prevent bypass when
179 	 * different layers grant via different mechanisms.
180 	 */
181 	for (size_t i = 0; i < rule->num_layers; i++) {
182 		const struct landlock_layer *const layer = &rule->layers[i];
183 
184 		/* Clear the bits where the layer in the rule grants access. */
185 		masks->layers[layer->level - 1].access &= ~layer->access;
186 
187 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
188 		/* Collect rule flags for each layer. */
189 		if (layer->flags.quiet)
190 			masks->layers[layer->level - 1].quiet = true;
191 #endif /* CONFIG_SECURITY_LANDLOCK_LOG */
192 	}
193 
194 	for (size_t i = 0; i < ARRAY_SIZE(masks->layers); i++) {
195 		if (masks->layers[i].access)
196 			return false;
197 	}
198 	return true;
199 }
200 
201 typedef access_mask_t
202 get_access_mask_t(const struct landlock_domain *const domain,
203 		  const u16 layer_level);
204 
205 /**
206  * landlock_init_layer_masks - Initialize layer masks from an access request
207  *
208  * Populates @masks such that for each access right in @access_request, the bits
209  * for all the layers are set where this access right is handled.  Rule flags
210  * are also zeroed.
211  *
212  * @domain: The domain that defines the current restrictions.
213  * @access_request: The requested access rights to check.
214  * @masks: Layer access masks to populate.
215  * @key_type: The key type to switch between access masks of different types.
216  *
217  * Return: An access mask where each access right bit is set which is handled in
218  * any of the active layers in @domain.
219  */
220 access_mask_t
221 landlock_init_layer_masks(const struct landlock_domain *const domain,
222 			  const access_mask_t access_request,
223 			  struct layer_masks *const masks,
224 			  const enum landlock_key_type key_type)
225 {
226 	access_mask_t handled_accesses = 0;
227 	get_access_mask_t *get_access_mask;
228 
229 	switch (key_type) {
230 	case LANDLOCK_KEY_INODE:
231 		get_access_mask = landlock_get_fs_access_mask;
232 		break;
233 
234 #if IS_ENABLED(CONFIG_INET)
235 	case LANDLOCK_KEY_NET_PORT:
236 		get_access_mask = landlock_get_net_access_mask;
237 		break;
238 #endif /* IS_ENABLED(CONFIG_INET) */
239 
240 	default:
241 		WARN_ON_ONCE(1);
242 		return 0;
243 	}
244 
245 	/* An empty access request can happen because of O_WRONLY | O_RDWR. */
246 	if (!access_request)
247 		return 0;
248 
249 	for (size_t i = 0; i < domain->num_layers; i++) {
250 		const access_mask_t handled = get_access_mask(domain, i);
251 
252 		masks->layers[i].access = access_request & handled;
253 		handled_accesses |= masks->layers[i].access;
254 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
255 		masks->layers[i].quiet = false;
256 #endif /* CONFIG_SECURITY_LANDLOCK_LOG */
257 	}
258 	for (size_t i = domain->num_layers; i < ARRAY_SIZE(masks->layers);
259 	     i++) {
260 		masks->layers[i].access = 0;
261 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
262 		masks->layers[i].quiet = false;
263 #endif /* CONFIG_SECURITY_LANDLOCK_LOG */
264 	}
265 
266 	return handled_accesses;
267 }
268 
269 static int merge_tree(struct landlock_domain *const dst,
270 		      struct landlock_ruleset *const src,
271 		      const enum landlock_key_type key_type)
272 {
273 	struct landlock_rule *walker_rule, *next_rule;
274 	struct rb_root *src_root;
275 	int err = 0;
276 
277 	might_sleep();
278 	lockdep_assert_held(&src->lock);
279 
280 	src_root = landlock_get_rule_root(&src->rules, key_type);
281 	if (IS_ERR(src_root))
282 		return PTR_ERR(src_root);
283 
284 	/* Merges the @src tree. */
285 	rbtree_postorder_for_each_entry_safe(walker_rule, next_rule, src_root,
286 					     node) {
287 		struct landlock_layer layers[] = { {
288 			.level = dst->num_layers,
289 		} };
290 		const struct landlock_id id = {
291 			.key = walker_rule->key,
292 			.type = key_type,
293 		};
294 
295 		if (WARN_ON_ONCE(walker_rule->num_layers != 1))
296 			return -EINVAL;
297 
298 		if (WARN_ON_ONCE(walker_rule->layers[0].level != 0))
299 			return -EINVAL;
300 
301 		layers[0].access = walker_rule->layers[0].access;
302 		layers[0].flags = walker_rule->layers[0].flags;
303 
304 		err = landlock_store_rule(&dst->rules, id, &layers,
305 					  ARRAY_SIZE(layers));
306 		if (err)
307 			return err;
308 	}
309 	return err;
310 }
311 
312 static int merge_ruleset(struct landlock_domain *const dst,
313 			 struct landlock_ruleset *const src)
314 {
315 	int err = 0;
316 
317 	might_sleep();
318 	/* Should already be checked by landlock_merge_ruleset() */
319 	if (WARN_ON_ONCE(!src))
320 		return 0;
321 	/* Only merge into a domain. */
322 	if (WARN_ON_ONCE(!dst || !dst->hierarchy))
323 		return -EINVAL;
324 
325 	lockdep_assert_held(&src->lock);
326 
327 	/* Stacks the new layer. */
328 	if (WARN_ON_ONCE(dst->num_layers < 1))
329 		return -EINVAL;
330 
331 	dst->handled_masks[dst->num_layers - 1] =
332 		landlock_upgrade_handled_access_masks(src->handled_masks);
333 
334 	/* Merges the @src inode tree. */
335 	err = merge_tree(dst, src, LANDLOCK_KEY_INODE);
336 	if (err)
337 		return err;
338 
339 #if IS_ENABLED(CONFIG_INET)
340 	/* Merges the @src network port tree. */
341 	err = merge_tree(dst, src, LANDLOCK_KEY_NET_PORT);
342 	if (err)
343 		return err;
344 #endif /* IS_ENABLED(CONFIG_INET) */
345 
346 	return 0;
347 }
348 
349 static int inherit_tree(struct landlock_domain *const parent,
350 			struct landlock_domain *const child,
351 			const enum landlock_key_type key_type)
352 {
353 	struct landlock_rule *walker_rule, *next_rule;
354 	struct rb_root *parent_root;
355 	int err = 0;
356 
357 	might_sleep();
358 
359 	parent_root = landlock_get_rule_root(&parent->rules, key_type);
360 	if (IS_ERR(parent_root))
361 		return PTR_ERR(parent_root);
362 
363 	/* Copies the @parent inode or network tree. */
364 	rbtree_postorder_for_each_entry_safe(walker_rule, next_rule,
365 					     parent_root, node) {
366 		const struct landlock_id id = {
367 			.key = walker_rule->key,
368 			.type = key_type,
369 		};
370 
371 		err = landlock_store_rule(&child->rules, id,
372 					  &walker_rule->layers,
373 					  walker_rule->num_layers);
374 		if (err)
375 			return err;
376 	}
377 	return err;
378 }
379 
380 static int inherit_ruleset(struct landlock_domain *const parent,
381 			   struct landlock_domain *const child)
382 {
383 	int err = 0;
384 
385 	might_sleep();
386 	if (!parent)
387 		return 0;
388 
389 	/* Copies the @parent inode tree. */
390 	err = inherit_tree(parent, child, LANDLOCK_KEY_INODE);
391 	if (err)
392 		return err;
393 
394 #if IS_ENABLED(CONFIG_INET)
395 	/* Copies the @parent network port tree. */
396 	err = inherit_tree(parent, child, LANDLOCK_KEY_NET_PORT);
397 	if (err)
398 		return err;
399 #endif /* IS_ENABLED(CONFIG_INET) */
400 
401 	if (WARN_ON_ONCE(child->num_layers <= parent->num_layers))
402 		return -EINVAL;
403 
404 	/*
405 	 * Copies the parent layer stack and leaves a space for the new layer.
406 	 */
407 	memcpy(child->handled_masks, parent->handled_masks,
408 	       flex_array_size(parent, handled_masks, parent->num_layers));
409 
410 	if (WARN_ON_ONCE(!parent->hierarchy))
411 		return -EINVAL;
412 
413 	landlock_get_hierarchy(parent->hierarchy);
414 	child->hierarchy->parent = parent->hierarchy;
415 
416 	return 0;
417 }
418 
419 /**
420  * landlock_merge_ruleset - Merge a ruleset with a domain
421  *
422  * @parent: Parent domain.
423  * @ruleset: New ruleset to be merged.
424  *
425  * The current task is requesting to be restricted.  The subjective credentials
426  * must not be in an overridden state. cf. landlock_init_hierarchy_log().
427  *
428  * The caller must hold @ruleset->lock.
429  *
430  * Return: A new domain merging @parent and @ruleset on success, or ERR_PTR() on
431  * failure.  If @parent is NULL, the new domain duplicates @ruleset.
432  */
433 struct landlock_domain *
434 landlock_merge_ruleset(struct landlock_domain *const parent,
435 		       struct landlock_ruleset *const ruleset)
436 {
437 	struct landlock_domain *new_dom __free(landlock_put_domain) = NULL;
438 	u32 num_layers;
439 	int err;
440 
441 	might_sleep();
442 	lockdep_assert_held(&ruleset->lock);
443 	if (WARN_ON_ONCE(!ruleset))
444 		return ERR_PTR(-EINVAL);
445 
446 	if (parent) {
447 		if (parent->num_layers >= LANDLOCK_MAX_NUM_LAYERS)
448 			return ERR_PTR(-E2BIG);
449 		num_layers = parent->num_layers + 1;
450 	} else {
451 		num_layers = 1;
452 	}
453 
454 	/* Creates a new domain... */
455 	new_dom = create_domain(num_layers);
456 	if (IS_ERR(new_dom))
457 		return new_dom;
458 
459 	new_dom->hierarchy =
460 		kzalloc_obj(*new_dom->hierarchy, GFP_KERNEL_ACCOUNT);
461 	if (!new_dom->hierarchy)
462 		return ERR_PTR(-ENOMEM);
463 
464 	refcount_set(&new_dom->hierarchy->usage, 1);
465 
466 	/* ...as a child of @parent... */
467 	err = inherit_ruleset(parent, new_dom);
468 	if (err)
469 		return ERR_PTR(err);
470 
471 	/* ...and including @ruleset. */
472 	err = merge_ruleset(new_dom, ruleset);
473 	if (err)
474 		return ERR_PTR(err);
475 
476 	err = landlock_init_hierarchy_log(new_dom->hierarchy);
477 	if (err)
478 		return ERR_PTR(err);
479 
480 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
481 	new_dom->hierarchy->quiet_masks = ruleset->quiet_masks;
482 #endif /* CONFIG_SECURITY_LANDLOCK_LOG */
483 
484 	return no_free_ptr(new_dom);
485 }
486 
487 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
488 
489 /**
490  * get_current_exe - Get the current's executable path, if any
491  *
492  * @exe_str: Returned pointer to a path string with a lifetime tied to the
493  *           returned buffer, if any.
494  * @exe_size: Returned size of @exe_str (including the trailing null
495  *            character), if any.
496  *
497  * Return: A pointer to an allocated buffer where @exe_str point to, %NULL if
498  * there is no executable path, or an error otherwise.
499  */
500 static const void *get_current_exe(const char **const exe_str,
501 				   size_t *const exe_size)
502 {
503 	const size_t buffer_size = LANDLOCK_PATH_MAX_SIZE;
504 	struct mm_struct *mm = current->mm;
505 	struct file *file __free(fput) = NULL;
506 	char *buffer __free(kfree) = NULL;
507 	const char *exe;
508 	ssize_t size;
509 
510 	if (!mm)
511 		return NULL;
512 
513 	file = get_mm_exe_file(mm);
514 	if (!file)
515 		return NULL;
516 
517 	buffer = kmalloc(buffer_size, GFP_KERNEL);
518 	if (!buffer)
519 		return ERR_PTR(-ENOMEM);
520 
521 	exe = d_path(&file->f_path, buffer, buffer_size);
522 	if (WARN_ON_ONCE(IS_ERR(exe)))
523 		/* Should never happen according to LANDLOCK_PATH_MAX_SIZE. */
524 		return ERR_CAST(exe);
525 
526 	size = buffer + buffer_size - exe;
527 	if (WARN_ON_ONCE(size <= 0))
528 		return ERR_PTR(-ENAMETOOLONG);
529 
530 	*exe_size = size;
531 	*exe_str = exe;
532 	return no_free_ptr(buffer);
533 }
534 
535 /*
536  * Return: A newly allocated object describing a domain, or an error
537  * otherwise.
538  */
539 static struct landlock_details *get_current_details(void)
540 {
541 	/* Cf. audit_log_d_path_exe() */
542 	static const char null_path[] = "(null)";
543 	const char *path_str = null_path;
544 	size_t path_size = sizeof(null_path);
545 	const void *buffer __free(kfree) = NULL;
546 	struct landlock_details *details;
547 
548 	buffer = get_current_exe(&path_str, &path_size);
549 	if (IS_ERR(buffer))
550 		return ERR_CAST(buffer);
551 
552 	/*
553 	 * Create the new details according to the path's length.  Account to
554 	 * the calling task's memcg, like the other Landlock per-domain
555 	 * allocations, even if it may not control the related size.
556 	 */
557 	details =
558 		kzalloc_flex(*details, exe_path, path_size, GFP_KERNEL_ACCOUNT);
559 	if (!details)
560 		return ERR_PTR(-ENOMEM);
561 
562 	memcpy(details->exe_path, path_str, path_size);
563 	details->pid = get_pid(task_tgid(current));
564 	details->uid = from_kuid(&init_user_ns, current_uid());
565 	get_task_comm(details->comm, current);
566 	return details;
567 }
568 
569 /**
570  * landlock_init_hierarchy_log - Partially initialize landlock_hierarchy
571  *
572  * @hierarchy: The hierarchy to initialize.
573  *
574  * The current task is referenced as the domain that is enforcing the
575  * restriction.  The subjective credentials must not be in an overridden state.
576  *
577  * @hierarchy->parent and @hierarchy->usage should already be set.
578  *
579  * Return: 0 on success, -errno on failure.
580  */
581 int landlock_init_hierarchy_log(struct landlock_hierarchy *const hierarchy)
582 {
583 	struct landlock_details *details;
584 
585 	details = get_current_details();
586 	if (IS_ERR(details))
587 		return PTR_ERR(details);
588 
589 	hierarchy->details = details;
590 	hierarchy->id = landlock_get_id_range(1);
591 	/*
592 	 * The hierarchy is born unobservable: landlock_restrict_self() moves it
593 	 * out of LANDLOCK_LOG_UNCOMMITTED once it has emitted the creation
594 	 * event, so the matching free_domain event fires for it and not for a
595 	 * hierarchy whose creation was never observed.
596 	 */
597 	hierarchy->log_status = LANDLOCK_LOG_UNCOMMITTED;
598 	hierarchy->log_same_exec = true;
599 	hierarchy->log_new_exec = false;
600 	atomic64_set(&hierarchy->num_denials, 0);
601 	return 0;
602 }
603 
604 static deny_masks_t
605 get_layer_deny_mask(const access_mask_t all_existing_optional_access,
606 		    const unsigned long access_bit, const size_t layer)
607 {
608 	unsigned long access_weight;
609 
610 	/* This may require change with new object types. */
611 	WARN_ON_ONCE(all_existing_optional_access !=
612 		     _LANDLOCK_ACCESS_FS_OPTIONAL);
613 
614 	if (WARN_ON_ONCE(layer >= LANDLOCK_MAX_NUM_LAYERS))
615 		return 0;
616 
617 	access_weight = hweight_long(all_existing_optional_access &
618 				     GENMASK(access_bit, 0));
619 	if (WARN_ON_ONCE(access_weight < 1))
620 		return 0;
621 
622 	return layer
623 	       << ((access_weight - 1) * HWEIGHT(LANDLOCK_MAX_NUM_LAYERS - 1));
624 }
625 
626 /**
627  * landlock_get_quiet_optional_accesses - Get optional accesses which are
628  *                                        covered by quiet rule flags.
629  *
630  * @all_existing_optional_access: Bitmask of valid optional accesses.
631  * @deny_masks: Domain layer levels that denied each optional access (the
632  *              deny_masks field on struct landlock_file_security).
633  * @masks: The struct layer_masks collected during the path walk.
634  *
635  * Return: a bitmask of which optional accesses are denied by layers for which
636  * the quiet flag was collected during the path walk.
637  */
638 optional_access_t landlock_get_quiet_optional_accesses(
639 	const access_mask_t all_existing_optional_access,
640 	const deny_masks_t deny_masks, const struct layer_masks *const masks)
641 {
642 	const unsigned long access_opt = all_existing_optional_access;
643 	size_t access_index = 0;
644 	unsigned long access_bit;
645 	optional_access_t quiet_optional_accesses = 0;
646 
647 	/* This will require change with new object types. */
648 	WARN_ON_ONCE(access_opt != _LANDLOCK_ACCESS_FS_OPTIONAL);
649 
650 	for_each_set_bit(access_bit, &access_opt,
651 			 BITS_PER_TYPE(access_mask_t)) {
652 		const u8 layer =
653 			(deny_masks >> (access_index *
654 					HWEIGHT(LANDLOCK_MAX_NUM_LAYERS - 1))) &
655 			(LANDLOCK_MAX_NUM_LAYERS - 1);
656 
657 		if (masks->layers[layer].quiet)
658 			quiet_optional_accesses |= BIT(access_index);
659 		access_index++;
660 	}
661 	return quiet_optional_accesses;
662 }
663 
664 #ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST
665 
666 static void test_get_layer_deny_mask(struct kunit *const test)
667 {
668 	const unsigned long truncate = BIT_INDEX(LANDLOCK_ACCESS_FS_TRUNCATE);
669 	const unsigned long ioctl_dev = BIT_INDEX(LANDLOCK_ACCESS_FS_IOCTL_DEV);
670 
671 	KUNIT_EXPECT_EQ(test, 0,
672 			get_layer_deny_mask(_LANDLOCK_ACCESS_FS_OPTIONAL,
673 					    truncate, 0));
674 	KUNIT_EXPECT_EQ(test, 0x3,
675 			get_layer_deny_mask(_LANDLOCK_ACCESS_FS_OPTIONAL,
676 					    truncate, 3));
677 
678 	KUNIT_EXPECT_EQ(test, 0,
679 			get_layer_deny_mask(_LANDLOCK_ACCESS_FS_OPTIONAL,
680 					    ioctl_dev, 0));
681 	KUNIT_EXPECT_EQ(test, 0xf0,
682 			get_layer_deny_mask(_LANDLOCK_ACCESS_FS_OPTIONAL,
683 					    ioctl_dev, 15));
684 }
685 
686 #endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
687 
688 deny_masks_t
689 landlock_get_deny_masks(const access_mask_t all_existing_optional_access,
690 			const access_mask_t optional_access,
691 			const struct layer_masks *const masks)
692 {
693 	const unsigned long access_opt = optional_access;
694 	unsigned long access_bit;
695 	deny_masks_t deny_masks = 0;
696 	access_mask_t all_denied = 0;
697 
698 	/* This may require change with new object types. */
699 	WARN_ON_ONCE(!access_mask_subset(optional_access,
700 					 all_existing_optional_access));
701 
702 	if (WARN_ON_ONCE(!masks))
703 		return 0;
704 
705 	if (WARN_ON_ONCE(!access_opt))
706 		return 0;
707 
708 	for (ssize_t i = ARRAY_SIZE(masks->layers) - 1; i >= 0; i--) {
709 		const access_mask_t denied = masks->layers[i].access &
710 					     optional_access;
711 		const unsigned long newly_denied = denied & ~all_denied;
712 
713 		if (!newly_denied)
714 			continue;
715 
716 		for_each_set_bit(access_bit, &newly_denied,
717 				 8 * sizeof(access_mask_t)) {
718 			deny_masks |= get_layer_deny_mask(
719 				all_existing_optional_access, access_bit, i);
720 		}
721 		all_denied |= denied;
722 	}
723 	return deny_masks;
724 }
725 
726 #ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST
727 
728 static void test_landlock_get_deny_masks(struct kunit *const test)
729 {
730 	const struct layer_masks layers1 = {
731 		.layers[0].access = LANDLOCK_ACCESS_FS_EXECUTE |
732 				    LANDLOCK_ACCESS_FS_IOCTL_DEV,
733 		.layers[1].access = LANDLOCK_ACCESS_FS_TRUNCATE,
734 		.layers[2].access = LANDLOCK_ACCESS_FS_IOCTL_DEV,
735 		.layers[9].access = LANDLOCK_ACCESS_FS_EXECUTE,
736 	};
737 
738 	KUNIT_EXPECT_EQ(test, 0x1,
739 			landlock_get_deny_masks(_LANDLOCK_ACCESS_FS_OPTIONAL,
740 						LANDLOCK_ACCESS_FS_TRUNCATE,
741 						&layers1));
742 	KUNIT_EXPECT_EQ(test, 0x20,
743 			landlock_get_deny_masks(_LANDLOCK_ACCESS_FS_OPTIONAL,
744 						LANDLOCK_ACCESS_FS_IOCTL_DEV,
745 						&layers1));
746 	KUNIT_EXPECT_EQ(
747 		test, 0x21,
748 		landlock_get_deny_masks(_LANDLOCK_ACCESS_FS_OPTIONAL,
749 					LANDLOCK_ACCESS_FS_TRUNCATE |
750 						LANDLOCK_ACCESS_FS_IOCTL_DEV,
751 					&layers1));
752 }
753 
754 #endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
755 
756 #ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST
757 
758 static struct kunit_case test_cases[] = {
759 	/* clang-format off */
760 	KUNIT_CASE(test_get_layer_deny_mask),
761 	KUNIT_CASE(test_landlock_get_deny_masks),
762 	{}
763 	/* clang-format on */
764 };
765 
766 static struct kunit_suite test_suite = {
767 	.name = "landlock_domain",
768 	.test_cases = test_cases,
769 };
770 
771 kunit_test_suite(test_suite);
772 
773 #endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
774 
775 #endif /* CONFIG_SECURITY_LANDLOCK_LOG */
776