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