xref: /linux/security/landlock/domain.c (revision d3df7ed4683f8c1b35672a40bf20af6a08ef8ca9)
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 	if (WARN_ON_ONCE(!ruleset))
443 		return ERR_PTR(-EINVAL);
444 
445 	lockdep_assert_held(&ruleset->lock);
446 
447 	if (parent) {
448 		if (parent->num_layers >= LANDLOCK_MAX_NUM_LAYERS)
449 			return ERR_PTR(-E2BIG);
450 		num_layers = parent->num_layers + 1;
451 	} else {
452 		num_layers = 1;
453 	}
454 
455 	/* Creates a new domain... */
456 	new_dom = create_domain(num_layers);
457 	if (IS_ERR(new_dom))
458 		return new_dom;
459 
460 	new_dom->hierarchy =
461 		kzalloc_obj(*new_dom->hierarchy, GFP_KERNEL_ACCOUNT);
462 	if (!new_dom->hierarchy)
463 		return ERR_PTR(-ENOMEM);
464 
465 	refcount_set(&new_dom->hierarchy->usage, 1);
466 
467 	/* ...as a child of @parent... */
468 	err = inherit_ruleset(parent, new_dom);
469 	if (err)
470 		return ERR_PTR(err);
471 
472 	/* ...and including @ruleset. */
473 	err = merge_ruleset(new_dom, ruleset);
474 	if (err)
475 		return ERR_PTR(err);
476 
477 	err = landlock_init_hierarchy_log(new_dom->hierarchy);
478 	if (err)
479 		return ERR_PTR(err);
480 
481 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
482 	new_dom->hierarchy->quiet_masks = ruleset->quiet_masks;
483 #endif /* CONFIG_SECURITY_LANDLOCK_LOG */
484 
485 	return no_free_ptr(new_dom);
486 }
487 
488 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
489 
490 /**
491  * get_current_exe - Get the current's executable path, if any
492  *
493  * @exe_str: Returned pointer to a path string with a lifetime tied to the
494  *           returned buffer, if any.
495  * @exe_size: Returned size of @exe_str (including the trailing null
496  *            character), if any.
497  *
498  * Return: A pointer to an allocated buffer where @exe_str point to, %NULL if
499  * there is no executable path, or an error otherwise.
500  */
501 static const void *get_current_exe(const char **const exe_str,
502 				   size_t *const exe_size)
503 {
504 	const size_t buffer_size = LANDLOCK_PATH_MAX_SIZE;
505 	struct mm_struct *mm = current->mm;
506 	struct file *file __free(fput) = NULL;
507 	char *buffer __free(kfree) = NULL;
508 	const char *exe;
509 	ssize_t size;
510 
511 	if (!mm)
512 		return NULL;
513 
514 	file = get_mm_exe_file(mm);
515 	if (!file)
516 		return NULL;
517 
518 	buffer = kmalloc(buffer_size, GFP_KERNEL);
519 	if (!buffer)
520 		return ERR_PTR(-ENOMEM);
521 
522 	exe = d_path(&file->f_path, buffer, buffer_size);
523 	if (WARN_ON_ONCE(IS_ERR(exe)))
524 		/* Should never happen according to LANDLOCK_PATH_MAX_SIZE. */
525 		return ERR_CAST(exe);
526 
527 	size = buffer + buffer_size - exe;
528 	if (WARN_ON_ONCE(size <= 0))
529 		return ERR_PTR(-ENAMETOOLONG);
530 
531 	*exe_size = size;
532 	*exe_str = exe;
533 	return no_free_ptr(buffer);
534 }
535 
536 /*
537  * Return: A newly allocated object describing a domain, or an error
538  * otherwise.
539  */
540 static struct landlock_details *get_current_details(void)
541 {
542 	/* Cf. audit_log_d_path_exe() */
543 	static const char null_path[] = "(null)";
544 	const char *path_str = null_path;
545 	size_t path_size = sizeof(null_path);
546 	const void *buffer __free(kfree) = NULL;
547 	struct landlock_details *details;
548 
549 	buffer = get_current_exe(&path_str, &path_size);
550 	if (IS_ERR(buffer))
551 		return ERR_CAST(buffer);
552 
553 	/*
554 	 * Create the new details according to the path's length.  Account to
555 	 * the calling task's memcg, like the other Landlock per-domain
556 	 * allocations, even if it may not control the related size.
557 	 */
558 	details =
559 		kzalloc_flex(*details, exe_path, path_size, GFP_KERNEL_ACCOUNT);
560 	if (!details)
561 		return ERR_PTR(-ENOMEM);
562 
563 	memcpy(details->exe_path, path_str, path_size);
564 	details->pid = get_pid(task_tgid(current));
565 	details->uid = from_kuid(&init_user_ns, current_uid());
566 	get_task_comm(details->comm, current);
567 	return details;
568 }
569 
570 /**
571  * landlock_init_hierarchy_log - Partially initialize landlock_hierarchy
572  *
573  * @hierarchy: The hierarchy to initialize.
574  *
575  * The current task is referenced as the domain that is enforcing the
576  * restriction.  The subjective credentials must not be in an overridden state.
577  *
578  * @hierarchy->parent and @hierarchy->usage should already be set.
579  *
580  * Return: 0 on success, -errno on failure.
581  */
582 int landlock_init_hierarchy_log(struct landlock_hierarchy *const hierarchy)
583 {
584 	struct landlock_details *details;
585 
586 	details = get_current_details();
587 	if (IS_ERR(details))
588 		return PTR_ERR(details);
589 
590 	hierarchy->details = details;
591 	hierarchy->id = landlock_get_id_range(1);
592 	/*
593 	 * The hierarchy is born unobservable: landlock_restrict_self() moves it
594 	 * out of LANDLOCK_LOG_UNCOMMITTED once it has emitted the creation
595 	 * event, so the matching free_domain event fires for it and not for a
596 	 * hierarchy whose creation was never observed.
597 	 */
598 	hierarchy->log_status = LANDLOCK_LOG_UNCOMMITTED;
599 	hierarchy->log_same_exec = true;
600 	hierarchy->log_new_exec = false;
601 	atomic64_set(&hierarchy->num_denials, 0);
602 	return 0;
603 }
604 
605 static deny_masks_t
606 get_layer_deny_mask(const access_mask_t all_existing_optional_access,
607 		    const unsigned long access_bit, const size_t layer)
608 {
609 	unsigned long access_weight;
610 
611 	/* This may require change with new object types. */
612 	WARN_ON_ONCE(all_existing_optional_access !=
613 		     _LANDLOCK_ACCESS_FS_OPTIONAL);
614 
615 	if (WARN_ON_ONCE(layer >= LANDLOCK_MAX_NUM_LAYERS))
616 		return 0;
617 
618 	access_weight = hweight_long(all_existing_optional_access &
619 				     GENMASK(access_bit, 0));
620 	if (WARN_ON_ONCE(access_weight < 1))
621 		return 0;
622 
623 	return layer
624 	       << ((access_weight - 1) * HWEIGHT(LANDLOCK_MAX_NUM_LAYERS - 1));
625 }
626 
627 /**
628  * landlock_get_quiet_optional_accesses - Get optional accesses which are
629  *                                        covered by quiet rule flags.
630  *
631  * @all_existing_optional_access: Bitmask of valid optional accesses.
632  * @deny_masks: Domain layer levels that denied each optional access (the
633  *              deny_masks field on struct landlock_file_security).
634  * @masks: The struct layer_masks collected during the path walk.
635  *
636  * Return: a bitmask of which optional accesses are denied by layers for which
637  * the quiet flag was collected during the path walk.
638  */
639 optional_access_t landlock_get_quiet_optional_accesses(
640 	const access_mask_t all_existing_optional_access,
641 	const deny_masks_t deny_masks, const struct layer_masks *const masks)
642 {
643 	const unsigned long access_opt = all_existing_optional_access;
644 	size_t access_index = 0;
645 	unsigned long access_bit;
646 	optional_access_t quiet_optional_accesses = 0;
647 
648 	/* This will require change with new object types. */
649 	WARN_ON_ONCE(access_opt != _LANDLOCK_ACCESS_FS_OPTIONAL);
650 
651 	for_each_set_bit(access_bit, &access_opt,
652 			 BITS_PER_TYPE(access_mask_t)) {
653 		const u8 layer =
654 			(deny_masks >> (access_index *
655 					HWEIGHT(LANDLOCK_MAX_NUM_LAYERS - 1))) &
656 			(LANDLOCK_MAX_NUM_LAYERS - 1);
657 
658 		if (masks->layers[layer].quiet)
659 			quiet_optional_accesses |= BIT(access_index);
660 		access_index++;
661 	}
662 	return quiet_optional_accesses;
663 }
664 
665 #ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST
666 
667 static void test_get_layer_deny_mask(struct kunit *const test)
668 {
669 	const unsigned long truncate = BIT_INDEX(LANDLOCK_ACCESS_FS_TRUNCATE);
670 	const unsigned long ioctl_dev = BIT_INDEX(LANDLOCK_ACCESS_FS_IOCTL_DEV);
671 
672 	KUNIT_EXPECT_EQ(test, 0,
673 			get_layer_deny_mask(_LANDLOCK_ACCESS_FS_OPTIONAL,
674 					    truncate, 0));
675 	KUNIT_EXPECT_EQ(test, 0x3,
676 			get_layer_deny_mask(_LANDLOCK_ACCESS_FS_OPTIONAL,
677 					    truncate, 3));
678 
679 	KUNIT_EXPECT_EQ(test, 0,
680 			get_layer_deny_mask(_LANDLOCK_ACCESS_FS_OPTIONAL,
681 					    ioctl_dev, 0));
682 	KUNIT_EXPECT_EQ(test, 0xf0,
683 			get_layer_deny_mask(_LANDLOCK_ACCESS_FS_OPTIONAL,
684 					    ioctl_dev, 15));
685 }
686 
687 #endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
688 
689 deny_masks_t
690 landlock_get_deny_masks(const access_mask_t all_existing_optional_access,
691 			const access_mask_t optional_access,
692 			const struct layer_masks *const masks)
693 {
694 	const unsigned long access_opt = optional_access;
695 	unsigned long access_bit;
696 	deny_masks_t deny_masks = 0;
697 	access_mask_t all_denied = 0;
698 
699 	/* This may require change with new object types. */
700 	WARN_ON_ONCE(!access_mask_subset(optional_access,
701 					 all_existing_optional_access));
702 
703 	if (WARN_ON_ONCE(!masks))
704 		return 0;
705 
706 	if (WARN_ON_ONCE(!access_opt))
707 		return 0;
708 
709 	for (ssize_t i = ARRAY_SIZE(masks->layers) - 1; i >= 0; i--) {
710 		const access_mask_t denied = masks->layers[i].access &
711 					     optional_access;
712 		const unsigned long newly_denied = denied & ~all_denied;
713 
714 		if (!newly_denied)
715 			continue;
716 
717 		for_each_set_bit(access_bit, &newly_denied,
718 				 8 * sizeof(access_mask_t)) {
719 			deny_masks |= get_layer_deny_mask(
720 				all_existing_optional_access, access_bit, i);
721 		}
722 		all_denied |= denied;
723 	}
724 	return deny_masks;
725 }
726 
727 #ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST
728 
729 static void test_landlock_get_deny_masks(struct kunit *const test)
730 {
731 	const struct layer_masks layers1 = {
732 		.layers[0].access = LANDLOCK_ACCESS_FS_EXECUTE |
733 				    LANDLOCK_ACCESS_FS_IOCTL_DEV,
734 		.layers[1].access = LANDLOCK_ACCESS_FS_TRUNCATE,
735 		.layers[2].access = LANDLOCK_ACCESS_FS_IOCTL_DEV,
736 		.layers[9].access = LANDLOCK_ACCESS_FS_EXECUTE,
737 	};
738 
739 	KUNIT_EXPECT_EQ(test, 0x1,
740 			landlock_get_deny_masks(_LANDLOCK_ACCESS_FS_OPTIONAL,
741 						LANDLOCK_ACCESS_FS_TRUNCATE,
742 						&layers1));
743 	KUNIT_EXPECT_EQ(test, 0x20,
744 			landlock_get_deny_masks(_LANDLOCK_ACCESS_FS_OPTIONAL,
745 						LANDLOCK_ACCESS_FS_IOCTL_DEV,
746 						&layers1));
747 	KUNIT_EXPECT_EQ(
748 		test, 0x21,
749 		landlock_get_deny_masks(_LANDLOCK_ACCESS_FS_OPTIONAL,
750 					LANDLOCK_ACCESS_FS_TRUNCATE |
751 						LANDLOCK_ACCESS_FS_IOCTL_DEV,
752 					&layers1));
753 }
754 
755 #endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
756 
757 #ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST
758 
759 static struct kunit_case test_cases[] = {
760 	/* clang-format off */
761 	KUNIT_CASE(test_get_layer_deny_mask),
762 	KUNIT_CASE(test_landlock_get_deny_masks),
763 	{}
764 	/* clang-format on */
765 };
766 
767 static struct kunit_suite test_suite = {
768 	.name = "landlock_domain",
769 	.test_cases = test_cases,
770 };
771 
772 kunit_test_suite(test_suite);
773 
774 #endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
775 
776 #endif /* CONFIG_SECURITY_LANDLOCK_LOG */
777