xref: /linux/security/landlock/syscalls.c (revision 42fc7e6543f6d17d2cf9ed3e5021f103a3d11182)
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/security.h>
26 #include <linux/stddef.h>
27 #include <linux/syscalls.h>
28 #include <linux/types.h>
29 #include <linux/uaccess.h>
30 #include <uapi/linux/landlock.h>
31 
32 #include "cred.h"
33 #include "domain.h"
34 #include "fs.h"
35 #include "limits.h"
36 #include "net.h"
37 #include "ruleset.h"
38 #include "setup.h"
39 #include "tsync.h"
40 
41 static bool is_initialized(void)
42 {
43 	if (likely(landlock_initialized))
44 		return true;
45 
46 	pr_warn_once(
47 		"Disabled but requested by user space. "
48 		"You should enable Landlock at boot time: "
49 		"https://docs.kernel.org/userspace-api/landlock.html#boot-time-configuration\n");
50 	return false;
51 }
52 
53 /**
54  * copy_min_struct_from_user - Safe future-proof argument copying
55  *
56  * Extend copy_struct_from_user() to check for consistent user buffer.
57  *
58  * @dst: Kernel space pointer or NULL.
59  * @ksize: Actual size of the data pointed to by @dst.
60  * @ksize_min: Minimal required size to be copied.
61  * @src: User space pointer or NULL.
62  * @usize: (Alleged) size of the data pointed to by @src.
63  */
64 static __always_inline int
65 copy_min_struct_from_user(void *const dst, const size_t ksize,
66 			  const size_t ksize_min, const void __user *const src,
67 			  const size_t usize)
68 {
69 	/* Checks buffer inconsistencies. */
70 	BUILD_BUG_ON(!dst);
71 	if (!src)
72 		return -EFAULT;
73 
74 	/* Checks size ranges. */
75 	BUILD_BUG_ON(ksize <= 0);
76 	BUILD_BUG_ON(ksize < ksize_min);
77 	if (usize < ksize_min)
78 		return -EINVAL;
79 	if (usize > PAGE_SIZE)
80 		return -E2BIG;
81 
82 	/* Copies user buffer and fills with zeros. */
83 	return copy_struct_from_user(dst, ksize, src, usize);
84 }
85 
86 /*
87  * This function only contains arithmetic operations with constants, leading to
88  * BUILD_BUG_ON().  The related code is evaluated and checked at build time,
89  * but it is then ignored thanks to compiler optimizations.
90  */
91 static void build_check_abi(void)
92 {
93 	struct landlock_ruleset_attr ruleset_attr;
94 	struct landlock_path_beneath_attr path_beneath_attr;
95 	struct landlock_net_port_attr net_port_attr;
96 	size_t ruleset_size, path_beneath_size, net_port_size;
97 
98 	/*
99 	 * For each user space ABI structures, first checks that there is no
100 	 * hole in them, then checks that all architectures have the same
101 	 * struct size.
102 	 */
103 	ruleset_size = sizeof(ruleset_attr.handled_access_fs);
104 	ruleset_size += sizeof(ruleset_attr.handled_access_net);
105 	ruleset_size += sizeof(ruleset_attr.scoped);
106 	BUILD_BUG_ON(sizeof(ruleset_attr) != ruleset_size);
107 	BUILD_BUG_ON(sizeof(ruleset_attr) != 24);
108 
109 	path_beneath_size = sizeof(path_beneath_attr.allowed_access);
110 	path_beneath_size += sizeof(path_beneath_attr.parent_fd);
111 	BUILD_BUG_ON(sizeof(path_beneath_attr) != path_beneath_size);
112 	BUILD_BUG_ON(sizeof(path_beneath_attr) != 12);
113 
114 	net_port_size = sizeof(net_port_attr.allowed_access);
115 	net_port_size += sizeof(net_port_attr.port);
116 	BUILD_BUG_ON(sizeof(net_port_attr) != net_port_size);
117 	BUILD_BUG_ON(sizeof(net_port_attr) != 16);
118 }
119 
120 /* Ruleset handling */
121 
122 static int fop_ruleset_release(struct inode *const inode,
123 			       struct file *const filp)
124 {
125 	struct landlock_ruleset *ruleset = filp->private_data;
126 
127 	landlock_put_ruleset(ruleset);
128 	return 0;
129 }
130 
131 static ssize_t fop_dummy_read(struct file *const filp, char __user *const buf,
132 			      const size_t size, loff_t *const ppos)
133 {
134 	/* Dummy handler to enable FMODE_CAN_READ. */
135 	return -EINVAL;
136 }
137 
138 static ssize_t fop_dummy_write(struct file *const filp,
139 			       const char __user *const buf, const size_t size,
140 			       loff_t *const ppos)
141 {
142 	/* Dummy handler to enable FMODE_CAN_WRITE. */
143 	return -EINVAL;
144 }
145 
146 /*
147  * A ruleset file descriptor enables to build a ruleset by adding (i.e.
148  * writing) rule after rule, without relying on the task's context.  This
149  * reentrant design is also used in a read way to enforce the ruleset on the
150  * current task.
151  */
152 static const struct file_operations ruleset_fops = {
153 	.release = fop_ruleset_release,
154 	.read = fop_dummy_read,
155 	.write = fop_dummy_write,
156 };
157 
158 /*
159  * The Landlock ABI version should be incremented for each new Landlock-related
160  * user space visible change (e.g. Landlock syscalls).  This version should
161  * only be incremented once per Linux release, and the date in
162  * Documentation/userspace-api/landlock.rst should be updated to reflect the
163  * UAPI change.
164  */
165 const int landlock_abi_version = 8;
166 
167 /**
168  * sys_landlock_create_ruleset - Create a new ruleset
169  *
170  * @attr: Pointer to a &struct landlock_ruleset_attr identifying the scope of
171  *        the new ruleset.
172  * @size: Size of the pointed &struct landlock_ruleset_attr (needed for
173  *        backward and forward compatibility).
174  * @flags: Supported values:
175  *
176  *         - %LANDLOCK_CREATE_RULESET_VERSION
177  *         - %LANDLOCK_CREATE_RULESET_ERRATA
178  *
179  * This system call enables to create a new Landlock ruleset, and returns the
180  * related file descriptor on success.
181  *
182  * If %LANDLOCK_CREATE_RULESET_VERSION or %LANDLOCK_CREATE_RULESET_ERRATA is
183  * set, then @attr must be NULL and @size must be 0.
184  *
185  * Possible returned errors are:
186  *
187  * - %EOPNOTSUPP: Landlock is supported by the kernel but disabled at boot time;
188  * - %EINVAL: unknown @flags, or unknown access, or unknown scope, or too small @size;
189  * - %E2BIG: @attr or @size inconsistencies;
190  * - %EFAULT: @attr or @size inconsistencies;
191  * - %ENOMSG: empty &landlock_ruleset_attr.handled_access_fs.
192  *
193  * .. kernel-doc:: include/uapi/linux/landlock.h
194  *     :identifiers: landlock_create_ruleset_flags
195  */
196 SYSCALL_DEFINE3(landlock_create_ruleset,
197 		const struct landlock_ruleset_attr __user *const, attr,
198 		const size_t, size, const __u32, flags)
199 {
200 	struct landlock_ruleset_attr ruleset_attr;
201 	struct landlock_ruleset *ruleset;
202 	int err, ruleset_fd;
203 
204 	/* Build-time checks. */
205 	build_check_abi();
206 
207 	if (!is_initialized())
208 		return -EOPNOTSUPP;
209 
210 	if (flags) {
211 		if (attr || size)
212 			return -EINVAL;
213 
214 		if (flags == LANDLOCK_CREATE_RULESET_VERSION)
215 			return landlock_abi_version;
216 
217 		if (flags == LANDLOCK_CREATE_RULESET_ERRATA)
218 			return landlock_errata;
219 
220 		return -EINVAL;
221 	}
222 
223 	/* Copies raw user space buffer. */
224 	err = copy_min_struct_from_user(&ruleset_attr, sizeof(ruleset_attr),
225 					offsetofend(typeof(ruleset_attr),
226 						    handled_access_fs),
227 					attr, size);
228 	if (err)
229 		return err;
230 
231 	/* Checks content (and 32-bits cast). */
232 	if ((ruleset_attr.handled_access_fs | LANDLOCK_MASK_ACCESS_FS) !=
233 	    LANDLOCK_MASK_ACCESS_FS)
234 		return -EINVAL;
235 
236 	/* Checks network content (and 32-bits cast). */
237 	if ((ruleset_attr.handled_access_net | LANDLOCK_MASK_ACCESS_NET) !=
238 	    LANDLOCK_MASK_ACCESS_NET)
239 		return -EINVAL;
240 
241 	/* Checks IPC scoping content (and 32-bits cast). */
242 	if ((ruleset_attr.scoped | LANDLOCK_MASK_SCOPE) != LANDLOCK_MASK_SCOPE)
243 		return -EINVAL;
244 
245 	/* Checks arguments and transforms to kernel struct. */
246 	ruleset = landlock_create_ruleset(ruleset_attr.handled_access_fs,
247 					  ruleset_attr.handled_access_net,
248 					  ruleset_attr.scoped);
249 	if (IS_ERR(ruleset))
250 		return PTR_ERR(ruleset);
251 
252 	/* Creates anonymous FD referring to the ruleset. */
253 	ruleset_fd = anon_inode_getfd("[landlock-ruleset]", &ruleset_fops,
254 				      ruleset, O_RDWR | O_CLOEXEC);
255 	if (ruleset_fd < 0)
256 		landlock_put_ruleset(ruleset);
257 	return ruleset_fd;
258 }
259 
260 /*
261  * Returns an owned ruleset from a FD. It is thus needed to call
262  * landlock_put_ruleset() on the return value.
263  */
264 static struct landlock_ruleset *get_ruleset_from_fd(const int fd,
265 						    const fmode_t mode)
266 {
267 	CLASS(fd, ruleset_f)(fd);
268 	struct landlock_ruleset *ruleset;
269 
270 	if (fd_empty(ruleset_f))
271 		return ERR_PTR(-EBADF);
272 
273 	/* Checks FD type and access right. */
274 	if (fd_file(ruleset_f)->f_op != &ruleset_fops)
275 		return ERR_PTR(-EBADFD);
276 	if (!(fd_file(ruleset_f)->f_mode & mode))
277 		return ERR_PTR(-EPERM);
278 	ruleset = fd_file(ruleset_f)->private_data;
279 	if (WARN_ON_ONCE(ruleset->num_layers != 1))
280 		return ERR_PTR(-EINVAL);
281 	landlock_get_ruleset(ruleset);
282 	return ruleset;
283 }
284 
285 /* Path handling */
286 
287 /*
288  * @path: Must call put_path(@path) after the call if it succeeded.
289  */
290 static int get_path_from_fd(const s32 fd, struct path *const path)
291 {
292 	CLASS(fd_raw, f)(fd);
293 
294 	BUILD_BUG_ON(!__same_type(
295 		fd, ((struct landlock_path_beneath_attr *)NULL)->parent_fd));
296 
297 	if (fd_empty(f))
298 		return -EBADF;
299 	/*
300 	 * Forbids ruleset FDs, internal filesystems (e.g. nsfs), including
301 	 * pseudo filesystems that will never be mountable (e.g. sockfs,
302 	 * pipefs).
303 	 */
304 	if ((fd_file(f)->f_op == &ruleset_fops) ||
305 	    (fd_file(f)->f_path.mnt->mnt_flags & MNT_INTERNAL) ||
306 	    (fd_file(f)->f_path.dentry->d_sb->s_flags & SB_NOUSER) ||
307 	    IS_PRIVATE(d_backing_inode(fd_file(f)->f_path.dentry)))
308 		return -EBADFD;
309 
310 	*path = fd_file(f)->f_path;
311 	path_get(path);
312 	return 0;
313 }
314 
315 static int add_rule_path_beneath(struct landlock_ruleset *const ruleset,
316 				 const void __user *const rule_attr)
317 {
318 	struct landlock_path_beneath_attr path_beneath_attr;
319 	struct path path;
320 	int res, err;
321 	access_mask_t mask;
322 
323 	/* Copies raw user space buffer. */
324 	res = copy_from_user(&path_beneath_attr, rule_attr,
325 			     sizeof(path_beneath_attr));
326 	if (res)
327 		return -EFAULT;
328 
329 	/*
330 	 * Informs about useless rule: empty allowed_access (i.e. deny rules)
331 	 * are ignored in path walks.
332 	 */
333 	if (!path_beneath_attr.allowed_access)
334 		return -ENOMSG;
335 
336 	/* Checks that allowed_access matches the @ruleset constraints. */
337 	mask = ruleset->access_masks[0].fs;
338 	if ((path_beneath_attr.allowed_access | mask) != mask)
339 		return -EINVAL;
340 
341 	/* Gets and checks the new rule. */
342 	err = get_path_from_fd(path_beneath_attr.parent_fd, &path);
343 	if (err)
344 		return err;
345 
346 	/* Imports the new rule. */
347 	err = landlock_append_fs_rule(ruleset, &path,
348 				      path_beneath_attr.allowed_access);
349 	path_put(&path);
350 	return err;
351 }
352 
353 static int add_rule_net_port(struct landlock_ruleset *ruleset,
354 			     const void __user *const rule_attr)
355 {
356 	struct landlock_net_port_attr net_port_attr;
357 	int res;
358 	access_mask_t mask;
359 
360 	/* Copies raw user space buffer. */
361 	res = copy_from_user(&net_port_attr, rule_attr, sizeof(net_port_attr));
362 	if (res)
363 		return -EFAULT;
364 
365 	/*
366 	 * Informs about useless rule: empty allowed_access (i.e. deny rules)
367 	 * are ignored by network actions.
368 	 */
369 	if (!net_port_attr.allowed_access)
370 		return -ENOMSG;
371 
372 	/* Checks that allowed_access matches the @ruleset constraints. */
373 	mask = landlock_get_net_access_mask(ruleset, 0);
374 	if ((net_port_attr.allowed_access | mask) != mask)
375 		return -EINVAL;
376 
377 	/* Denies inserting a rule with port greater than 65535. */
378 	if (net_port_attr.port > U16_MAX)
379 		return -EINVAL;
380 
381 	/* Imports the new rule. */
382 	return landlock_append_net_rule(ruleset, net_port_attr.port,
383 					net_port_attr.allowed_access);
384 }
385 
386 /**
387  * sys_landlock_add_rule - Add a new rule to a ruleset
388  *
389  * @ruleset_fd: File descriptor tied to the ruleset that should be extended
390  *		with the new rule.
391  * @rule_type: Identify the structure type pointed to by @rule_attr:
392  *             %LANDLOCK_RULE_PATH_BENEATH or %LANDLOCK_RULE_NET_PORT.
393  * @rule_attr: Pointer to a rule (matching the @rule_type).
394  * @flags: Must be 0.
395  *
396  * This system call enables to define a new rule and add it to an existing
397  * ruleset.
398  *
399  * Possible returned errors are:
400  *
401  * - %EOPNOTSUPP: Landlock is supported by the kernel but disabled at boot time;
402  * - %EAFNOSUPPORT: @rule_type is %LANDLOCK_RULE_NET_PORT but TCP/IP is not
403  *   supported by the running kernel;
404  * - %EINVAL: @flags is not 0;
405  * - %EINVAL: The rule accesses are inconsistent (i.e.
406  *   &landlock_path_beneath_attr.allowed_access or
407  *   &landlock_net_port_attr.allowed_access is not a subset of the ruleset
408  *   handled accesses)
409  * - %EINVAL: &landlock_net_port_attr.port is greater than 65535;
410  * - %ENOMSG: Empty accesses (e.g. &landlock_path_beneath_attr.allowed_access is
411  *   0);
412  * - %EBADF: @ruleset_fd is not a file descriptor for the current thread, or a
413  *   member of @rule_attr is not a file descriptor as expected;
414  * - %EBADFD: @ruleset_fd is not a ruleset file descriptor, or a member of
415  *   @rule_attr is not the expected file descriptor type;
416  * - %EPERM: @ruleset_fd has no write access to the underlying ruleset;
417  * - %EFAULT: @rule_attr was not a valid address.
418  */
419 SYSCALL_DEFINE4(landlock_add_rule, const int, ruleset_fd,
420 		const enum landlock_rule_type, rule_type,
421 		const void __user *const, rule_attr, const __u32, flags)
422 {
423 	struct landlock_ruleset *ruleset __free(landlock_put_ruleset) = NULL;
424 
425 	if (!is_initialized())
426 		return -EOPNOTSUPP;
427 
428 	/* No flag for now. */
429 	if (flags)
430 		return -EINVAL;
431 
432 	/* Gets and checks the ruleset. */
433 	ruleset = get_ruleset_from_fd(ruleset_fd, FMODE_CAN_WRITE);
434 	if (IS_ERR(ruleset))
435 		return PTR_ERR(ruleset);
436 
437 	switch (rule_type) {
438 	case LANDLOCK_RULE_PATH_BENEATH:
439 		return add_rule_path_beneath(ruleset, rule_attr);
440 	case LANDLOCK_RULE_NET_PORT:
441 		return add_rule_net_port(ruleset, rule_attr);
442 	default:
443 		return -EINVAL;
444 	}
445 }
446 
447 /* Enforcement */
448 
449 /**
450  * sys_landlock_restrict_self - Enforce a ruleset on the calling thread
451  *
452  * @ruleset_fd: File descriptor tied to the ruleset to merge with the target.
453  * @flags: Supported values:
454  *
455  *         - %LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF
456  *         - %LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON
457  *         - %LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF
458  *         - %LANDLOCK_RESTRICT_SELF_TSYNC
459  *
460  * This system call enforces a Landlock ruleset on the current thread.
461  * Enforcing a ruleset requires that the task has %CAP_SYS_ADMIN in its
462  * namespace or is running with no_new_privs.  This avoids scenarios where
463  * unprivileged tasks can affect the behavior of privileged children.
464  *
465  * Possible returned errors are:
466  *
467  * - %EOPNOTSUPP: Landlock is supported by the kernel but disabled at boot time;
468  * - %EINVAL: @flags contains an unknown bit.
469  * - %EBADF: @ruleset_fd is not a file descriptor for the current thread;
470  * - %EBADFD: @ruleset_fd is not a ruleset file descriptor;
471  * - %EPERM: @ruleset_fd has no read access to the underlying ruleset, or the
472  *   current thread is not running with no_new_privs, or it doesn't have
473  *   %CAP_SYS_ADMIN in its namespace.
474  * - %E2BIG: The maximum number of stacked rulesets is reached for the current
475  *   thread.
476  *
477  * .. kernel-doc:: include/uapi/linux/landlock.h
478  *     :identifiers: landlock_restrict_self_flags
479  */
480 SYSCALL_DEFINE2(landlock_restrict_self, const int, ruleset_fd, const __u32,
481 		flags)
482 {
483 	struct landlock_ruleset *ruleset __free(landlock_put_ruleset) = NULL;
484 	struct cred *new_cred;
485 	struct landlock_cred_security *new_llcred;
486 	bool __maybe_unused log_same_exec, log_new_exec, log_subdomains,
487 		prev_log_subdomains;
488 
489 	if (!is_initialized())
490 		return -EOPNOTSUPP;
491 
492 	/*
493 	 * Similar checks as for seccomp(2), except that an -EPERM may be
494 	 * returned.
495 	 */
496 	if (!task_no_new_privs(current) &&
497 	    !ns_capable_noaudit(current_user_ns(), CAP_SYS_ADMIN))
498 		return -EPERM;
499 
500 	if ((flags | LANDLOCK_MASK_RESTRICT_SELF) !=
501 	    LANDLOCK_MASK_RESTRICT_SELF)
502 		return -EINVAL;
503 
504 	/* Translates "off" flag to boolean. */
505 	log_same_exec = !(flags & LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF);
506 	/* Translates "on" flag to boolean. */
507 	log_new_exec = !!(flags & LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON);
508 	/* Translates "off" flag to boolean. */
509 	log_subdomains = !(flags & LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF);
510 
511 	/*
512 	 * It is allowed to set LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF with
513 	 * -1 as ruleset_fd, but no other flag must be set.
514 	 */
515 	if (!(ruleset_fd == -1 &&
516 	      flags == LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF)) {
517 		/* Gets and checks the ruleset. */
518 		ruleset = get_ruleset_from_fd(ruleset_fd, FMODE_CAN_READ);
519 		if (IS_ERR(ruleset))
520 			return PTR_ERR(ruleset);
521 	}
522 
523 	/* Prepares new credentials. */
524 	new_cred = prepare_creds();
525 	if (!new_cred)
526 		return -ENOMEM;
527 
528 	new_llcred = landlock_cred(new_cred);
529 
530 #ifdef CONFIG_AUDIT
531 	prev_log_subdomains = !new_llcred->log_subdomains_off;
532 	new_llcred->log_subdomains_off = !prev_log_subdomains ||
533 					 !log_subdomains;
534 #endif /* CONFIG_AUDIT */
535 
536 	/*
537 	 * The only case when a ruleset may not be set is if
538 	 * LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF is set and ruleset_fd is -1.
539 	 * We could optimize this case by not calling commit_creds() if this flag
540 	 * was already set, but it is not worth the complexity.
541 	 */
542 	if (ruleset) {
543 		/*
544 		 * There is no possible race condition while copying and
545 		 * manipulating the current credentials because they are
546 		 * dedicated per thread.
547 		 */
548 		struct landlock_ruleset *const new_dom =
549 			landlock_merge_ruleset(new_llcred->domain, ruleset);
550 		if (IS_ERR(new_dom)) {
551 			abort_creds(new_cred);
552 			return PTR_ERR(new_dom);
553 		}
554 
555 #ifdef CONFIG_AUDIT
556 		new_dom->hierarchy->log_same_exec = log_same_exec;
557 		new_dom->hierarchy->log_new_exec = log_new_exec;
558 		if ((!log_same_exec && !log_new_exec) || !prev_log_subdomains)
559 			new_dom->hierarchy->log_status = LANDLOCK_LOG_DISABLED;
560 #endif /* CONFIG_AUDIT */
561 
562 		/* Replaces the old (prepared) domain. */
563 		landlock_put_ruleset(new_llcred->domain);
564 		new_llcred->domain = new_dom;
565 
566 #ifdef CONFIG_AUDIT
567 		new_llcred->domain_exec |= BIT(new_dom->num_layers - 1);
568 #endif /* CONFIG_AUDIT */
569 	}
570 
571 	if (flags & LANDLOCK_RESTRICT_SELF_TSYNC) {
572 		const int err = landlock_restrict_sibling_threads(
573 			current_cred(), new_cred);
574 		if (err) {
575 			abort_creds(new_cred);
576 			return err;
577 		}
578 	}
579 
580 	return commit_creds(new_cred);
581 }
582