xref: /linux/samples/landlock/sandboxer.c (revision 4e94ddfe2aab72139acb8d5372fac9e6c3f3e383)
1 // SPDX-License-Identifier: BSD-3-Clause
2 /*
3  * Simple Landlock sandbox manager able to launch a process restricted by a
4  * user-defined filesystem access control policy.
5  *
6  * Copyright © 2017-2020 Mickaël Salaün <mic@digikod.net>
7  * Copyright © 2020 ANSSI
8  */
9 
10 #define _GNU_SOURCE
11 #define __SANE_USERSPACE_TYPES__
12 #include <arpa/inet.h>
13 #include <errno.h>
14 #include <fcntl.h>
15 #include <linux/landlock.h>
16 #include <linux/prctl.h>
17 #include <stddef.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <sys/prctl.h>
22 #include <sys/stat.h>
23 #include <sys/syscall.h>
24 #include <unistd.h>
25 
26 #ifndef landlock_create_ruleset
27 static inline int
28 landlock_create_ruleset(const struct landlock_ruleset_attr *const attr,
29 			const size_t size, const __u32 flags)
30 {
31 	return syscall(__NR_landlock_create_ruleset, attr, size, flags);
32 }
33 #endif
34 
35 #ifndef landlock_add_rule
36 static inline int landlock_add_rule(const int ruleset_fd,
37 				    const enum landlock_rule_type rule_type,
38 				    const void *const rule_attr,
39 				    const __u32 flags)
40 {
41 	return syscall(__NR_landlock_add_rule, ruleset_fd, rule_type, rule_attr,
42 		       flags);
43 }
44 #endif
45 
46 #ifndef landlock_restrict_self
47 static inline int landlock_restrict_self(const int ruleset_fd,
48 					 const __u32 flags)
49 {
50 	return syscall(__NR_landlock_restrict_self, ruleset_fd, flags);
51 }
52 #endif
53 
54 #define ENV_FS_RO_NAME "LL_FS_RO"
55 #define ENV_FS_RW_NAME "LL_FS_RW"
56 #define ENV_TCP_BIND_NAME "LL_TCP_BIND"
57 #define ENV_TCP_CONNECT_NAME "LL_TCP_CONNECT"
58 #define ENV_DELIMITER ":"
59 
60 static int parse_path(char *env_path, const char ***const path_list)
61 {
62 	int i, num_paths = 0;
63 
64 	if (env_path) {
65 		num_paths++;
66 		for (i = 0; env_path[i]; i++) {
67 			if (env_path[i] == ENV_DELIMITER[0])
68 				num_paths++;
69 		}
70 	}
71 	*path_list = malloc(num_paths * sizeof(**path_list));
72 	for (i = 0; i < num_paths; i++)
73 		(*path_list)[i] = strsep(&env_path, ENV_DELIMITER);
74 
75 	return num_paths;
76 }
77 
78 /* clang-format off */
79 
80 #define ACCESS_FILE ( \
81 	LANDLOCK_ACCESS_FS_EXECUTE | \
82 	LANDLOCK_ACCESS_FS_WRITE_FILE | \
83 	LANDLOCK_ACCESS_FS_READ_FILE | \
84 	LANDLOCK_ACCESS_FS_TRUNCATE)
85 
86 /* clang-format on */
87 
88 static int populate_ruleset_fs(const char *const env_var, const int ruleset_fd,
89 			       const __u64 allowed_access)
90 {
91 	int num_paths, i, ret = 1;
92 	char *env_path_name;
93 	const char **path_list = NULL;
94 	struct landlock_path_beneath_attr path_beneath = {
95 		.parent_fd = -1,
96 	};
97 
98 	env_path_name = getenv(env_var);
99 	if (!env_path_name) {
100 		/* Prevents users to forget a setting. */
101 		fprintf(stderr, "Missing environment variable %s\n", env_var);
102 		return 1;
103 	}
104 	env_path_name = strdup(env_path_name);
105 	unsetenv(env_var);
106 	num_paths = parse_path(env_path_name, &path_list);
107 	if (num_paths == 1 && path_list[0][0] == '\0') {
108 		/*
109 		 * Allows to not use all possible restrictions (e.g. use
110 		 * LL_FS_RO without LL_FS_RW).
111 		 */
112 		ret = 0;
113 		goto out_free_name;
114 	}
115 
116 	for (i = 0; i < num_paths; i++) {
117 		struct stat statbuf;
118 
119 		path_beneath.parent_fd = open(path_list[i], O_PATH | O_CLOEXEC);
120 		if (path_beneath.parent_fd < 0) {
121 			fprintf(stderr, "Failed to open \"%s\": %s\n",
122 				path_list[i], strerror(errno));
123 			goto out_free_name;
124 		}
125 		if (fstat(path_beneath.parent_fd, &statbuf)) {
126 			close(path_beneath.parent_fd);
127 			goto out_free_name;
128 		}
129 		path_beneath.allowed_access = allowed_access;
130 		if (!S_ISDIR(statbuf.st_mode))
131 			path_beneath.allowed_access &= ACCESS_FILE;
132 		if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_PATH_BENEATH,
133 				      &path_beneath, 0)) {
134 			fprintf(stderr,
135 				"Failed to update the ruleset with \"%s\": %s\n",
136 				path_list[i], strerror(errno));
137 			close(path_beneath.parent_fd);
138 			goto out_free_name;
139 		}
140 		close(path_beneath.parent_fd);
141 	}
142 	ret = 0;
143 
144 out_free_name:
145 	free(path_list);
146 	free(env_path_name);
147 	return ret;
148 }
149 
150 static int populate_ruleset_net(const char *const env_var, const int ruleset_fd,
151 				const __u64 allowed_access)
152 {
153 	int ret = 1;
154 	char *env_port_name, *strport;
155 	struct landlock_net_port_attr net_port = {
156 		.allowed_access = allowed_access,
157 		.port = 0,
158 	};
159 
160 	env_port_name = getenv(env_var);
161 	if (!env_port_name)
162 		return 0;
163 	env_port_name = strdup(env_port_name);
164 	unsetenv(env_var);
165 
166 	while ((strport = strsep(&env_port_name, ENV_DELIMITER))) {
167 		net_port.port = atoi(strport);
168 		if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
169 				      &net_port, 0)) {
170 			fprintf(stderr,
171 				"Failed to update the ruleset with port \"%llu\": %s\n",
172 				net_port.port, strerror(errno));
173 			goto out_free_name;
174 		}
175 	}
176 	ret = 0;
177 
178 out_free_name:
179 	free(env_port_name);
180 	return ret;
181 }
182 
183 /* clang-format off */
184 
185 #define ACCESS_FS_ROUGHLY_READ ( \
186 	LANDLOCK_ACCESS_FS_EXECUTE | \
187 	LANDLOCK_ACCESS_FS_READ_FILE | \
188 	LANDLOCK_ACCESS_FS_READ_DIR)
189 
190 #define ACCESS_FS_ROUGHLY_WRITE ( \
191 	LANDLOCK_ACCESS_FS_WRITE_FILE | \
192 	LANDLOCK_ACCESS_FS_REMOVE_DIR | \
193 	LANDLOCK_ACCESS_FS_REMOVE_FILE | \
194 	LANDLOCK_ACCESS_FS_MAKE_CHAR | \
195 	LANDLOCK_ACCESS_FS_MAKE_DIR | \
196 	LANDLOCK_ACCESS_FS_MAKE_REG | \
197 	LANDLOCK_ACCESS_FS_MAKE_SOCK | \
198 	LANDLOCK_ACCESS_FS_MAKE_FIFO | \
199 	LANDLOCK_ACCESS_FS_MAKE_BLOCK | \
200 	LANDLOCK_ACCESS_FS_MAKE_SYM | \
201 	LANDLOCK_ACCESS_FS_REFER | \
202 	LANDLOCK_ACCESS_FS_TRUNCATE)
203 
204 /* clang-format on */
205 
206 #define LANDLOCK_ABI_LAST 4
207 
208 int main(const int argc, char *const argv[], char *const *const envp)
209 {
210 	const char *cmd_path;
211 	char *const *cmd_argv;
212 	int ruleset_fd, abi;
213 	char *env_port_name;
214 	__u64 access_fs_ro = ACCESS_FS_ROUGHLY_READ,
215 	      access_fs_rw = ACCESS_FS_ROUGHLY_READ | ACCESS_FS_ROUGHLY_WRITE;
216 
217 	struct landlock_ruleset_attr ruleset_attr = {
218 		.handled_access_fs = access_fs_rw,
219 		.handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP |
220 				      LANDLOCK_ACCESS_NET_CONNECT_TCP,
221 	};
222 
223 	if (argc < 2) {
224 		fprintf(stderr,
225 			"usage: %s=\"...\" %s=\"...\" %s=\"...\" %s=\"...\"%s "
226 			"<cmd> [args]...\n\n",
227 			ENV_FS_RO_NAME, ENV_FS_RW_NAME, ENV_TCP_BIND_NAME,
228 			ENV_TCP_CONNECT_NAME, argv[0]);
229 		fprintf(stderr,
230 			"Launch a command in a restricted environment.\n\n");
231 		fprintf(stderr,
232 			"Environment variables containing paths and ports "
233 			"each separated by a colon:\n");
234 		fprintf(stderr,
235 			"* %s: list of paths allowed to be used in a read-only way.\n",
236 			ENV_FS_RO_NAME);
237 		fprintf(stderr,
238 			"* %s: list of paths allowed to be used in a read-write way.\n\n",
239 			ENV_FS_RW_NAME);
240 		fprintf(stderr,
241 			"Environment variables containing ports are optional "
242 			"and could be skipped.\n");
243 		fprintf(stderr,
244 			"* %s: list of ports allowed to bind (server).\n",
245 			ENV_TCP_BIND_NAME);
246 		fprintf(stderr,
247 			"* %s: list of ports allowed to connect (client).\n",
248 			ENV_TCP_CONNECT_NAME);
249 		fprintf(stderr,
250 			"\nexample:\n"
251 			"%s=\"/bin:/lib:/usr:/proc:/etc:/dev/urandom\" "
252 			"%s=\"/dev/null:/dev/full:/dev/zero:/dev/pts:/tmp\" "
253 			"%s=\"9418\" "
254 			"%s=\"80:443\" "
255 			"%s bash -i\n\n",
256 			ENV_FS_RO_NAME, ENV_FS_RW_NAME, ENV_TCP_BIND_NAME,
257 			ENV_TCP_CONNECT_NAME, argv[0]);
258 		fprintf(stderr,
259 			"This sandboxer can use Landlock features "
260 			"up to ABI version %d.\n",
261 			LANDLOCK_ABI_LAST);
262 		return 1;
263 	}
264 
265 	abi = landlock_create_ruleset(NULL, 0, LANDLOCK_CREATE_RULESET_VERSION);
266 	if (abi < 0) {
267 		const int err = errno;
268 
269 		perror("Failed to check Landlock compatibility");
270 		switch (err) {
271 		case ENOSYS:
272 			fprintf(stderr,
273 				"Hint: Landlock is not supported by the current kernel. "
274 				"To support it, build the kernel with "
275 				"CONFIG_SECURITY_LANDLOCK=y and prepend "
276 				"\"landlock,\" to the content of CONFIG_LSM.\n");
277 			break;
278 		case EOPNOTSUPP:
279 			fprintf(stderr,
280 				"Hint: Landlock is currently disabled. "
281 				"It can be enabled in the kernel configuration by "
282 				"prepending \"landlock,\" to the content of CONFIG_LSM, "
283 				"or at boot time by setting the same content to the "
284 				"\"lsm\" kernel parameter.\n");
285 			break;
286 		}
287 		return 1;
288 	}
289 
290 	/* Best-effort security. */
291 	switch (abi) {
292 	case 1:
293 		/*
294 		 * Removes LANDLOCK_ACCESS_FS_REFER for ABI < 2
295 		 *
296 		 * Note: The "refer" operations (file renaming and linking
297 		 * across different directories) are always forbidden when using
298 		 * Landlock with ABI 1.
299 		 *
300 		 * If only ABI 1 is available, this sandboxer knowingly forbids
301 		 * refer operations.
302 		 *
303 		 * If a program *needs* to do refer operations after enabling
304 		 * Landlock, it can not use Landlock at ABI level 1.  To be
305 		 * compatible with different kernel versions, such programs
306 		 * should then fall back to not restrict themselves at all if
307 		 * the running kernel only supports ABI 1.
308 		 */
309 		ruleset_attr.handled_access_fs &= ~LANDLOCK_ACCESS_FS_REFER;
310 		__attribute__((fallthrough));
311 	case 2:
312 		/* Removes LANDLOCK_ACCESS_FS_TRUNCATE for ABI < 3 */
313 		ruleset_attr.handled_access_fs &= ~LANDLOCK_ACCESS_FS_TRUNCATE;
314 		__attribute__((fallthrough));
315 	case 3:
316 		/* Removes network support for ABI < 4 */
317 		ruleset_attr.handled_access_net &=
318 			~(LANDLOCK_ACCESS_NET_BIND_TCP |
319 			  LANDLOCK_ACCESS_NET_CONNECT_TCP);
320 		fprintf(stderr,
321 			"Hint: You should update the running kernel "
322 			"to leverage Landlock features "
323 			"provided by ABI version %d (instead of %d).\n",
324 			LANDLOCK_ABI_LAST, abi);
325 		__attribute__((fallthrough));
326 	case LANDLOCK_ABI_LAST:
327 		break;
328 	default:
329 		fprintf(stderr,
330 			"Hint: You should update this sandboxer "
331 			"to leverage Landlock features "
332 			"provided by ABI version %d (instead of %d).\n",
333 			abi, LANDLOCK_ABI_LAST);
334 	}
335 	access_fs_ro &= ruleset_attr.handled_access_fs;
336 	access_fs_rw &= ruleset_attr.handled_access_fs;
337 
338 	/* Removes bind access attribute if not supported by a user. */
339 	env_port_name = getenv(ENV_TCP_BIND_NAME);
340 	if (!env_port_name) {
341 		ruleset_attr.handled_access_net &=
342 			~LANDLOCK_ACCESS_NET_BIND_TCP;
343 	}
344 	/* Removes connect access attribute if not supported by a user. */
345 	env_port_name = getenv(ENV_TCP_CONNECT_NAME);
346 	if (!env_port_name) {
347 		ruleset_attr.handled_access_net &=
348 			~LANDLOCK_ACCESS_NET_CONNECT_TCP;
349 	}
350 
351 	ruleset_fd =
352 		landlock_create_ruleset(&ruleset_attr, sizeof(ruleset_attr), 0);
353 	if (ruleset_fd < 0) {
354 		perror("Failed to create a ruleset");
355 		return 1;
356 	}
357 
358 	if (populate_ruleset_fs(ENV_FS_RO_NAME, ruleset_fd, access_fs_ro)) {
359 		goto err_close_ruleset;
360 	}
361 	if (populate_ruleset_fs(ENV_FS_RW_NAME, ruleset_fd, access_fs_rw)) {
362 		goto err_close_ruleset;
363 	}
364 
365 	if (populate_ruleset_net(ENV_TCP_BIND_NAME, ruleset_fd,
366 				 LANDLOCK_ACCESS_NET_BIND_TCP)) {
367 		goto err_close_ruleset;
368 	}
369 	if (populate_ruleset_net(ENV_TCP_CONNECT_NAME, ruleset_fd,
370 				 LANDLOCK_ACCESS_NET_CONNECT_TCP)) {
371 		goto err_close_ruleset;
372 	}
373 
374 	if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
375 		perror("Failed to restrict privileges");
376 		goto err_close_ruleset;
377 	}
378 	if (landlock_restrict_self(ruleset_fd, 0)) {
379 		perror("Failed to enforce ruleset");
380 		goto err_close_ruleset;
381 	}
382 	close(ruleset_fd);
383 
384 	cmd_path = argv[1];
385 	cmd_argv = argv + 1;
386 	execvpe(cmd_path, cmd_argv, envp);
387 	fprintf(stderr, "Failed to execute \"%s\": %s\n", cmd_path,
388 		strerror(errno));
389 	fprintf(stderr, "Hint: access to the binary, the interpreter or "
390 			"shared libraries may be denied.\n");
391 	return 1;
392 
393 err_close_ruleset:
394 	close(ruleset_fd);
395 	return 1;
396 }
397