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