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