diff --git a/.github/workflows/build-privsep.yml b/.github/workflows/build-privsep.yml new file mode 100644 index 0000000000..7fb2529465 --- /dev/null +++ b/.github/workflows/build-privsep.yml @@ -0,0 +1,82 @@ +--- +# SPDX-License-Identifier: GPL-2.0-or-later +# +# This file is part of nvme. +# Copyright (c) 2026 SUSE LLC +# +# Authors: Daniel Wagner + +name: Build privsep + +# Privilege separation (Linux only) and the decoder sandbox (Linux and +# FreeBSD) are disabled by default for now. Build and test them here, so +# they do not bitrot: scripts/build.sh privsep. See Documentation/PRIVSEP.md. +on: + push: + branches: [master] + pull_request: + branches: [master] + + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + actions: read + contents: read + +jobs: + privsep-linux: + name: privsep and sandbox on Linux + runs-on: ubuntu-latest + container: + image: ghcr.io/linux-nvme/fedora:latest + steps: + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + # The privsep tests skip as root, and the sandbox runs in process + # under valgrind: run them as a user, without valgrind. + - name: Add a user for the tests + run: | + useradd -m ci + chown -R ci "$GITHUB_WORKSPACE" + - name: build + run: | + runuser -u ci -- scripts/build.sh -b debug -c gcc privsep + - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 + name: upload logs + if: failure() + with: + name: privsep logs files + path: | + .build-ci/meson-logs/*.txt + + # The FreeBSD VM is slow, so as build-freebsd.yml this runs only when + # master is updated, not on every pull request. + privsep-freebsd: + name: sandbox on FreeBSD + if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.repository == 'linux-nvme/nvme-cli') }} + runs-on: arc-vm-nvme-cli + steps: + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + repository: "linux-blktests/blktests-ci" + - name: Build and test nvme-cli in VM + id: build + uses: ./.github/actions/kubevirt-action + with: + container_disk_image: ghcr.io/linux-nvme/blktests-freebsd-containerdisk:next + distro: freebsd + run_cmds: | + set -e + set -x + uname -a + + sudo pkg install -y bash git meson ninja pkgconf json-c openssl + + git clone https://github.com/${{ github.repository }} nvme-cli + cd nvme-cli + git checkout ${{ github.sha }} + + bash scripts/build.sh -b debug -c cc privsep diff --git a/Documentation/PRIVSEP.md b/Documentation/PRIVSEP.md new file mode 100644 index 0000000000..ff5372586b --- /dev/null +++ b/Documentation/PRIVSEP.md @@ -0,0 +1,310 @@ + +# Privilege separation and the decoder sandbox + +nvme-cli decodes a lot of data it should not trust: whatever a device, or a +fabrics target, returns. Much of it runs as root, because opening +`/dev/nvme*` needs root. Two features reduce what a bug in that code can +do: + +- **Privilege separation** (`-Dprivsep`, Linux): when root runs nvme-cli on + behalf of a user (sudo), nvme-cli starts a small helper which keeps root, + drops its own privileges and sends the device commands through the helper. +- **The decoder sandbox** (`-Dsandbox`, Linux and FreeBSD): the printers + which decode device data run in a forked child process which can do + little more than allocate memory and write to stdout and stderr, whether + or not nvme-cli runs privileged. + +Both are technology previews and disabled by default. This document +describes the design for reviewers; the code is the source of truth. + +## Threat model + +The attacker controls the data a device (or a fabrics target) returns: +identify data, log pages, features. The goal is that a memory-safety bug in +the code of nvme-cli which decodes that data does not turn into root, and +not into access to other devices, files or processes either. Most of the +bugs fuzzing found were in these decoders. + +The command line, `nvme-cli.conf` and `--set-options` are not untrusted in +this sense: the user who runs nvme-cli controls the command line, and +`nvme-cli.conf` belongs to root. Their parsers run in process. + +Not a goal: + +- Restricting which NVMe commands a user may issue. A user who may run + `sudo nvme` may do anything to the NVMe devices; the helper passes every + admin and I/O command through. What the user loses is root outside of + the NVMe devices. +- setuid. A setuid nvme-cli is not supported: it keeps running as it was + started and never trusts the environment. +- Fabrics, keys, the registry and the other commands without a device + keep running as root for now (see "Which commands drop"). + +## Privilege separation + +### Components + +| Part | Where | Runs as | +|---|---|---| +| `nvme-privsep-helper` | `libnvme/privsep/helper.c`, installed into `libexecdir` | root | +| client and spawn API | `libnvme/src/privsep/` (`libnvme-privsep.h`) | the caller | +| wire protocol | `libnvme/src/privsep/privsep-proto.h` | both | +| decision, drop and attach | `src/privsep.c` | nvme-cli | + +The helper does as little as possible: it decodes request headers, checks +them, issues the ioctl or sysfs write through the public libnvme function +of the same name and returns the raw result. It never parses data a device +returned. nvme-cli, which does, runs unprivileged. + +### Lifecycle in nvme-cli + +`main()` in `src/nvme.c`: + +1. `plugin_lookup()` parses the global options in front of the command and + finds the command, without running anything. +2. `nvme_privsep_init()` decides, using only that result and the + environment: + - no command to run (help, version), a command marked `needs_root`, or + an MI device (`mctp:,`, which talks to MCTP sockets itself): + keep running as is; + - otherwise, if nvme-cli runs as real and effective root and not in + secure-execution mode, the target user is `SUDO_UID`/`SUDO_GID`, else + `NVME_PRIVSEP_UID`/`NVME_PRIVSEP_GID` (decimal only). Without either, + root keeps its privileges, so scripts and services are unchanged. +3. With a target: `libnvme_privsep_spawn()` starts the helper, then + `setgroups(1, &gid)`, `setresgid()`, `setresuid()`, and a check that + `setuid(0)` fails. The supplementary groups become the target group + only, because looking up the user's groups would run NSS as root. If the + helper cannot be started or the drop fails, nvme-cli exits with an error + instead of continuing as root. +4. Only now `setlocale()` runs, `nvme-cli.conf` is read (as the target + user, so the file has to be world-readable; it holds no secrets) and the + command parses its options. +5. Every global context nvme-cli creates gets the helper attached + (`nvme_privsep_attach()` → `libnvme_set_privsep()`), so `libnvme_open()` + returns helper-backed handles transparently. + +The drop happens before any configuration or option parsing, so as little +code as possible runs as root. + +### Which commands drop + +`struct command` has an opt-out flag, `.needs_root`. Commands drop by +default. The commands marked are the ones without a device argument +(fabrics, enumeration, keys, exclusions, configuration, registry, NBFT) and +the device commands which also touch PCI config space, the kernel log or +root-owned paths. The list doubles as the to-do list for dropping +everywhere. Should a deprecated command forward to a `needs_root` one after +the drop, `nvme_privsep_check()` refuses to run it. + +### The helper channel + +`libnvme_privsep_spawn()` creates an `AF_UNIX` `SOCK_STREAM` socketpair, +forks, puts the helper's end on fd 3 (`LIBNVME_PRIVSEP_FD`), closes all +other descriptors and `exec`s the helper. The helper inherits the caller's +credentials, which is why nvme-cli spawns it before dropping. The client +then sends `HELLO` and checks the protocol version. The helper reopens fds +0-2 on `/dev/null` if they were closed, so a device is never opened as +stdin or stdout. + +Helper-backed transport handles have `fd = -1` and no io_uring. Each +libnvme function that has a helper path has a single +`if (hdl->type == PRIVSEP)` (or `ctx->privsep`) branch. MI keeps its own +path. + +### Wire protocol + +Same host, same build: host byte order, the host's errno values and +`open()` flags, no versioning beyond `HELLO` (version 1 until released). +Each request is a `struct libnvme_privsep_req` (op, handle id, payload +length) plus payload. Each response is a `struct libnvme_privsep_resp` +(status, length, result) plus payload. The helper answers in order. A +broken stream makes the channel unusable; the client does not retry. + +| Op | Handle | Payload → response | +|---|---|---| +| `HELLO` | 0 | → result = version | +| `OPEN` | 0 | flags, options, name → handle id, `S_IFCHR`/`S_IFBLK` | +| `CLOSE` | h | – | +| `ADMIN`, `IO` | h | command (+ data and metadata for host-to-controller opcodes) → CQE result (+ data for reads) | +| `RESET_CTRL`, `RESET_SUBSYSTEM`, `RESCAN_NS`, `GET_NSID`, `REREAD_PARTITIONS`, `UPDATE_BLOCK_SIZE` | h | the libnvme function of the same name | +| `READ_REGS`, `WRITE_REG32`, `WRITE_REG64` | h | offset and length (reads ≤ 4 KiB) | +| `SED` | h | one of the `IOC_OPAL_*` requests `sed-linux.c` uses (nine, three of them depending on the kernel headers), with its fixed-size argument; namespaces only; the payload is wiped after use | +| `FABRICS` | 0 | connect string → kernel reply; result = failed step | +| `DELETE_CTRL` | 0 | `nvmeX` → writes `delete_controller` | + +Checks in the helper: `HELLO` first; payloads ≤ 8 MiB + 4 KiB; device names +`nvmeX`, `nvmeXnY`, `ngXnY` (optionally with `/dev/`); open flags limited to +the access mode and `O_EXCL`; unknown `OPEN` options rejected; data lengths +must match the payload; buffers are page-aligned like nvme-cli's; at most +64 open handles. `LIBNVME_PRIVSEP_OPEN_NO_IOCTL_PROBING` +carries `--no-ioctl-probing`: the helper opens such handles in a context +without 64-bit ioctl probing. + +## The decoder sandbox + +### Why, in addition to privilege separation + +- Plain root without `SUDO_UID` keeps root, and so do the `needs_root` + commands. Their decoders run as root. +- With privilege separation, the unprivileged nvme-cli still holds the + socket to the helper, which issues any NVMe command, including format, + sanitize and firmware commit. A decoder that is taken over could use it. +- A decoder that crashes takes nvme-cli down with it. + +In the sandbox, a decoder can't open files or use the helper socket, and a +crash only takes the child down. + +### The primitive + +```c +int shr_sandbox_begin(struct shr_sandbox_output *out); +void shr_sandbox_end(const void *buf, size_t len); +``` + +``` +caller child (fork: same memory) +------ ----- +fflush(stdout, stderr) +pipe(), fork() ───────────────────────► close all fds but 0-2 and the pipe (on fd 3) + enter seccomp / Capsicum +read 'S' ◄────────────────────────────── write 'S' ("I am sandboxed") + begin() returns SHR_SANDBOX_CHILD + run the decoder: reads the data in + its copy of memory, prints itself + shr_sandbox_end(result, len) +read the length and the result ◄──────── write them, _exit(0) +expect EOF, waitpid() +begin() returns SHR_SANDBOX_DONE +``` + +The child sees the memory of the caller as it was at the fork, so it reads +the device data without copying it. Whatever else it changes is lost; only +its output on stdout and stderr and the one result it hands to +`shr_sandbox_end()` remain. The caller treats that result as untrusted. + +**Sandbox off** (the default; under valgrind; Windows; or called in the +sandbox already): `shr_sandbox_begin()` returns `SHR_SANDBOX_OFF` and the +caller runs the code itself. + +Errors: a child that could not enter the sandbox reports it with a special +exit status *before* it sends the marker, and only then does +`shr_sandbox_begin()` return `SHR_SANDBOX_OFF`. Anything else (a missing +marker, a result over 64 MiB, data after the result, a crash, a non-zero +exit) is an error. + +### The printers + +The hook is the `nvme_print()` macro in `src/nvme-print.c`, which all +`nvme_show_*()` functions use, including the ones of the log plugin: + +```c +if (nvme_print_check(ops, ops->name) && nvme_print_begin(ops, ops->name)) { + ops->name(__VA_ARGS__); + nvme_print_end(ops); +} +``` + +`nvme_print_begin()` returns false in the caller once a sandboxed child +has printed. Printers that the sandboxed printer calls itself (e.g. the +hex dump) run inline in the same child, and so do the status and error +messages they print, which do not use the macro. + +Some printers stay in process (`nvme_print_sandboxed()`): + +- the libnvme tree printers (`list`, `list-subsys`, `show-topology`, + `relatives`), which read sysfs while they print and decode no device + data; +- the ZNS zone list printers, which hand JSON objects to their caller; +- `top`, which is interactive, and `config_conn_list`; +- `show_init`/`show_finish`, and the status and error messages, unless + a sandboxed printer prints them. + +If a sandboxed printer fails, nvme-cli says so ("the decoder of the device +data crashed or misbehaved in the sandbox") and exits with an error. + +### JSON output + +A command prints one JSON document: `parse_args()` calls +`nvme_show_init()`, the printers add members to it (`json_r`), and +`nvme_show_finish()` prints it. In process nothing changes. A sandboxed +child, though, has only a copy of the document, and what it adds is lost. + +`struct print_ops` therefore has optional capture hooks, which +`nvme_print_begin()` and `nvme_print_end()` call around a sandboxed +printer. The dispatcher hands the result over as it is; only the output +plugin knows what it contains. Plugins which write to stdout, as the +child can, leave them unset. The JSON plugin implements them: + +1. `capture_begin()`, in the child: the printer call gets an object of + its own as `json_r`; printers it calls write to the same object; +2. `capture_end()`, in the child: its members are serialized, as pairs of + a length and the key, a length and the value; +3. `capture_add()`, in the caller: they are added to the document as raw + text, with a serializer that re-indents them to their level. A member + replaces one of the same key, as when the printer runs in process. + +The text is not parsed again. A parse would turn 128-bit numbers, which +nvme-cli prints as bare JSON numbers, into doubles. Only the framing is +checked: the child can write anything to stdout, so a raw member in the +JSON document gives it nothing new. + +### The sandbox itself + +- **Descriptors:** the child keeps only fds 0-2 and the result pipe, so it + cannot reach the privsep helper socket or any device. It closes the others + with `close_range()`, else those listed in `/proc/self/fd` (Linux) or + with `closefrom()` (FreeBSD); a loop up to the limit would miss those + above a lowered limit. If it cannot close them, it fails. nvme-cli opens + `/dev/null` on closed standard descriptors at its start, so none of them + is the helper socket or a device. +- **Linux:** `PR_SET_NO_NEW_PRIVS` and a seccomp BPF filter. A wrong + architecture (and x32) kills the process. Allowed: `write`, `writev`, + memory management (`brk`, `mmap`, `munmap`, `mremap`, `madvise`), + `fstat`, `getrandom`, `futex`, signals and `tgkill()` to the child itself + (for `abort()`), `getpid`, `gettid`, `exit`, `exit_group`, and `ioctl()` + only for `TCGETS`, `TCGETS2` and `TIOCGWINSZ` (terminal queries for + `isatty()` and line wrapping). Other ioctls fail with `ENOTTY`, and every + other system call fails with `EPERM`, so that libc degrades gracefully + (e.g. `gettext()` without its catalog). +- **FreeBSD:** the rights of fds 0-3 are limited to write, `fstat` and the + terminal ioctls, then `cap_enter()`. +- The sandbox must be entered while the process runs a single thread. +- libc loads some data on first use, which the child could not read. The + caller loads the time zone (`tzset()`) before the fork, so times print + the same in the child. +- Cost: under 1 ms per printed object (fork, seccomp, JSON splicing). + +### Switches + +- `-Dsandbox=enabled` turns it on by default. `NVME_SANDBOX=0` turns it off + (e.g. for a debugger); `NVME_SANDBOX=1` turns it on in any build. + +### Not covered + +- Size and offset handling in the command code that fetches the data, + before it is printed (e.g. a log read in parts). +- Vendor plugins that decode inside the command instead of through + `nvme_show_*()`. Each needs its decoding split from the fetching. +- The printers that stay in process (see above). + +## Testing + +- libnvme: `libnvme/tests/privsep/` (helper protocol, handles, ioctl + probing). +- nvme-cli: `nvme-cli - privsep` (the helper is used and opens the + devices; `needs_root`, MI, help and version don't drop), and every mock + CLI test runs a second time through the helper (`-privsep`) and in + the sandbox (`-sandbox`). `NVME_PRIVSEP_TEST_HELPER` names a helper + an unprivileged nvme-cli uses as well; it is ignored as root and in + secure-execution mode. +- Sandbox: `shared - sandbox-util` (results, fallback, nesting, denied + system calls, descriptors, terminal queries, malformed and oversized + results, crashes), `print-sandbox-compare`, which runs the decoders of + the print test on random device data with and without the sandbox and + requires the same exit status, stdout and stderr, and a check in the + print test that the sandbox is used. +- CI: both are disabled by default, `scripts/build.sh privsep` enables + them and runs the tests (as a user, the privsep tests skip as root). + The `Build privsep` workflow runs it on Linux and, with the sandbox + only, on FreeBSD. diff --git a/Documentation/TESTING.md b/Documentation/TESTING.md index 1f10af6252..22a9f4109a 100644 --- a/Documentation/TESTING.md +++ b/Documentation/TESTING.md @@ -79,6 +79,14 @@ The GitHub Actions workflow uses `scripts/build.sh`. To reproduce the CI build l ./scripts/build.sh ``` +Privilege separation and the decoder sandbox are disabled by default and +have their own config, which runs the tests as a user (the privsep tests +skip as root), see [PRIVSEP.md](PRIVSEP.md): + +```bash +./scripts/build.sh privsep +``` + Build artifacts remain inside the container unless a host volume is mounted. ### 5. Cross-Build Example diff --git a/README.md b/README.md index 805dcfe418..d7eb13ba21 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,7 @@ summary with `nvme help`. | Configuring host identity, NVMe-oF connections, and multi-orchestrator coordination | [CONFIGURATION.md](Documentation/CONFIGURATION.md) | | Pre-built binaries, reproducing CI builds, memory/sanitizer testing | [TESTING.md](Documentation/TESTING.md) | | libnvme coverage against NVMe specifications, chapter by chapter | [SPEC-COVERAGE.md](Documentation/SPEC-COVERAGE.md) | +| Privilege separation and the decoder sandbox: design, threat model, helper protocol | [PRIVSEP.md](Documentation/PRIVSEP.md) | | Command/plugin man pages | `man nvme`, or browse [Documentation](Documentation/) | | Contributing: adding commands/plugins, API naming, commit & PR workflow | [CONTRIBUTING.md](CONTRIBUTING.md) | | Reporting security vulnerabilities | [SECURITY.md](SECURITY.md) | diff --git a/SECURITY.md b/SECURITY.md index 47e90b8585..977154ffd8 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -43,6 +43,11 @@ This policy applies only to vulnerabilities in the source code of this repository. Issues related to third-party dependencies should be reported to the respective upstream projects. +The threat model in [PRIVSEP.md](Documentation/PRIVSEP.md#threat-model) +describes which inputs nvme-cli treats as untrusted, the data a device or a +fabrics target returns, and what privilege separation and the decoder sandbox +protect against. It helps to judge whether an issue crosses a trust boundary. + Thank you for helping improve the security of this project. diff --git a/meson.build b/meson.build index 08660288f5..6c4a9c3d8e 100644 --- a/meson.build +++ b/meson.build @@ -81,6 +81,9 @@ want_mi = get_option('mi').require(host_system == 'linux', want_sed = get_option('sed').allowed() want_privsep = get_option('privsep').require(host_system == 'linux', error_message: 'privsep requires Linux').allowed() +want_sandbox = get_option('sandbox').require( + host_system == 'linux' or host_system == 'freebsd', + error_message: 'sandbox requires Linux or FreeBSD').allowed() want_top = get_option('top').require(host_system == 'linux', error_message: 'top requires Linux').allowed() discoverd_opt = get_option('nvme-discoverd').require(want_fabrics, @@ -201,6 +204,8 @@ conf.set('CONFIG_MI', want_mi, description: 'Is MI enabled') conf.set('CONFIG_SED', want_sed, description: 'Is SED enabled') conf.set('CONFIG_PRIVSEP', want_privsep, description: 'Is the privilege separation helper enabled') +conf.set('CONFIG_SANDBOX', want_sandbox, + description: 'Are the decoders of device data sandboxed by default') conf.set('LIBNVME_PRIVSEP_HELPER', '"@0@"'.format(libexecdir / 'nvme-privsep-helper')) conf.set('CONFIG_LOOPBACK', want_ioctl_tests, @@ -1005,6 +1010,7 @@ wanted_dict = { 'libnvme': want_libnvme, 'fabrics': want_fabrics, 'privsep': want_privsep, + 'sandbox': want_sandbox, 'nvme-discoverd': want_discoverd, 'mdns': want_mdns, 'nvme-keysd': want_keysd, diff --git a/meson_options.txt b/meson_options.txt index b985141d34..1a9e660533 100644 --- a/meson_options.txt +++ b/meson_options.txt @@ -35,6 +35,12 @@ option( value: 'disabled', description : 'privilege separation helper (technology preview; Linux only)' ) +option( + 'sandbox', + type : 'feature', + value: 'disabled', + description : 'decode the data devices return in a sandboxed child process (technology preview; Linux and FreeBSD)' +) option( 'nvme-discoverd', type : 'feature', diff --git a/scripts/build.sh b/scripts/build.sh index abb9e6e12e..f84b3cebf2 100755 --- a/scripts/build.sh +++ b/scripts/build.sh @@ -58,6 +58,9 @@ usage() { echo " [default] default settings" echo " libdbus build with libdbus" echo " liburing build with liburing" + echo " privsep build with privilege separation (Linux) and the" + echo " decoder sandbox; run the tests as a user, the" + echo " privsep tests skip as root" echo " fallback download all dependencies" echo " and build them as shared libraries" echo " cross use cross toolchain to build" @@ -318,6 +321,28 @@ config_meson_liburing() { "${BUILDDIR}" } +# Privilege separation (Linux only) and the decoder sandbox are disabled by +# default for now, this config builds and tests them. +config_meson_privsep() { + local extra_args=() + + if [ "$(uname -s)" = Linux ]; then + # NVME_PRIVSEP_TEST_HELPER, which the tests use, is ignored as root + if [ "$(id -u)" -eq 0 ]; then + echo "error: run the privsep config as a user, not as root" >&2 + exit 1 + fi + extra_args+=(-Dprivsep=enabled) + fi + + CC="${CC}" "${MESON}" setup \ + --werror \ + --buildtype="${BUILDTYPE}" \ + -Dsandbox=enabled \ + "${extra_args[@]}" \ + "${BUILDDIR}" +} + config_meson_fallback() { CC="${CC}" "${MESON}" setup \ --werror \ diff --git a/shared/io-util.h b/shared/io-util.h index 845b3a9ed8..c41c2c75d1 100644 --- a/shared/io-util.h +++ b/shared/io-util.h @@ -33,6 +33,31 @@ static inline int shr_write_all(int fd, const void *buf, size_t len) return 0; } +/* + * Read up to len bytes, stopping early only at EOF, for binary data. + * Return: the number of bytes read, or -errno on a read failure. + */ +static inline ssize_t shr_read_full(int fd, void *buf, size_t len) +{ + char *p = buf; + size_t total = 0; + ssize_t n; + + while (total < len) { + n = read(fd, p + total, len - total); + if (n < 0) { + if (errno == EINTR) + continue; + return -errno; + } + if (n == 0) + break; + total += (size_t)n; + } + + return total; +} + /* * Read fd into out until EOF, keeping at most out_len - 1 bytes * (NUL-terminated) and discarding any excess. Always reads to EOF so a writer diff --git a/shared/meson.build b/shared/meson.build index 9ab8ec9a94..b12f36ae45 100644 --- a/shared/meson.build +++ b/shared/meson.build @@ -37,6 +37,7 @@ if host_system == 'windows' 'fs-util-win.c', 'crypto-util-win.c', 'proc-util-win.c', + 'sandbox-util-win.c', 'sig-util-win.c', 'term-util-win.c', ] @@ -48,6 +49,7 @@ else 'pci-util-linux.c', 'crypto-util-linux.c', 'proc-util-linux.c', + 'sandbox-util.c', 'sig-util-linux.c', 'term-util-linux.c', ] diff --git a/shared/sandbox-util-win.c b/shared/sandbox-util-win.c new file mode 100644 index 0000000000..9213d5796b --- /dev/null +++ b/shared/sandbox-util-win.c @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +/* + * This file is part of nvme-cli. + * Copyright (c) 2026 SUSE Software Solutions + * + * Authors: Daniel Wagner + */ +#include + +#include "sandbox-util.h" + +/* Windows has no fork(), so the code runs in process. */ +void shr_sandbox_enable(bool enable) +{ +} + +int shr_sandbox_begin(struct shr_sandbox_output *out) +{ + *out = (struct shr_sandbox_output){}; + return SHR_SANDBOX_OFF; +} + +void shr_sandbox_end(const void *buf, size_t len) +{ + abort(); +} diff --git a/shared/sandbox-util.c b/shared/sandbox-util.c new file mode 100644 index 0000000000..15d007842b --- /dev/null +++ b/shared/sandbox-util.c @@ -0,0 +1,439 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +/* + * This file is part of nvme-cli. + * Copyright (c) 2026 SUSE Software Solutions + * + * Authors: Daniel Wagner + */ +#include +#include +#include +#include +#include +#include +#include + +#include + +#if defined(__linux__) +#include +#endif + +#if defined(__linux__) +#include +#include +#include +#include +#include +#ifdef TCGETS2 +#include /* struct termios2 */ +#else +#include /* struct termios, e.g. of TCGETS on powerpc */ +#endif +#include +#include +#elif defined(__FreeBSD__) +#include +#include +#include +#endif + +#include + +#include "io-util.h" +#include "sandbox-util.h" + +/* Exit status of a child which found no sandbox to enter. */ +#define SANDBOX_UNAVAILABLE 125 + +/* Sent by the child once it runs sandboxed. */ +#define SANDBOX_MARKER 'S' + +/* The result pipe in the child. */ +#define SANDBOX_FD 3 + +static bool sandbox_enabled; + +/* Set in the child, which is sandboxed already. */ +static bool in_sandbox; + +void shr_sandbox_enable(bool enable) +{ + sandbox_enabled = enable; +} + +#if defined(__linux__) +/* + * The open descriptors are listed in /proc, a loop up to the limit would + * miss those above a limit lowered after they were opened. + */ +static int close_from(int low) +{ + struct dirent *de; + DIR *dir; + int fd; + + dir = opendir("/proc/self/fd"); + if (!dir) + return -errno; + while ((de = readdir(dir))) { + fd = atoi(de->d_name); + if (fd >= low && fd != dirfd(dir)) + close(fd); + } + closedir(dir); + + return 0; +} +#elif defined(__FreeBSD__) +static int close_from(int low) +{ + closefrom(low); + return 0; +} +#else +static int close_from(int low) +{ + return -EOPNOTSUPP; +} +#endif + +/* The child keeps stdio and the result pipe only. */ +static int keep_fds(int fd) +{ + if (fd != SANDBOX_FD && dup2(fd, SANDBOX_FD) < 0) + return -errno; +#if defined(NVME_HAVE_CLOSE_RANGE) && !defined(SANDBOX_NO_CLOSE_RANGE) + if (!close_range(SANDBOX_FD + 1, ~0U, 0)) + return 0; +#endif + return close_from(SANDBOX_FD + 1); +} + +#if defined(__linux__) + +#if defined(__x86_64__) +#define SANDBOX_AUDIT_ARCH AUDIT_ARCH_X86_64 +#elif defined(__i386__) +#define SANDBOX_AUDIT_ARCH AUDIT_ARCH_I386 +#elif defined(__aarch64__) +#define SANDBOX_AUDIT_ARCH AUDIT_ARCH_AARCH64 +#elif defined(__arm__) +#define SANDBOX_AUDIT_ARCH AUDIT_ARCH_ARM +#elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ +#define SANDBOX_AUDIT_ARCH AUDIT_ARCH_PPC64LE +#elif defined(__powerpc64__) +#define SANDBOX_AUDIT_ARCH AUDIT_ARCH_PPC64 +#elif defined(__s390x__) +#define SANDBOX_AUDIT_ARCH AUDIT_ARCH_S390X +#elif defined(__riscv) && __riscv_xlen == 64 +#define SANDBOX_AUDIT_ARCH AUDIT_ARCH_RISCV64 +#elif defined(__loongarch64) +#define SANDBOX_AUDIT_ARCH AUDIT_ARCH_LOONGARCH64 +#endif + +#ifdef SANDBOX_AUDIT_ARCH +struct filter { + struct sock_filter insn[64]; + unsigned int len; +}; + +static void emit(struct filter *f, struct sock_filter insn) +{ + if (f->len < ARRAY_SIZE(f->insn)) + f->insn[f->len] = insn; + f->len++; +} + +static void ret(struct filter *f, __u32 action) +{ + emit(f, (struct sock_filter)BPF_STMT(BPF_RET | BPF_K, action)); +} + +/* Loads the 32 bit word at @off of struct seccomp_data. */ +static void load(struct filter *f, __u32 off) +{ + emit(f, (struct sock_filter)BPF_STMT(BPF_LD | BPF_W | BPF_ABS, off)); +} + +static void jump_eq(struct filter *f, __u32 k, __u8 jt, __u8 jf) +{ + emit(f, (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, k, + jt, jf)); +} + +/* Allows the system call, or the argument, in the accumulator. */ +static void allow(struct filter *f, __u32 k) +{ + jump_eq(f, k, 0, 1); + ret(f, SECCOMP_RET_ALLOW); +} + +/* The kernel takes ioctl requests and pids as 32 bit, the low word. */ +#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ +#define ARG_LOW(n) (offsetof(struct seccomp_data, args[n]) + 4) +#else +#define ARG_LOW(n) offsetof(struct seccomp_data, args[n]) +#endif +#endif /* SANDBOX_AUDIT_ARCH */ + +/* + * Memory management, writes, the terminal queries of stdio and word + * wrapping, random numbers (hash tables seed themselves), exit, and what + * abort() and the runtime of sanitizers need. Signals go to the child + * itself only. Other system calls fail with EPERM, so that libc falls + * back gracefully, e.g. gettext() when it cannot open a message catalog. + * + * Return: 0, -EOPNOTSUPP without seccomp support, or another negative + * error code. + */ +static int sandbox_enter(void) +{ +#ifdef SANDBOX_AUDIT_ARCH + struct filter f = { .len = 0 }; + struct sock_fprog prog; + + load(&f, offsetof(struct seccomp_data, arch)); + jump_eq(&f, SANDBOX_AUDIT_ARCH, 1, 0); + ret(&f, SECCOMP_RET_KILL_PROCESS); + load(&f, offsetof(struct seccomp_data, nr)); +#ifdef __X32_SYSCALL_BIT + emit(&f, (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JGE | BPF_K, + __X32_SYSCALL_BIT, 0, 1)); + ret(&f, SECCOMP_RET_KILL_PROCESS); +#endif + + allow(&f, __NR_write); + allow(&f, __NR_writev); + allow(&f, __NR_brk); +#ifdef __NR_mmap + allow(&f, __NR_mmap); +#endif +#ifdef __NR_mmap2 + allow(&f, __NR_mmap2); +#endif + allow(&f, __NR_munmap); + allow(&f, __NR_mremap); + allow(&f, __NR_madvise); +#ifdef __NR_fstat + allow(&f, __NR_fstat); +#endif +#ifdef __NR_newfstatat + allow(&f, __NR_newfstatat); +#endif +#ifdef __NR_fstatat64 + allow(&f, __NR_fstatat64); +#endif +#ifdef __NR_getrandom + allow(&f, __NR_getrandom); +#endif + allow(&f, __NR_sigaltstack); +#ifdef __NR_futex + allow(&f, __NR_futex); +#endif +#ifdef __NR_futex_time64 + allow(&f, __NR_futex_time64); +#endif + allow(&f, __NR_sched_yield); + allow(&f, __NR_rt_sigprocmask); + allow(&f, __NR_rt_sigreturn); + allow(&f, __NR_getpid); + allow(&f, __NR_gettid); + allow(&f, __NR_exit); + allow(&f, __NR_exit_group); + + /* tgkill() of the child itself, for abort(); skips 4 if not. */ + jump_eq(&f, __NR_tgkill, 0, 4); + load(&f, ARG_LOW(0)); + allow(&f, getpid()); + ret(&f, SECCOMP_RET_ERRNO | EPERM); + + /* ioctl() for the terminal queries only. */ + jump_eq(&f, __NR_ioctl, 1, 0); + ret(&f, SECCOMP_RET_ERRNO | EPERM); + load(&f, ARG_LOW(1)); + allow(&f, TCGETS); +#ifdef TCGETS2 + allow(&f, TCGETS2); /* isatty() of glibc 2.42 and later */ +#endif + allow(&f, TIOCGWINSZ); + ret(&f, SECCOMP_RET_ERRNO | ENOTTY); + + if (f.len > ARRAY_SIZE(f.insn)) + return -E2BIG; + + prog.len = f.len; + prog.filter = f.insn; + /* Without seccomp filter support, PR_SET_SECCOMP fails with EINVAL. */ + if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) || + prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog, 0, 0)) + return errno == EINVAL ? -EOPNOTSUPP : -errno; + + return 0; +#else + return -EOPNOTSUPP; +#endif +} + +#elif defined(__FreeBSD__) + +/* Limits a descriptor to writes and the terminal queries. */ +static int limit_fd(int fd) +{ + static const unsigned long cmds[] = { TIOCGETA, TIOCGWINSZ }; + cap_rights_t rights; + + cap_rights_init(&rights, CAP_WRITE, CAP_FSTAT, CAP_IOCTL); + if (cap_rights_limit(fd, &rights) && errno != EBADF) + return -errno; + if (cap_ioctls_limit(fd, cmds, ARRAY_SIZE(cmds)) && errno != EBADF) + return -errno; + + return 0; +} + +static int sandbox_enter(void) +{ + int fd, err; + + if (!feature_present("security_capability_mode")) + return -EOPNOTSUPP; + + for (fd = 0; fd <= SANDBOX_FD; fd++) { + err = limit_fd(fd); + if (err) + return err; + } + if (cap_enter()) + return -errno; + + return 0; +} + +#else + +static int sandbox_enter(void) +{ + return -EOPNOTSUPP; +} + +#endif + +/* valgrind runs in the child too, where the sandbox stops it. */ +static bool under_valgrind(void) +{ + const char *preload = getenv("LD_PRELOAD"); + + return preload && strstr(preload, "vgpreload"); +} + +/* The output of a child of shr_sandbox_begin(), at most. */ +#define SANDBOX_MAX_OUTPUT (64 * 1024 * 1024) + +/* Return: 0 with the output in @out, or a negative error code. */ +static int sandbox_read_output(int fd, struct shr_sandbox_output *out) +{ + uint64_t len; + char c; + + if (shr_read_full(fd, &len, sizeof(len)) != sizeof(len) || + len > SANDBOX_MAX_OUTPUT) + return -EPROTO; + out->buf = malloc(len ? len : 1); + if (!out->buf) + return -ENOMEM; + if (shr_read_full(fd, out->buf, len) != (ssize_t)len || + shr_read_full(fd, &c, 1) != 0) { + free(out->buf); + out->buf = NULL; + return -EPROTO; + } + out->len = len; + + return 0; +} + +int shr_sandbox_begin(struct shr_sandbox_output *out) +{ + char marker = SANDBOX_MARKER; + int fds[2], status, err; + ssize_t n; + pid_t pid; + + *out = (struct shr_sandbox_output){}; + if (!sandbox_enabled || in_sandbox || under_valgrind()) + return SHR_SANDBOX_OFF; + + /* The child would write out the buffered output a second time. */ + fflush(stdout); + fflush(stderr); + /* libc loads the time zone on first use, the child cannot read it */ + tzset(); + + if (pipe(fds)) + return -errno; + + pid = fork(); + if (pid < 0) { + err = -errno; + close(fds[0]); + close(fds[1]); + return err; + } + if (!pid) { + close(fds[0]); + err = keep_fds(fds[1]); + if (!err) + err = sandbox_enter(); + if (err) + _exit(err == -EOPNOTSUPP ? SANDBOX_UNAVAILABLE : 1); + in_sandbox = true; + if (shr_write_all(SANDBOX_FD, &marker, 1)) + _exit(1); + return SHR_SANDBOX_CHILD; + } + close(fds[1]); + + err = -EPROTO; + n = shr_read_full(fds[0], &marker, 1); + if (n == 1 && marker == SANDBOX_MARKER) + err = sandbox_read_output(fds[0], out); + close(fds[0]); + + while (waitpid(pid, &status, 0) < 0) + if (errno != EINTR) { + err = -ECHILD; + break; + } + + /* Only a child which did not enter the sandbox may report that. */ + if (n == 0) + return WIFEXITED(status) && + WEXITSTATUS(status) == SANDBOX_UNAVAILABLE ? + SHR_SANDBOX_OFF : -ECHILD; + if (!err && (!WIFEXITED(status) || WEXITSTATUS(status))) + err = -ECHILD; + if (err) { + free(out->buf); + *out = (struct shr_sandbox_output){}; + return err; + } + + return SHR_SANDBOX_DONE; +} + +void shr_sandbox_end(const void *buf, size_t len) +{ + uint64_t n = len; + + /* The buffers hold output of the child only. */ + fflush(stdout); + fflush(stderr); + + if (shr_write_all(SANDBOX_FD, &n, sizeof(n)) || + (len && shr_write_all(SANDBOX_FD, buf, len))) + _exit(1); + + /* _exit() skips the atexit handlers of the caller. */ + _exit(0); +} diff --git a/shared/sandbox-util.h b/shared/sandbox-util.h new file mode 100644 index 0000000000..82fe5f763f --- /dev/null +++ b/shared/sandbox-util.h @@ -0,0 +1,95 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* + * This file is part of nvme-cli. + * Copyright (c) 2026 SUSE Software Solutions + * + * Authors: Daniel Wagner + */ +#pragma once + +#include +#include + +/* + * Runs code which handles untrusted data, e.g. a decoder of data a device + * returned, in a forked child process which can only allocate memory, + * write to stdout and stderr and exit: seccomp on Linux, Capsicum on + * FreeBSD. The child closes all other descriptors first, so it cannot + * reach e.g. the privsep helper. + * + * struct shr_sandbox_output out; + * + * switch (shr_sandbox_begin(&out)) { + * case SHR_SANDBOX_OFF: // no sandbox: run it here + * decode(data); + * break; + * case SHR_SANDBOX_CHILD: // in the sandbox + * decode(data); + * shr_sandbox_end(result, len); + * case SHR_SANDBOX_DONE: // the child ran it, out has its result + * use(out.buf, out.len); + * free(out.buf); + * break; + * default: // the child failed, e.g. crashed + * ... + * } + * + * The child sees the memory of the caller as it was at the fork, so it + * can read the data without copying it. What it changes is lost, except + * its output on stdout and stderr and the result it hands to + * shr_sandbox_end(). The caller must treat that result as untrusted, as + * the child may have been taken over. + * + * Call it only while the process runs a single thread. Keep the standard + * descriptors open from the start of the program, e.g. on /dev/null: the + * child keeps them, whatever a descriptor opened while one was closed + * refers to. + * + * See Documentation/PRIVSEP.md for the design. + */ + +/* + * shr_sandbox_enable() - Enable or disable the sandbox + * @enable: whether to run the code sandboxed, where supported + * + * Disabled by default. + */ +void shr_sandbox_enable(bool enable); + +/* What shr_sandbox_begin() returns, unless it fails. */ +enum shr_sandbox_where { + SHR_SANDBOX_OFF, /* no sandbox: run the code in process */ + SHR_SANDBOX_CHILD, /* in the sandbox: run the code, then end */ + SHR_SANDBOX_DONE, /* in the caller: the child ran the code */ +}; + +/* What the child handed to shr_sandbox_end(), malloc()ed. */ +struct shr_sandbox_output { + void *buf; + size_t len; +}; + +/* + * shr_sandbox_begin() - Run the code which follows sandboxed + * @out: on SHR_SANDBOX_DONE, the result of the child, to free() + * + * Forks a child which enters the sandbox and returns SHR_SANDBOX_CHILD. + * The child runs the code and calls shr_sandbox_end(). The caller waits + * for the child and returns SHR_SANDBOX_DONE. Returns SHR_SANDBOX_OFF, + * and the caller runs the code itself, when the sandbox is disabled, not + * supported by the system, e.g. under valgrind, or when called in the + * sandbox already. + * + * Return: a value of enum shr_sandbox_where, or a negative error code if + * the child failed: it crashed, exited without shr_sandbox_end() or wrote + * a malformed result. + */ +int shr_sandbox_begin(struct shr_sandbox_output *out); + +/* + * shr_sandbox_end() - End the child of shr_sandbox_begin() + * @buf: result for the caller, may be NULL + * @len: length of @buf, at most 64 MiB + */ +void shr_sandbox_end(const void *buf, size_t len) + __attribute__((noreturn)); diff --git a/shared/tests/meson.build b/shared/tests/meson.build index 1558cbf26b..4071fe78ee 100644 --- a/shared/tests/meson.build +++ b/shared/tests/meson.build @@ -312,6 +312,36 @@ test_sig_util = executable( test('shared - sig-util', test_sig_util, suite: 'unit') +if host_system != 'windows' + test_sandbox_util = executable( + 'test-sandbox-util', + ['test-sandbox-util.c'], + dependencies: [ + ccan_dep, + config_dep, + shared_dep, + ], + ) + + test('shared - sandbox-util', test_sandbox_util, suite: 'unit') + + # The same without close_range(), which closes the descriptors otherwise + test_sandbox_util_fallback = executable( + 'test-sandbox-util-fallback', + ['test-sandbox-util.c', '../sandbox-util.c'], + c_args: ['-DSANDBOX_NO_CLOSE_RANGE'], + include_directories: ['..'], + dependencies: [ + ccan_dep, + config_dep, + shared_dep, + ], + ) + + test('shared - sandbox-util-fallback', test_sandbox_util_fallback, + suite: 'unit') +endif + test_assert_util = executable( 'test-assert-util', ['test-assert-util.c'], diff --git a/shared/tests/test-io-util.c b/shared/tests/test-io-util.c index db278b27b2..ea552d9d1c 100644 --- a/shared/tests/test-io-util.c +++ b/shared/tests/test-io-util.c @@ -157,6 +157,40 @@ static bool test_read_all(void) return pass; } +static bool test_read_full(void) +{ + static const char *path = "shr-test-io-util-full"; + static const char msg[] = "binary\0data"; + char buf[32]; + bool pass = true; + ssize_t n; + int fd; + + printf("shr_read_full:\n"); + + fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644); + if (fd < 0) + return check_bool("temp file opened for writing", false); + pass &= check_bool("write", !shr_write_all(fd, msg, sizeof(msg))); + close(fd); + + fd = open(path, O_RDONLY); + if (fd < 0) + return check_bool("temp file reopened for reading", false); + n = shr_read_full(fd, buf, 4); + pass &= check_bool("reads as much as asked", n == 4); + n = shr_read_full(fd, buf, sizeof(buf)); + pass &= check_bool("stops at EOF with the length", + n == sizeof(msg) - 4 && + !memcmp(buf, msg + 4, sizeof(msg) - 4)); + n = shr_read_full(fd, buf, sizeof(buf)); + pass &= check_bool("returns 0 at EOF", n == 0); + close(fd); + unlink(path); + + return pass; +} + int main(void) { bool pass = true; @@ -165,6 +199,7 @@ int main(void) pass &= test_zero_length(); pass &= test_bad_fd(); pass &= test_read_all(); + pass &= test_read_full(); fflush(stdout); exit(pass ? EXIT_SUCCESS : EXIT_FAILURE); diff --git a/shared/tests/test-sandbox-util.c b/shared/tests/test-sandbox-util.c new file mode 100644 index 0000000000..582a9d05ef --- /dev/null +++ b/shared/tests/test-sandbox-util.c @@ -0,0 +1,338 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +/* + * This file is part of nvme-cli. + * Copyright (c) 2026 SUSE Software Solutions + * + * Authors: Daniel Wagner + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#ifdef __linux__ +#include +#endif + +#include + +#include + +static bool check_bool(const char *name, bool got) +{ + printf(" - %s [%s]\n", name, got ? "PASS" : "FAIL"); + return got; +} + +/* What the functions write, handed back as the result. */ +static struct { + pid_t pid; + int err; + char text[16]; +} out; +static int outside; + +/* + * Runs @fn with shr_sandbox_begin(), the child hands back @out. + * + * Return: what shr_sandbox_begin() returned, or -EPROTO for a result of + * an unexpected size. + */ +static int run(int (*fn)(void *arg), void *arg) +{ + struct shr_sandbox_output res; + int ret; + + memset(&out, 0, sizeof(out)); + ret = shr_sandbox_begin(&res); + switch (ret) { + case SHR_SANDBOX_OFF: + fn(arg); + break; + case SHR_SANDBOX_CHILD: + fn(arg); + shr_sandbox_end(&out, sizeof(out)); + case SHR_SANDBOX_DONE: + if (res.len == sizeof(out)) + memcpy(&out, res.buf, sizeof(out)); + else + ret = -EPROTO; + free(res.buf); + break; + } + + return ret; +} + +static int fn_result(void *arg) +{ + out.pid = getpid(); + memcpy(out.text, "decoded", sizeof("decoded")); + outside = 1; + return 0; +} + +/* The child is sandboxed already, so the code runs in it. */ +static int fn_nested(void *arg) +{ + struct shr_sandbox_output res; + + out.err = shr_sandbox_begin(&res); + return 0; +} + +/* A child may hand back nothing. */ +static bool run_empty(void) +{ + struct shr_sandbox_output res; + int ret = shr_sandbox_begin(&res); + + if (ret == SHR_SANDBOX_CHILD) + shr_sandbox_end(NULL, 0); + free(res.buf); + + return ret == SHR_SANDBOX_DONE && !res.len; +} + +static int fn_malloc(void *arg) +{ + size_t len = 4 << 20; + char *p = malloc(len); + + if (!p) + return -ENOMEM; + memset(p, 0x5a, len); + p = realloc(p, 2 * len); + if (!p) + return -ENOMEM; + out.text[0] = p[len - 1]; + free(p); + return 0; +} + +/* Opening a file is not allowed. */ +static int fn_open(void *arg) +{ + int fd = open("/dev/null", O_RDONLY); + + if (fd < 0) + out.err = errno; + else + close(fd); + return 0; +} + +/* Descriptors other than stdio are closed in the sandbox. */ +static int fn_write_fd(void *arg) +{ + if (write(*(int *)arg, "x", 1) < 0) + out.err = errno; + return 0; +} + +/* stdio asks whether a stream is a terminal. */ +static int fn_isatty(void *arg) +{ + struct winsize ws; + + out.err = isatty(STDIN_FILENO) && + !ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) ? 0 : ENOTTY; + return 0; +} + +#ifdef __linux__ +/* FIONREAD works on a pipe, so only the filter can make it fail. */ +static int fn_ioctl(void *arg) +{ + int n; + + if (ioctl(STDIN_FILENO, FIONREAD, &n)) + out.err = errno; + return 0; +} + +/* Signal 0 only checks whether a signal could be sent. */ +static int fn_tgkill(void *arg) +{ + pid_t pid = *(pid_t *)arg; + + if (syscall(SYS_tgkill, pid, pid, 0)) + out.err = errno; + return 0; +} +#endif + +/* + * A child taken over could write data of its choice to the result pipe; + * the caller must notice data beyond the result. + */ +static int fn_extra(void *arg) +{ + uint64_t len = sizeof(out); + + if (write(3, &len, sizeof(len)) < 0 || + write(3, &out, sizeof(out)) < 0 || + write(3, "x", 1) < 0) + _exit(1); + _exit(0); +} + +/* ... and a length beyond what the caller takes. */ +static int fn_huge(void *arg) +{ + uint64_t len = (uint64_t)1 << 40; + + if (write(3, &len, sizeof(len)) < 0) + out.err = errno; + _exit(0); +} + +/* The child cannot read the time zone, the caller loads it. */ +static int fn_localtime(void *arg) +{ + time_t t = 0; + struct tm tm; + + strftime(out.text, sizeof(out.text), "%Z %z", localtime_r(&t, &tm)); + return 0; +} + +static int fn_abort(void *arg) +{ + abort(); +} + +static int fn_exit(void *arg) +{ + _exit(0); +} + +/* Runs @fn with @fd as stdin. */ +static int run_stdin(int (*fn)(void *arg), int fd) +{ + int saved = dup(STDIN_FILENO), ret; + + dup2(fd, STDIN_FILENO); + ret = run(fn, NULL); + dup2(saved, STDIN_FILENO); + close(saved); + + return ret; +} + +/* A descriptor above a lowered limit, which a loop up to the limit misses */ +static bool run_high_fd(int fd) +{ + struct rlimit saved, low; + int high = 200; + bool ret; + + if (getrlimit(RLIMIT_NOFILE, &saved) || saved.rlim_cur <= high || + dup2(fd, high) != high) { + printf(" - no descriptor above the limit [SKIP]\n"); + return true; + } + low = saved; + low.rlim_cur = 64; + ret = !setrlimit(RLIMIT_NOFILE, &low); + ret &= check_bool("descriptors above the limit are closed", + run(fn_write_fd, &high) == SHR_SANDBOX_DONE && + out.err == EBADF); + setrlimit(RLIMIT_NOFILE, &saved); + close(high); + + return ret; +} + +int main(void) +{ + char zone[sizeof(out.text)]; + pid_t self = getpid(); + bool pass = true; + time_t t = 0; + struct tm tm; + int fds[2], pty, ret; + + printf("shr_sandbox_begin:\n"); + + pass &= check_bool("disabled: runs in process", + run(fn_result, NULL) == SHR_SANDBOX_OFF && + out.pid == self && outside == 1); + + shr_sandbox_enable(true); + outside = 0; + ret = run(fn_result, NULL); + if (ret == SHR_SANDBOX_OFF) { + printf(" - no sandbox on this system [SKIP]\n"); + return pass ? 77 : EXIT_FAILURE; + } + pass &= check_bool("the code runs in a child", + ret == SHR_SANDBOX_DONE && out.pid != self); + pass &= check_bool("the result is returned", + !strcmp(out.text, "decoded")); + pass &= check_bool("other memory is not", outside == 0); + pass &= check_bool("in the sandbox, the code runs in the child", + run(fn_nested, NULL) == SHR_SANDBOX_DONE && + out.err == SHR_SANDBOX_OFF); + pass &= check_bool("an empty result", run_empty()); + pass &= check_bool("memory can be allocated", + run(fn_malloc, NULL) == SHR_SANDBOX_DONE && + out.text[0] == 0x5a); + /* the time zone of the system, which only tells something if not UTC */ + run(fn_localtime, NULL); + strftime(zone, sizeof(zone), "%Z %z", localtime_r(&t, &tm)); + if (strcmp(zone, "UTC +0000") && strcmp(zone, "GMT +0000")) + pass &= check_bool("the time zone of the caller is used", + !strcmp(out.text, zone)); + else + printf(" - the time zone is UTC [SKIP]\n"); + pass &= check_bool("files cannot be opened", + run(fn_open, NULL) == SHR_SANDBOX_DONE && out.err); + + if (!pipe(fds)) { + pass &= check_bool("other descriptors are closed", + run(fn_write_fd, &fds[1]) == + SHR_SANDBOX_DONE && out.err == EBADF); + pass &= run_high_fd(fds[1]); +#ifdef __linux__ + pass &= check_bool("other ioctls fail with ENOTTY", + run_stdin(fn_ioctl, fds[0]) == + SHR_SANDBOX_DONE && out.err == ENOTTY); +#endif + close(fds[0]); + close(fds[1]); + } + + pty = posix_openpt(O_RDWR | O_NOCTTY); + if (pty >= 0) { + pass &= check_bool("terminal queries work", + run_stdin(fn_isatty, pty) == + SHR_SANDBOX_DONE && !out.err); + close(pty); + } else { + printf(" - no pty for the terminal queries [SKIP]\n"); + } + +#ifdef __linux__ + pass &= check_bool("other processes cannot be signaled", + run(fn_tgkill, &self) == SHR_SANDBOX_DONE && + out.err == EPERM); +#endif + pass &= check_bool("data after the result fails", + run(fn_extra, NULL) == -EPROTO); + pass &= check_bool("a result too large fails", + run(fn_huge, NULL) == -EPROTO); + pass &= check_bool("abort() in the child fails", + run(fn_abort, NULL) == -EPROTO); + pass &= check_bool("exit without a result fails", + run(fn_exit, NULL) == -EPROTO); + + return pass ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/src/nvme-print-json.c b/src/nvme-print-json.c index 59d764c3b1..47be310381 100644 --- a/src/nvme-print-json.c +++ b/src/nvme-print-json.c @@ -5900,6 +5900,150 @@ void json_show_finish(void) json_r = NULL; } +/* + * A sandboxed printer: the child inherits the document as it was at the + * fork. Let the printer write to an object of its own instead, whose + * members the caller adds to its document. + */ +static int json_capture_begin(void) +{ + if (!json_init) + return 0; + + json_r = json_create_object(); + return json_r ? 0 : -ENOMEM; +} + +static int json_member_put(struct printbuf *pb, const char *s, size_t len) +{ + uint32_t n = len; + + if (len > UINT32_MAX) + return -EOVERFLOW; + printbuf_memappend(pb, (const char *)&n, sizeof(n)); + printbuf_memappend(pb, s, len); + + return 0; +} + +/* + * The members the printer added, serialized as pairs of a length and the + * key, a length and the value. @buf is to free(). + */ +static int json_capture_end(void **buf, size_t *len) +{ + struct printbuf *pb; + const char *v; + int err = 0; + + *buf = NULL; + *len = 0; + if (!json_init) + return 0; + + pb = printbuf_new(); + if (!pb) + return -ENOMEM; + json_object_object_foreach(json_r, key, val) { + v = json_object_to_json_string_ext(val, + JSON_C_TO_STRING_PRETTY | + JSON_C_TO_STRING_NOSLASHESCAPE); + if (!v || json_member_put(pb, key, strlen(key)) || + json_member_put(pb, v, strlen(v))) { + err = -ENOMEM; + break; + } + } + if (!err && printbuf_length(pb)) { + *buf = malloc(printbuf_length(pb)); + if (*buf) { + memcpy(*buf, pb->buf, printbuf_length(pb)); + *len = printbuf_length(pb); + } else { + err = -ENOMEM; + } + } + printbuf_free(pb); + + return err; +} + +/* Writes a serialized value as it is, indented to @level */ +static int json_member_serialize(struct json_object *jso, + struct printbuf *pb, int level, int flags) +{ + const char *s = json_object_get_string(jso); + size_t len = json_object_get_string_len(jso), i, start = 0; + int j; + + for (i = 0; i < len; i++) { + if (s[i] != '\n') + continue; + printbuf_memappend(pb, s + start, i - start + 1); + start = i + 1; + if (flags & JSON_C_TO_STRING_PRETTY) + for (j = 0; j < level; j++) + printbuf_strappend(pb, " "); + } + printbuf_memappend(pb, s + start, len - start); + + return 0; +} + +static bool json_member_get(const char **p, const char *end, + const char **s, uint32_t *n) +{ + if ((size_t)(end - *p) < sizeof(*n)) + return false; + memcpy(n, *p, sizeof(*n)); + *p += sizeof(*n); + if ((size_t)(end - *p) < *n) + return false; + *s = *p; + *p += *n; + + return true; +} + +/* + * Adds the members of a sandboxed printer to the document. They are added + * as the child serialized them, not parsed again: a parse would turn 128 + * bit numbers into doubles. A member replaces one of the same key, as when + * the printer runs in process. The child may have been taken over: check + * the framing, the values are only copied to the output. + */ +static int json_capture_add(const void *buf, size_t len) +{ + const char *p = buf, *end = p + len, *k, *v; + struct json_object *val; + __cleanup_free char *key = NULL; + uint32_t klen, vlen; + + if (!len) + return 0; + if (!json_init || !json_r) + return -EPROTO; + + while (p < end) { + if (!json_member_get(&p, end, &k, &klen) || + !json_member_get(&p, end, &v, &vlen) || + memchr(k, '\0', klen)) + return -EPROTO; + free(key); + key = strndup(k, klen); + if (!key) + return -ENOMEM; + val = json_object_new_string_len(v, vlen); + if (!val) + return -ENOMEM; + json_object_set_serializer(val, json_member_serialize, + NULL, NULL); + json_object_object_add(json_r, key, val); + } + + return 0; +} + static void json_mgmt_addr_list_log(struct nvme_mgmt_addr_list_log *ma_list) { int i; @@ -6364,6 +6508,9 @@ static struct print_ops json_print_ops = { .show_opcode_status = json_output_opcode_status, .show_error_status = json_output_error_status, .show_key_value = json_output_key_value, + .capture_begin = json_capture_begin, + .capture_end = json_capture_end, + .capture_add = json_capture_add, }; struct print_ops *nvme_get_json_print_ops(nvme_print_flags_t flags) diff --git a/src/nvme-print.c b/src/nvme-print.c index fbd4fbbba9..95bc7f9151 100644 --- a/src/nvme-print.c +++ b/src/nvme-print.c @@ -7,24 +7,35 @@ #include #include #include +#include #include +#include #include #include #include #include +#include #include #include "cleanup.h" #include "nvme-models.h" #include "nvme-print.h" +/* + * A printer runs between nvme_print_begin() and nvme_print_end(). The + * printers which decode device data run in the sandbox, if enabled. See + * Documentation/PRIVSEP.md. + */ #define nvme_print(name, flags, ...) \ do { \ struct print_ops *ops = nvme_print_ops(flags); \ - if (nvme_print_check(ops, ops->name)) \ + if (nvme_print_check(ops, ops->name) && \ + nvme_print_begin(ops, ops->name)) { \ ops->name(__VA_ARGS__); \ + nvme_print_end(ops); \ + } \ } while (false) #define nvme_print_output_format(name, ...) \ @@ -89,6 +100,109 @@ static struct print_ops *nvme_print_ops(nvme_print_flags_t flags) return ops; } +/* Printer calls in progress, a printer may call another one */ +static unsigned int print_depth; + +/* In the child of a sandboxed printer */ +static bool print_in_child; + +/* A printer failed in the sandbox */ +static bool print_failed; + +bool nvme_show_failed(void) +{ + return print_failed; +} + +/* + * The printers which stay in process: the ones of the libnvme tree, which + * read sysfs while printing, the ones which hand JSON objects to their + * caller, the interactive one and the document. + */ +static bool nvme_print_sandboxed(struct print_ops *ops, void *func) +{ + void *in_process[] = { + ops->relatives, ops->list_item, ops->list_items, + ops->print_nvme_subsystem_list, ops->topology_ctrl, + ops->topology_namespace, ops->topology_multipath, + ops->topology_tabular, ops->config_conn_list, ops->top, + ops->zns_start_zone_list, ops->zns_finish_zone_list, + ops->zns_report_zones, ops->show_init, ops->show_finish, + ops->connect_msg, + }; + size_t i; + + for (i = 0; i < ARRAY_SIZE(in_process); i++) + if (func == in_process[i]) + return false; + + return true; +} + +static void nvme_print_error(int err) +{ + print_failed = true; + if (err == -ECHILD || err == -EPROTO) + nvme_show_error( + "the decoder of the device data crashed or misbehaved in the sandbox"); + else + nvme_show_error( + "cannot decode the device data in the sandbox: %s", + libnvme_strerror(-err)); +} + +/* + * Return: whether to run the printer here, in process or in the sandbox. + * A sandboxed printer writes to stdout as it does in process. What it + * writes elsewhere, the output plugin captures in the child and adds in + * the caller. + */ +static bool nvme_print_begin(struct print_ops *ops, void *func) +{ + struct shr_sandbox_output out; + int ret; + + if (print_depth++ || !nvme_print_sandboxed(ops, func)) + return true; + + ret = shr_sandbox_begin(&out); + switch (ret) { + case SHR_SANDBOX_OFF: + return true; + case SHR_SANDBOX_CHILD: + print_in_child = true; + /* the caller notices a child without a result */ + if (ops->capture_begin && ops->capture_begin()) + _exit(1); + return true; + case SHR_SANDBOX_DONE: + if (ops->capture_add) + ret = ops->capture_add(out.buf, out.len); + else + ret = out.len ? -EPROTO : 0; + free(out.buf); + break; + } + + print_depth--; + if (ret) + nvme_print_error(ret); + return false; +} + +static void nvme_print_end(struct print_ops *ops) +{ + void *buf = NULL; + size_t len = 0; + + if (--print_depth || !print_in_child) + return; + + if (ops->capture_end && ops->capture_end(&buf, &len)) + _exit(1); + shr_sandbox_end(buf, len); +} + static bool nvme_print_check(struct print_ops *ops, void *func) { if (!ops || !func) diff --git a/src/nvme-print.h b/src/nvme-print.h index 79fb8db1fc..3833289582 100644 --- a/src/nvme-print.h +++ b/src/nvme-print.h @@ -421,6 +421,15 @@ struct print_ops { void (*show_error_status)(int status, const char *msg, va_list ap); void (*show_key_value)(const char *key, const char *val, va_list ap); + /* + * A sandboxed printer, see nvme_print_begin(): output which does not + * go to stdout is captured in the child, between capture_begin() and + * capture_end(), and handed to capture_add() in the caller. Optional. + */ + int (*capture_begin)(void); + int (*capture_end)(void **buf, size_t *len); + int (*capture_add)(const void *buf, size_t len); + nvme_print_flags_t flags; }; @@ -434,6 +443,9 @@ static inline struct print_ops *nvme_get_json_print_ops(nvme_print_flags_t flags #endif /* !CONFIG_JSONC */ +/* A printer failed in the sandbox */ +bool nvme_show_failed(void); + struct print_ops *nvme_get_stdout_print_ops(nvme_print_flags_t flags); struct print_ops *nvme_get_binary_print_ops(nvme_print_flags_t flags); diff --git a/src/nvme.c b/src/nvme.c index edeeb0accb..a425d4d8ac 100644 --- a/src/nvme.c +++ b/src/nvme.c @@ -38,6 +38,7 @@ #include #include #include +#include #include #include #include @@ -164,11 +165,62 @@ static void __shr_destructor free_plugins(void) } } +/* + * Open /dev/null on the standard descriptors which are closed. Else the + * next descriptor nvme-cli opens, e.g. the socket to the privsep helper, + * becomes one of them, and the output goes there. + */ +static int nvme_reserve_stdio(void) +{ +#ifndef _WIN32 + int fd, null; + + for (fd = STDIN_FILENO; fd <= STDERR_FILENO; fd++) { + if (fcntl(fd, F_GETFD) >= 0 || errno != EBADF) + continue; + /* the lowest free descriptor, fd */ + null = open("/dev/null", O_RDWR); + if (null < 0) + return -errno; + if (null != fd) { + close(null); + return -EBADF; + } + } +#endif + return 0; +} + +/* + * The decoders of device data run sandboxed with -Dsandbox=enabled unless + * NVME_SANDBOX=0, e.g. for a debugger, and in any build with + * NVME_SANDBOX=1. + */ +static void nvme_sandbox_init(void) +{ + const char *env = getenv("NVME_SANDBOX"); + bool enable = false; + +#ifdef CONFIG_SANDBOX + enable = true; +#endif + if (env) + enable = strcmp(env, "0"); + shr_sandbox_enable(enable); +} + int nvme_main(int argc, char **argv) { struct plugin_call call = {}; int err; + err = nvme_reserve_stdio(); + if (err) { + fprintf(stderr, "%s: cannot open /dev/null: %s\n", argv[0], + strerror(-err)); + return 1; + } + #ifdef _WIN32 /* * Set stdout and stderr to binary mode to prevent Windows text-mode @@ -183,6 +235,8 @@ int nvme_main(int argc, char **argv) general_help(&builtin, NULL); return 0; } + + nvme_sandbox_init(); nvme_args_register(); /* The command line comes first, nvme-cli.conf does not override it */ @@ -211,5 +265,5 @@ int nvme_main(int argc, char **argv) if (argconfig_help_requested()) return 0; - return err ? 1 : 0; + return err || nvme_show_failed() ? 1 : 0; } diff --git a/tests/cli/meson.build b/tests/cli/meson.build index 8b74d7e1a0..54fba66aa4 100644 --- a/tests/cli/meson.build +++ b/tests/cli/meson.build @@ -135,6 +135,18 @@ if python3.found() mock_cli_tests += [ ['print', 'nvme_print_test.py', print_test_env, 300], ] + + # The decoders print the same with and without the sandbox + compare_env = print_test_env + compare_env.set('NVME_TEST_COMPARE_SANDBOX', '1') + test('nvme-cli - print-sandbox-compare', + python3, + args: [files('nvme_print_test.py'), nvme_exe, + mock_nvme_lib], + env: compare_env, + depends: [nvme_exe, mock_nvme_lib], + timeout: 600, + suite: 'mock') endif if 'sed' in selected_plugins and want_sed and \ @@ -160,6 +172,16 @@ if python3.found() depends: [nvme_exe, mock_nvme_lib], timeout: t[3], suite: 'mock') + + sandbox_env = t[2] + sandbox_env.set('NVME_SANDBOX', '1') + test('nvme-cli - ' + t[0] + '-sandbox', + python3, + args: [files(t[1]), nvme_exe, mock_nvme_lib], + env: sandbox_env, + depends: [nvme_exe, mock_nvme_lib], + timeout: t[3], + suite: 'mock') endforeach if want_privsep diff --git a/tests/cli/nvme_mock_ipc.py b/tests/cli/nvme_mock_ipc.py index 3fc439433f..ba19e20c96 100644 --- a/tests/cli/nvme_mock_ipc.py +++ b/tests/cli/nvme_mock_ipc.py @@ -281,7 +281,7 @@ def _is_asan_binary(nvme_bin): def run_nvme(nvme_bin, env, sysfs_dir, base_dir, *args, encoding='utf-8', - stdin_data=None, stack_limit_kb=None): + stdin_data=None, stack_limit_kb=None, close_fd=None): """Runs `nvme_bin *args` under libmock_nvme.c. Returns the completed subprocess.Popen result, with stdout/stderr captured as text. Callers check .returncode/.stdout/.stderr themselves. @@ -290,7 +290,8 @@ def run_nvme(nvme_bin, env, sysfs_dir, base_dir, *args, encoding='utf-8', commands whose output is not text ('-o binary'). Pass @stdin_data to feed it to stdin, e.g. to answer a confirmation prompt. Otherwise stdin is /dev/null. Pass @stack_limit_kb to run nvme with that - stack size limit.""" + stack size limit. Pass @close_fd to run nvme with that standard + descriptor closed.""" cmd = [ nvme_bin, '--set-options', f'test-sysfs-dir={sysfs_dir},test-base-dir={base_dir}', @@ -321,9 +322,10 @@ def run_nvme(nvme_bin, env, sysfs_dir, base_dir, *args, encoding='utf-8', # process that, like the mock server, runs threads. if stack_limit_kb is not None: ulimit += f'ulimit -s {int(stack_limit_kb)}; ' + close = f' {int(close_fd)}>&-' if close_fd is not None else '' wrapped_cmd = [ '/bin/sh', '-c', - f'{ulimit}export LD_PRELOAD={shlex.quote(ld_preload)}; exec "$@"', + f'{ulimit}export LD_PRELOAD={shlex.quote(ld_preload)}; exec "$@"{close}', 'nvme-mock-wrapper', ] + cmd diff --git a/tests/cli/nvme_print_test.py b/tests/cli/nvme_print_test.py index 0399a8e935..13ce64e067 100644 --- a/tests/cli/nvme_print_test.py +++ b/tests/cli/nvme_print_test.py @@ -42,6 +42,8 @@ # Without json-c, some commands ignore '-o json' and print text. _HAVE_JSON = os.environ.get('NVME_TEST_JSON', '1') == '1' +# Run every command with and without the sandbox and compare the output. +_COMPARE_SANDBOX = os.environ.get('NVME_TEST_COMPARE_SANDBOX') == '1' _OPC_GET_LOG_PAGE = 0x02 _OPC_IDENTIFY = 0x06 @@ -181,6 +183,29 @@ def handle_raw_ioctl(self, conn, fd, ioc, payload): _LIST_FORMATS = [[], ['-v'], ['-o', 'json'], ['-v', '-o', 'json']] +def _pretty_indent_error(text): + """The first line of pretty JSON which is not indented by its depth.""" + depth = 0 + for n, line in enumerate(text.splitlines(), 1): + stripped = line.lstrip(' ') + closing = stripped[:1] in ('}', ']') + if stripped and len(line) - len(stripped) != 2 * (depth - closing): + return f'line {n}: {line!r}' + in_str = esc = False + for c in line: + if esc: + esc = False + elif c == '\\': + esc = in_str + elif c == '"': + in_str = not in_str + elif not in_str and c in '{[': + depth += 1 + elif not in_str and c in '}]': + depth -= 1 + return None + + class PrintCLITest(unittest.TestCase): CTRL = '/dev/nvme0' @@ -214,11 +239,20 @@ def _run_all(self, commands): with self.subTest(seed=seed, cmd=' '.join(cmd + fmt)): self._run(cmd + fmt) - def _run(self, args): + def _run(self, args, compare=True): binary = '-o' in args and 'binary' in args - result = run_nvme(_NVME_BIN, self.env, self.sysfs_dir, + env = dict(self.env, NVME_SANDBOX='1') \ + if _COMPARE_SANDBOX else self.env + result = run_nvme(_NVME_BIN, env, self.sysfs_dir, self.base_dir, *args, encoding=None if binary else 'utf-8') + if _COMPARE_SANDBOX and compare: + direct = run_nvme(_NVME_BIN, dict(self.env, NVME_SANDBOX='0'), + self.sysfs_dir, self.base_dir, *args, + encoding=None if binary else 'utf-8') + self.assertEqual(result.returncode, direct.returncode) + self.assertEqual(result.stdout, direct.stdout) + self.assertEqual(result.stderr, direct.stderr) errors, self.server.errors = self.server.errors, [] if errors: self.fail('the mock server failed:\n' + ''.join(errors)) @@ -229,6 +263,8 @@ def _run(self, args): if (_HAVE_JSON and result.returncode == 0 and '-o' in args and 'json' in args and result.stdout.strip()): json.loads(result.stdout) + # the members of the printer calls are put together as text + self.assertIsNone(_pretty_indent_error(result.stdout)) def test_id(self): self._run_all([['id', c, self.NS] for c in _ID]) @@ -256,7 +292,8 @@ def test_list(self): for cmd in _LIST: for fmt in _LIST_FORMATS: with self.subTest(tree=tree, cmd=' '.join(cmd + fmt)): - self._run(cmd + fmt) + # a missing hostnqn is generated anew each run + self._run(cmd + fmt, compare=False) def test_persistent_event(self): # One event of each type. Each one has enough data for the largest @@ -324,6 +361,31 @@ def test_persistent_event_entries(self): self.assertEqual([e['prev_ts'] for e in entries], [0x1000, 0x1001, 0x1002]) + @unittest.skipIf(os.geteuid() == 0, 'process limits do not apply to root') + def test_sandbox_used(self): + """With the sandbox, decoding needs a child process.""" + wrapper = os.path.join(self.tmp_dir, 'nvme-no-fork') + with open(wrapper, 'w', encoding='utf-8') as f: + f.write('#!/bin/sh\nulimit -u 1 || exit 99\n' + 'exec "$REAL_NVME" "$@"\n') + os.chmod(wrapper, 0o755) + env = dict(self.env, REAL_NVME=os.path.abspath(_NVME_BIN)) + # starting the privsep helper needs a child process too + env.pop('NVME_PRIVSEP_TEST_HELPER', None) + + direct = run_nvme(wrapper, dict(env, NVME_SANDBOX='0'), + self.sysfs_dir, self.base_dir, + 'log', 'smart', self.CTRL) + if direct.returncode == 99: + self.skipTest('ulimit -u not supported') + self.assertEqual(direct.returncode, 0) + sandboxed = run_nvme(wrapper, dict(env, NVME_SANDBOX='1'), + self.sysfs_dir, self.base_dir, + 'log', 'smart', self.CTRL) + self.assertEqual(sandboxed.returncode, 1) + self.assertIn('cannot decode the device data in the sandbox', + sandboxed.stderr) + def test_persistent_event_supported_events(self): # Only the Timestamp Change event (bit 3) is supported. header = bytearray(512) diff --git a/tests/cli/nvme_privsep_test.py b/tests/cli/nvme_privsep_test.py index 7e33f1aa6e..d2155cbe0a 100644 --- a/tests/cli/nvme_privsep_test.py +++ b/tests/cli/nvme_privsep_test.py @@ -80,11 +80,12 @@ def tearDown(self): self.server.join() shutil.rmtree(self.tmp_dir, ignore_errors=True) - def nvme(self, helper, *args): + def nvme(self, helper, *args, close_fd=None): env = dict(self.env) if helper: env['NVME_PRIVSEP_TEST_HELPER'] = helper - return run_nvme(_NVME_BIN, env, self.sysfs_dir, self.base_dir, *args) + return run_nvme(_NVME_BIN, env, self.sysfs_dir, self.base_dir, *args, + close_fd=close_fd) def test_device_command_starts_helper(self): """A device command starts the helper and fails without one.""" @@ -127,6 +128,29 @@ def test_id_ctrl_through_helper(self): self.assertEqual(result.stdout, direct.stdout) self.assertEqual(self.server.ioctls - direct_ioctls, direct_ioctls) + def test_closed_stdio(self): + """A closed standard descriptor does not become the socket to the + helper: nvme-cli's output would go to the helper, and a sandboxed + decoder, which keeps stdio, could send it requests. The helper + lists the descriptors of nvme-cli, which waits for it.""" + fds = os.path.join(self.tmp_dir, 'fds') + wrapper = os.path.join(self.tmp_dir, 'helper-list-fds') + with open(wrapper, 'w', encoding='utf-8') as f: + f.write('#!/bin/sh\n' + f'ls -l /proc/$PPID/fd > "{fds}"\n' + 'exec "$REAL_HELPER" "$@"\n') + os.chmod(wrapper, stat.S_IRWXU) + self.env['REAL_HELPER'] = _HELPER + + for fd in (0, 1, 2): + result = self.nvme(wrapper, 'id-ctrl', '/dev/nvme0', + close_fd=fd) + self.assertEqual(result.returncode, 0, fd) + with open(fds, encoding='utf-8') as f: + links = dict(line.split()[-3::2] for line in f + if ' -> ' in line) + self.assertEqual(links.get(str(fd)), '/dev/null', fd) + def test_device_opened_by_helper(self): """nvme-cli itself does not open the device: without the mock in the helper, the open fails although nvme-cli has the mock."""