int main()

in landlock/sandboxer.c [158:238]


int main(const int argc, char *const argv[], char *const *const envp)
{
	const char *cmd_path;
	char *const *cmd_argv;
	int ruleset_fd;
	struct landlock_ruleset_attr ruleset_attr = {
		.handled_access_fs = ACCESS_FS_ROUGHLY_READ |
			ACCESS_FS_ROUGHLY_WRITE,
	};

	if (argc < 2) {
		fprintf(stderr, "usage: %s=\"...\" %s=\"...\" %s <cmd> [args]...\n\n",
				ENV_FS_RO_NAME, ENV_FS_RW_NAME, argv[0]);
		fprintf(stderr, "Launch a command in a restricted environment.\n\n");
		fprintf(stderr, "Environment variables containing paths, "
				"each separated by a colon:\n");
		fprintf(stderr, "* %s: list of paths allowed to be used in a read-only way.\n",
				ENV_FS_RO_NAME);
		fprintf(stderr, "* %s: list of paths allowed to be used in a read-write way.\n",
				ENV_FS_RW_NAME);
		fprintf(stderr, "\nexample:\n"
				"%s=\"/bin:/lib:/usr:/proc:/etc:/dev/urandom\" "
				"%s=\"/dev/null:/dev/full:/dev/zero:/dev/pts:/tmp\" "
				"%s bash -i\n",
				ENV_FS_RO_NAME, ENV_FS_RW_NAME, argv[0]);
		return 1;
	}

	ruleset_fd = landlock_create_ruleset(&ruleset_attr, sizeof(ruleset_attr), 0);
	if (ruleset_fd < 0) {
		const int err = errno;

		perror("Failed to create a ruleset");
		switch (err) {
		case ENOSYS:
			fprintf(stderr, "Hint: Landlock is not supported by the current kernel. "
					"To support it, build the kernel with "
					"CONFIG_SECURITY_LANDLOCK=y and prepend "
					"\"landlock,\" to the content of CONFIG_LSM.\n");
			break;
		case EOPNOTSUPP:
			fprintf(stderr, "Hint: Landlock is currently disabled. "
					"It can be enabled in the kernel configuration by "
					"prepending \"landlock,\" to the content of CONFIG_LSM, "
					"or at boot time by setting the same content to the "
					"\"lsm\" kernel parameter.\n");
			break;
		}
		return 1;
	}
	if (populate_ruleset(ENV_FS_RO_NAME, ruleset_fd,
				ACCESS_FS_ROUGHLY_READ)) {
		goto err_close_ruleset;
	}
	if (populate_ruleset(ENV_FS_RW_NAME, ruleset_fd,
				ACCESS_FS_ROUGHLY_READ | ACCESS_FS_ROUGHLY_WRITE)) {
		goto err_close_ruleset;
	}
	if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
		perror("Failed to restrict privileges");
		goto err_close_ruleset;
	}
	if (landlock_restrict_self(ruleset_fd, 0)) {
		perror("Failed to enforce ruleset");
		goto err_close_ruleset;
	}
	close(ruleset_fd);

	cmd_path = argv[1];
	cmd_argv = argv + 1;
	execvpe(cmd_path, cmd_argv, envp);
	fprintf(stderr, "Failed to execute \"%s\": %s\n", cmd_path,
			strerror(errno));
	fprintf(stderr, "Hint: access to the binary, the interpreter or "
			"shared libraries may be denied.\n");
	return 1;

err_close_ruleset:
	close(ruleset_fd);
	return 1;
}