xref: /linux/samples/landlock/sandboxer.c (revision a92cb5d7c6c988f304df355f4b5afcc379428f07)
1 // SPDX-License-Identifier: BSD-3-Clause
2 /*
3  * Simple Landlock sandbox manager able to execute a process restricted by
4  * user-defined file system and network access control policies.
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/socket.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 #include <stdbool.h>
26 
27 #if defined(__GLIBC__)
28 #include <linux/prctl.h>
29 #endif
30 
31 #ifndef landlock_create_ruleset
32 static inline int
33 landlock_create_ruleset(const struct landlock_ruleset_attr *const attr,
34 			const size_t size, const __u32 flags)
35 {
36 	return syscall(__NR_landlock_create_ruleset, attr, size, flags);
37 }
38 #endif
39 
40 #ifndef landlock_add_rule
41 static inline int landlock_add_rule(const int ruleset_fd,
42 				    const enum landlock_rule_type rule_type,
43 				    const void *const rule_attr,
44 				    const __u32 flags)
45 {
46 	return syscall(__NR_landlock_add_rule, ruleset_fd, rule_type, rule_attr,
47 		       flags);
48 }
49 #endif
50 
51 #ifndef landlock_restrict_self
52 static inline int landlock_restrict_self(const int ruleset_fd,
53 					 const __u32 flags)
54 {
55 	return syscall(__NR_landlock_restrict_self, ruleset_fd, flags);
56 }
57 #endif
58 
59 #define ENV_FS_RO_NAME "LL_FS_RO"
60 #define ENV_FS_RW_NAME "LL_FS_RW"
61 #define ENV_TCP_BIND_NAME "LL_TCP_BIND"
62 #define ENV_TCP_CONNECT_NAME "LL_TCP_CONNECT"
63 #define ENV_SCOPED_NAME "LL_SCOPED"
64 #define ENV_FORCE_LOG_NAME "LL_FORCE_LOG"
65 #define ENV_DELIMITER ":"
66 
67 static int str2num(const char *numstr, __u64 *num_dst)
68 {
69 	char *endptr = NULL;
70 	int err = 0;
71 	__u64 num;
72 
73 	errno = 0;
74 	num = strtoull(numstr, &endptr, 10);
75 	if (errno != 0)
76 		err = errno;
77 	/* Was the string empty, or not entirely parsed successfully? */
78 	else if ((*numstr == '\0') || (*endptr != '\0'))
79 		err = EINVAL;
80 	else
81 		*num_dst = num;
82 
83 	return err;
84 }
85 
86 static int parse_path(char *env_path, const char ***const path_list)
87 {
88 	int i, num_paths = 0;
89 
90 	if (env_path) {
91 		num_paths++;
92 		for (i = 0; env_path[i]; i++) {
93 			if (env_path[i] == ENV_DELIMITER[0])
94 				num_paths++;
95 		}
96 	}
97 	*path_list = malloc(num_paths * sizeof(**path_list));
98 	if (!*path_list)
99 		return -1;
100 
101 	for (i = 0; i < num_paths; i++)
102 		(*path_list)[i] = strsep(&env_path, ENV_DELIMITER);
103 
104 	return num_paths;
105 }
106 
107 /* clang-format off */
108 
109 #define ACCESS_FILE ( \
110 	LANDLOCK_ACCESS_FS_EXECUTE | \
111 	LANDLOCK_ACCESS_FS_WRITE_FILE | \
112 	LANDLOCK_ACCESS_FS_READ_FILE | \
113 	LANDLOCK_ACCESS_FS_TRUNCATE | \
114 	LANDLOCK_ACCESS_FS_IOCTL_DEV | \
115 	LANDLOCK_ACCESS_FS_RESOLVE_UNIX)
116 
117 /* clang-format on */
118 
119 static int populate_ruleset_fs(const char *const env_var, const int ruleset_fd,
120 			       const __u64 allowed_access)
121 {
122 	int num_paths, i, ret = 1;
123 	char *env_path_name;
124 	const char **path_list = NULL;
125 	struct landlock_path_beneath_attr path_beneath = {
126 		.parent_fd = -1,
127 	};
128 
129 	env_path_name = getenv(env_var);
130 	if (!env_path_name) {
131 		/* Prevents users to forget a setting. */
132 		fprintf(stderr, "Missing environment variable %s\n", env_var);
133 		return 1;
134 	}
135 	env_path_name = strdup(env_path_name);
136 	unsetenv(env_var);
137 	num_paths = parse_path(env_path_name, &path_list);
138 	if (num_paths < 0) {
139 		fprintf(stderr, "Failed to allocate memory\n");
140 		goto out_free_name;
141 	}
142 	if (num_paths == 1 && path_list[0][0] == '\0') {
143 		/*
144 		 * Allows to not use all possible restrictions (e.g. use
145 		 * LL_FS_RO without LL_FS_RW).
146 		 */
147 		ret = 0;
148 		goto out_free_name;
149 	}
150 
151 	for (i = 0; i < num_paths; i++) {
152 		struct stat statbuf;
153 
154 		path_beneath.parent_fd = open(path_list[i], O_PATH | O_CLOEXEC);
155 		if (path_beneath.parent_fd < 0) {
156 			fprintf(stderr, "Failed to open \"%s\": %s\n",
157 				path_list[i], strerror(errno));
158 			continue;
159 		}
160 		if (fstat(path_beneath.parent_fd, &statbuf)) {
161 			fprintf(stderr, "Failed to stat \"%s\": %s\n",
162 				path_list[i], strerror(errno));
163 			close(path_beneath.parent_fd);
164 			goto out_free_name;
165 		}
166 		path_beneath.allowed_access = allowed_access;
167 		if (!S_ISDIR(statbuf.st_mode))
168 			path_beneath.allowed_access &= ACCESS_FILE;
169 		if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_PATH_BENEATH,
170 				      &path_beneath, 0)) {
171 			fprintf(stderr,
172 				"Failed to update the ruleset with \"%s\": %s\n",
173 				path_list[i], strerror(errno));
174 			close(path_beneath.parent_fd);
175 			goto out_free_name;
176 		}
177 		close(path_beneath.parent_fd);
178 	}
179 	ret = 0;
180 
181 out_free_name:
182 	free(path_list);
183 	free(env_path_name);
184 	return ret;
185 }
186 
187 static int populate_ruleset_net(const char *const env_var, const int ruleset_fd,
188 				const __u64 allowed_access)
189 {
190 	int ret = 1;
191 	char *env_port_name, *env_port_name_next, *strport;
192 	struct landlock_net_port_attr net_port = {
193 		.allowed_access = allowed_access,
194 	};
195 
196 	env_port_name = getenv(env_var);
197 	if (!env_port_name)
198 		return 0;
199 	env_port_name = strdup(env_port_name);
200 	unsetenv(env_var);
201 
202 	env_port_name_next = env_port_name;
203 	while ((strport = strsep(&env_port_name_next, ENV_DELIMITER))) {
204 		__u64 port;
205 
206 		if (strcmp(strport, "") == 0)
207 			continue;
208 
209 		if (str2num(strport, &port)) {
210 			fprintf(stderr, "Failed to parse port at \"%s\"\n",
211 				strport);
212 			goto out_free_name;
213 		}
214 		net_port.port = port;
215 		if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
216 				      &net_port, 0)) {
217 			fprintf(stderr,
218 				"Failed to update the ruleset with port \"%llu\": %s\n",
219 				net_port.port, strerror(errno));
220 			goto out_free_name;
221 		}
222 	}
223 	ret = 0;
224 
225 out_free_name:
226 	free(env_port_name);
227 	return ret;
228 }
229 
230 /* Returns true on error, false otherwise. */
231 static bool check_ruleset_scope(const char *const env_var,
232 				struct landlock_ruleset_attr *ruleset_attr)
233 {
234 	char *env_type_scope, *env_type_scope_next, *ipc_scoping_name;
235 	bool error = false;
236 	bool abstract_scoping = false;
237 	bool signal_scoping = false;
238 
239 	/* Scoping is not supported by Landlock ABI */
240 	if (!(ruleset_attr->scoped &
241 	      (LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET | LANDLOCK_SCOPE_SIGNAL)))
242 		goto out_unset;
243 
244 	env_type_scope = getenv(env_var);
245 	/* Scoping is not supported by the user */
246 	if (!env_type_scope || strcmp("", env_type_scope) == 0)
247 		goto out_unset;
248 
249 	env_type_scope = strdup(env_type_scope);
250 	env_type_scope_next = env_type_scope;
251 	while ((ipc_scoping_name =
252 			strsep(&env_type_scope_next, ENV_DELIMITER))) {
253 		if (strcmp("a", ipc_scoping_name) == 0 && !abstract_scoping) {
254 			abstract_scoping = true;
255 		} else if (strcmp("s", ipc_scoping_name) == 0 &&
256 			   !signal_scoping) {
257 			signal_scoping = true;
258 		} else {
259 			fprintf(stderr, "Unknown or duplicate scope \"%s\"\n",
260 				ipc_scoping_name);
261 			error = true;
262 			goto out_free_name;
263 		}
264 	}
265 
266 out_free_name:
267 	free(env_type_scope);
268 
269 out_unset:
270 	if (!abstract_scoping)
271 		ruleset_attr->scoped &= ~LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET;
272 	if (!signal_scoping)
273 		ruleset_attr->scoped &= ~LANDLOCK_SCOPE_SIGNAL;
274 
275 	unsetenv(env_var);
276 	return error;
277 }
278 
279 /* clang-format off */
280 
281 #define ACCESS_FS_ROUGHLY_READ ( \
282 	LANDLOCK_ACCESS_FS_EXECUTE | \
283 	LANDLOCK_ACCESS_FS_READ_FILE | \
284 	LANDLOCK_ACCESS_FS_READ_DIR)
285 
286 #define ACCESS_FS_ROUGHLY_WRITE ( \
287 	LANDLOCK_ACCESS_FS_WRITE_FILE | \
288 	LANDLOCK_ACCESS_FS_REMOVE_DIR | \
289 	LANDLOCK_ACCESS_FS_REMOVE_FILE | \
290 	LANDLOCK_ACCESS_FS_MAKE_CHAR | \
291 	LANDLOCK_ACCESS_FS_MAKE_DIR | \
292 	LANDLOCK_ACCESS_FS_MAKE_REG | \
293 	LANDLOCK_ACCESS_FS_MAKE_SOCK | \
294 	LANDLOCK_ACCESS_FS_MAKE_FIFO | \
295 	LANDLOCK_ACCESS_FS_MAKE_BLOCK | \
296 	LANDLOCK_ACCESS_FS_MAKE_SYM | \
297 	LANDLOCK_ACCESS_FS_REFER | \
298 	LANDLOCK_ACCESS_FS_TRUNCATE | \
299 	LANDLOCK_ACCESS_FS_IOCTL_DEV | \
300 	LANDLOCK_ACCESS_FS_RESOLVE_UNIX)
301 
302 /* clang-format on */
303 
304 #define LANDLOCK_ABI_LAST 9
305 
306 #define XSTR(s) #s
307 #define STR(s) XSTR(s)
308 
309 /* clang-format off */
310 
311 static const char help[] =
312 	"usage: " ENV_FS_RO_NAME "=\"...\" " ENV_FS_RW_NAME "=\"...\" "
313 	"[other environment variables] %1$s <cmd> [args]...\n"
314 	"\n"
315 	"Execute the given command in a restricted environment.\n"
316 	"Multi-valued settings (lists of ports, paths, scopes) are colon-delimited.\n"
317 	"\n"
318 	"Mandatory settings:\n"
319 	"* " ENV_FS_RO_NAME ": paths allowed to be used in a read-only way\n"
320 	"* " ENV_FS_RW_NAME ": paths allowed to be used in a read-write way\n"
321 	"\n"
322 	"Optional settings (when not set, their associated access check "
323 	"is always allowed, which is different from an empty string which "
324 	"means an empty list):\n"
325 	"* " ENV_TCP_BIND_NAME ": ports allowed to bind (server)\n"
326 	"* " ENV_TCP_CONNECT_NAME ": ports allowed to connect (client)\n"
327 	"* " ENV_SCOPED_NAME ": actions denied on the outside of the landlock domain\n"
328 	"  - \"a\" to restrict opening abstract unix sockets\n"
329 	"  - \"s\" to restrict sending signals\n"
330 	"\n"
331 	"A sandboxer should not log denied access requests to avoid spamming logs, "
332 	"but to test audit we can set " ENV_FORCE_LOG_NAME "=1\n"
333 	"\n"
334 	"Example:\n"
335 	ENV_FS_RO_NAME "=\"${PATH}:/lib:/usr:/proc:/etc:/dev/urandom\" "
336 	ENV_FS_RW_NAME "=\"/dev/null:/dev/full:/dev/zero:/dev/pts:/tmp\" "
337 	ENV_TCP_BIND_NAME "=\"9418\" "
338 	ENV_TCP_CONNECT_NAME "=\"80:443\" "
339 	ENV_SCOPED_NAME "=\"a:s\" "
340 	"%1$s bash -i\n"
341 	"\n"
342 	"This sandboxer can use Landlock features up to ABI version "
343 	STR(LANDLOCK_ABI_LAST) ".\n";
344 
345 /* clang-format on */
346 
347 int main(const int argc, char *const argv[], char *const *const envp)
348 {
349 	const char *cmd_path;
350 	char *const *cmd_argv;
351 	int ruleset_fd, abi;
352 	char *env_port_name, *env_force_log;
353 	__u64 access_fs_ro = ACCESS_FS_ROUGHLY_READ,
354 	      access_fs_rw = ACCESS_FS_ROUGHLY_READ | ACCESS_FS_ROUGHLY_WRITE;
355 
356 	struct landlock_ruleset_attr ruleset_attr = {
357 		.handled_access_fs = access_fs_rw,
358 		.handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP |
359 				      LANDLOCK_ACCESS_NET_CONNECT_TCP,
360 		.scoped = LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET |
361 			  LANDLOCK_SCOPE_SIGNAL,
362 	};
363 	int supported_restrict_flags = LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON;
364 	int set_restrict_flags = 0;
365 
366 	if (argc < 2) {
367 		fprintf(stderr, help, argv[0]);
368 		return 1;
369 	}
370 
371 	abi = landlock_create_ruleset(NULL, 0, LANDLOCK_CREATE_RULESET_VERSION);
372 	if (abi < 0) {
373 		const int err = errno;
374 
375 		perror("Failed to check Landlock compatibility");
376 		switch (err) {
377 		case ENOSYS:
378 			fprintf(stderr,
379 				"Hint: Landlock is not supported by the current kernel. "
380 				"To support it, build the kernel with "
381 				"CONFIG_SECURITY_LANDLOCK=y and prepend "
382 				"\"landlock,\" to the content of CONFIG_LSM.\n");
383 			break;
384 		case EOPNOTSUPP:
385 			fprintf(stderr,
386 				"Hint: Landlock is currently disabled. "
387 				"It can be enabled in the kernel configuration by "
388 				"prepending \"landlock,\" to the content of CONFIG_LSM, "
389 				"or at boot time by setting the same content to the "
390 				"\"lsm\" kernel parameter.\n");
391 			break;
392 		}
393 		return 1;
394 	}
395 
396 	/* Best-effort security. */
397 	switch (abi) {
398 	case 1:
399 		/*
400 		 * Removes LANDLOCK_ACCESS_FS_REFER for ABI < 2
401 		 *
402 		 * Note: The "refer" operations (file renaming and linking
403 		 * across different directories) are always forbidden when using
404 		 * Landlock with ABI 1.
405 		 *
406 		 * If only ABI 1 is available, this sandboxer knowingly forbids
407 		 * refer operations.
408 		 *
409 		 * If a program *needs* to do refer operations after enabling
410 		 * Landlock, it can not use Landlock at ABI level 1.  To be
411 		 * compatible with different kernel versions, such programs
412 		 * should then fall back to not restrict themselves at all if
413 		 * the running kernel only supports ABI 1.
414 		 */
415 		ruleset_attr.handled_access_fs &= ~LANDLOCK_ACCESS_FS_REFER;
416 		__attribute__((fallthrough));
417 	case 2:
418 		/* Removes LANDLOCK_ACCESS_FS_TRUNCATE for ABI < 3 */
419 		ruleset_attr.handled_access_fs &= ~LANDLOCK_ACCESS_FS_TRUNCATE;
420 		__attribute__((fallthrough));
421 	case 3:
422 		/* Removes network support for ABI < 4 */
423 		ruleset_attr.handled_access_net &=
424 			~(LANDLOCK_ACCESS_NET_BIND_TCP |
425 			  LANDLOCK_ACCESS_NET_CONNECT_TCP);
426 		__attribute__((fallthrough));
427 	case 4:
428 		/* Removes LANDLOCK_ACCESS_FS_IOCTL_DEV for ABI < 5 */
429 		ruleset_attr.handled_access_fs &= ~LANDLOCK_ACCESS_FS_IOCTL_DEV;
430 
431 		__attribute__((fallthrough));
432 	case 5:
433 		/* Removes LANDLOCK_SCOPE_* for ABI < 6 */
434 		ruleset_attr.scoped &= ~(LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET |
435 					 LANDLOCK_SCOPE_SIGNAL);
436 		__attribute__((fallthrough));
437 	case 6:
438 		/* Removes LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON for ABI < 7 */
439 		supported_restrict_flags &=
440 			~LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON;
441 		__attribute__((fallthrough));
442 	case 7:
443 	case 8:
444 		/* Removes LANDLOCK_ACCESS_FS_RESOLVE_UNIX for ABI < 9 */
445 		ruleset_attr.handled_access_fs &=
446 			~LANDLOCK_ACCESS_FS_RESOLVE_UNIX;
447 		/* Must be printed for any ABI < LANDLOCK_ABI_LAST. */
448 		fprintf(stderr,
449 			"Hint: You should update the running kernel "
450 			"to leverage Landlock features "
451 			"provided by ABI version %d (instead of %d).\n",
452 			LANDLOCK_ABI_LAST, abi);
453 		__attribute__((fallthrough));
454 	case LANDLOCK_ABI_LAST:
455 		break;
456 	default:
457 		fprintf(stderr,
458 			"Hint: You should update this sandboxer "
459 			"to leverage Landlock features "
460 			"provided by ABI version %d (instead of %d).\n",
461 			abi, LANDLOCK_ABI_LAST);
462 	}
463 	access_fs_ro &= ruleset_attr.handled_access_fs;
464 	access_fs_rw &= ruleset_attr.handled_access_fs;
465 
466 	/* Removes bind access attribute if not supported by a user. */
467 	env_port_name = getenv(ENV_TCP_BIND_NAME);
468 	if (!env_port_name) {
469 		ruleset_attr.handled_access_net &=
470 			~LANDLOCK_ACCESS_NET_BIND_TCP;
471 	}
472 	/* Removes connect access attribute if not supported by a user. */
473 	env_port_name = getenv(ENV_TCP_CONNECT_NAME);
474 	if (!env_port_name) {
475 		ruleset_attr.handled_access_net &=
476 			~LANDLOCK_ACCESS_NET_CONNECT_TCP;
477 	}
478 
479 	if (check_ruleset_scope(ENV_SCOPED_NAME, &ruleset_attr))
480 		return 1;
481 
482 	/* Enables optional logs. */
483 	env_force_log = getenv(ENV_FORCE_LOG_NAME);
484 	if (env_force_log) {
485 		if (strcmp(env_force_log, "1") != 0) {
486 			fprintf(stderr, "Unknown value for " ENV_FORCE_LOG_NAME
487 					" (only \"1\" is handled)\n");
488 			return 1;
489 		}
490 		if (!(supported_restrict_flags &
491 		      LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON)) {
492 			fprintf(stderr,
493 				"Audit logs not supported by current kernel\n");
494 			return 1;
495 		}
496 		set_restrict_flags |= LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON;
497 		unsetenv(ENV_FORCE_LOG_NAME);
498 	}
499 
500 	ruleset_fd =
501 		landlock_create_ruleset(&ruleset_attr, sizeof(ruleset_attr), 0);
502 	if (ruleset_fd < 0) {
503 		perror("Failed to create a ruleset");
504 		return 1;
505 	}
506 
507 	if (populate_ruleset_fs(ENV_FS_RO_NAME, ruleset_fd, access_fs_ro)) {
508 		goto err_close_ruleset;
509 	}
510 	if (populate_ruleset_fs(ENV_FS_RW_NAME, ruleset_fd, access_fs_rw)) {
511 		goto err_close_ruleset;
512 	}
513 
514 	if (populate_ruleset_net(ENV_TCP_BIND_NAME, ruleset_fd,
515 				 LANDLOCK_ACCESS_NET_BIND_TCP)) {
516 		goto err_close_ruleset;
517 	}
518 	if (populate_ruleset_net(ENV_TCP_CONNECT_NAME, ruleset_fd,
519 				 LANDLOCK_ACCESS_NET_CONNECT_TCP)) {
520 		goto err_close_ruleset;
521 	}
522 
523 	if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
524 		perror("Failed to restrict privileges");
525 		goto err_close_ruleset;
526 	}
527 	if (landlock_restrict_self(ruleset_fd, set_restrict_flags)) {
528 		perror("Failed to enforce ruleset");
529 		goto err_close_ruleset;
530 	}
531 	close(ruleset_fd);
532 
533 	cmd_path = argv[1];
534 	cmd_argv = argv + 1;
535 	fprintf(stderr, "Executing the sandboxed command...\n");
536 	execvpe(cmd_path, cmd_argv, envp);
537 	fprintf(stderr, "Failed to execute \"%s\": %s\n", cmd_path,
538 		strerror(errno));
539 	fprintf(stderr, "Hint: access to the binary, the interpreter or "
540 			"shared libraries may be denied.\n");
541 	return 1;
542 
543 err_close_ruleset:
544 	close(ruleset_fd);
545 	return 1;
546 }
547