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
16
landlock_create_ruleset(const struct minijail_landlock_ruleset_attr * const attr,const size_t size,const __u32 flags)17 int landlock_create_ruleset(const struct
18 minijail_landlock_ruleset_attr *const attr,
19 const size_t size, const __u32 flags)
20 {
21 return syscall(__NR_landlock_create_ruleset, attr, size, flags);
22 }
23
landlock_add_rule(const int ruleset_fd,const enum minijail_landlock_rule_type rule_type,const void * const rule_attr,const __u32 flags)24 int landlock_add_rule(const int ruleset_fd,
25 const enum minijail_landlock_rule_type rule_type,
26 const void *const rule_attr, const __u32 flags)
27 {
28 return syscall(__NR_landlock_add_rule, ruleset_fd, rule_type,
29 rule_attr, flags);
30 }
31
landlock_restrict_self(const int ruleset_fd,const __u32 flags)32 int landlock_restrict_self(const int ruleset_fd,
33 const __u32 flags)
34 {
35 return syscall(__NR_landlock_restrict_self, ruleset_fd, flags);
36 }
37
populate_ruleset_internal(const char * const path,const int ruleset_fd,const uint64_t allowed_access)38 bool populate_ruleset_internal(const char *const path,
39 const int ruleset_fd,
40 const uint64_t allowed_access)
41 {
42 struct minijail_landlock_path_beneath_attr path_beneath = {
43 .parent_fd = -1,
44 };
45 struct stat statbuf;
46 attribute_cleanup_fd int parent_fd = open(path, O_PATH | O_CLOEXEC);
47 path_beneath.parent_fd = parent_fd;
48 if (path_beneath.parent_fd < 0) {
49 pwarn("Failed to open \"%s\"", path);
50 return false;
51 }
52 if (fstat(path_beneath.parent_fd, &statbuf)) {
53 return false;
54 }
55 path_beneath.allowed_access = allowed_access;
56 if (!S_ISDIR(statbuf.st_mode)) {
57 path_beneath.allowed_access &= ACCESS_FILE;
58 }
59 if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_PATH_BENEATH,
60 &path_beneath, 0)) {
61 pwarn("Failed to update ruleset \"%s\"", path);
62 return false;
63 }
64 return true;
65 }
66