• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2022 The ChromiumOS Authors
2  * Use of this source code is governed by a BSD-style license that can be
3  * found in the LICENSE file.
4  */
5 
6 /* Define _GNU_SOURCE because we need O_PATH to resolve correctly. */
7 #define _GNU_SOURCE
8 
9 #include "landlock_util.h"
10 
11 #include <fcntl.h>
12 #include <sys/stat.h>
13 
14 #include "util.h"
15 
landlock_create_ruleset(const struct minijail_landlock_ruleset_attr * const attr,const size_t size,const __u32 flags)16 int landlock_create_ruleset(
17     const struct minijail_landlock_ruleset_attr *const attr, const size_t size,
18     const __u32 flags)
19 {
20 	return syscall(__NR_landlock_create_ruleset, attr, size, flags);
21 }
22 
landlock_add_rule(const int ruleset_fd,const enum minijail_landlock_rule_type rule_type,const void * const rule_attr,const __u32 flags)23 int landlock_add_rule(const int ruleset_fd,
24 		      const enum minijail_landlock_rule_type rule_type,
25 		      const void *const rule_attr, const __u32 flags)
26 {
27 	return syscall(__NR_landlock_add_rule, ruleset_fd, rule_type, rule_attr,
28 		       flags);
29 }
30 
landlock_restrict_self(const int ruleset_fd,const __u32 flags)31 int landlock_restrict_self(const int ruleset_fd, const __u32 flags)
32 {
33 	return syscall(__NR_landlock_restrict_self, ruleset_fd, flags);
34 }
35 
populate_ruleset_internal(const char * const path,const int ruleset_fd,const uint64_t allowed_access)36 bool populate_ruleset_internal(const char *const path, const int ruleset_fd,
37 			       const uint64_t allowed_access)
38 {
39 	struct minijail_landlock_path_beneath_attr path_beneath = {
40 	    .parent_fd = -1,
41 	};
42 	struct stat statbuf;
43 	attribute_cleanup_fd int parent_fd = open(path, O_PATH | O_CLOEXEC);
44 	path_beneath.parent_fd = parent_fd;
45 	if (path_beneath.parent_fd < 0) {
46 		pwarn("Failed to open \"%s\"", path);
47 		return false;
48 	}
49 	if (fstat(path_beneath.parent_fd, &statbuf)) {
50 		return false;
51 	}
52 	path_beneath.allowed_access = allowed_access;
53 	if (!S_ISDIR(statbuf.st_mode)) {
54 		path_beneath.allowed_access &= ACCESS_FILE;
55 	}
56 	if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_PATH_BENEATH,
57 			      &path_beneath, 0)) {
58 		pwarn("Failed to update ruleset \"%s\"", path);
59 		return false;
60 	}
61 	return true;
62 }
63