diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 11d817b..56d8e28 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -169,6 +169,19 @@ jobs: - name: Benchmark smoke run if: matrix.variant == 'debug' run: build/linux-debug/bin/vbs_benchmarks --files 15 + - name: Hermetic sandbox smoke test + if: matrix.variant == 'debug' + run: | + set -eu + vbs=build/linux-debug/bin/vbs + if "${vbs}" doctor | grep -q "hermetic sandbox: user namespaces available"; then + tmp="$(mktemp -d)" + "${vbs}" new --dir "${tmp}/proj" --name sandbox_demo >/dev/null + "${vbs}" build --project "${tmp}/proj" --build-dir "${tmp}/build" --sandbox strict + else + echo "hermetic sandbox unavailable on this runner (user namespaces disabled);" \ + "skipping the strict smoke test" + fi - name: lcov coverage report if: matrix.variant == 'coverage' run: | diff --git a/CMakeLists.txt b/CMakeLists.txt index 5eeceaf..478fce9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -68,6 +68,7 @@ add_library(VoidBuild_Core STATIC src/Package/RegistryClient.cpp src/Package/Resolver.cpp src/Package/Manifest.cpp + src/Sandbox/Linux/NamespaceSandbox.cpp src/Provider/PkgConfig.cpp src/Provider/Provider.cpp src/Provider/Translator.cpp diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 1672ca5..a2a4da2 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -401,6 +401,8 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B ## Remaining future scope +- **Wave 148 (Hermetic sandboxing, F1)**: `Sandbox::sandbox_supported()` probes unprivileged user namespaces; `vbs build|test|run --sandbox=off|warn|strict` (or `VBS_SANDBOX`) wraps every action in the hidden `vbs __sandbox-exec` mode, which unshares user/mount/network namespaces, maps the caller to root, binds the project read-only, the build root (snapshots included) read-write, and `/usr`, `/lib`, `/bin`, `/etc` and the Nix store read-only before `pivot_root` and exec. `/proc`, `/sys` and `/dev` are bound read-write (their mounts cannot be remounted read-only from a user namespace), `/tmp` is an empty directory, and system read-only remounts that the kernel refuses degrade to writable binds (the project itself is required to be read-only). `vbs doctor` reports availability, CI runs a strict smoke build when the runner allows user namespaces, and `FullV1Tests.sandbox_strict_allows_project_builds_and_hides_outside_files` proves a strict build succeeds while an action that reads an outside file fails. + - **Wave 147 (Lifecycle CLI and native compiler caching, G1/G7 start)**: - `vbs run` builds and executes an executable target with program arguments and passes the exit code through; it uses Void::Process with inherited stdio so interactive programs keep the terminal, and runs Windows targets under Wine. - `vbs metadata` emits a schema-versioned workspace document (roots, profile, compiler, targets with sources/includes/links/labels/install rules, dependencies, lockfile revision) built with `Void::Json::Strict` instead of hand-written JSON. @@ -413,6 +415,7 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B - `vbs new` is a Cargo-style alias of `init` with the same templates. - `--bep FILE` on `build`/`test`/`run` writes a newline-delimited JSON Build Event Protocol stream (build/profile started, action started/finished, test finished with exit code, build finished), serialized with `Void::Json::Strict`. - **Native compiler caching**: `--native-cache off|auto|ccache|sccache` (or `VBS_NATIVE_CACHE`) prepends ccache/sccache to compile actions only; the wrapper and real compiler are part of the action key, archives/links are untouched, and `vbs doctor` reports availability. Verified deterministically by `FullV1Tests.native_cache_wrapper_is_lowered_into_compile_commands` and end to end when the tool is installed (`native_cache_wraps_compile_actions`). + - **Hermetic sandboxing**: `--sandbox=off|warn|strict` (or `VBS_SANDBOX`) runs actions through `vbs __sandbox-exec`, which unshares user/mount/network namespaces and pivots into a root containing only the read-only project, the writable build root and read-only system/toolchain roots; `vbs doctor` reports support and the strict lane degrades to a warning only when the host lacks user namespaces. - **Superiority plan ([22-superiority-and-gaps.md](../roadmap/22-superiority-and-gaps.md), 2026-12-05)**: revised platform strategy - **macOS deferred**, **Windows via MinGW-w64 cross-compilation + Wine execution** (`dev cpp-gcc -p pkgsCross.mingwW64.stdenv.cc`, `dev cpp-gcc -p wine64`), native MSVC deferred; plus packaging parity (ZIP/DEB/RPM), IDE ecosystem, migration tooling, test-runner parity, benchmarks, CI runners, and remote execution in prioritized order. diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index 06ed030..7992349 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -147,4 +147,5 @@ Base HEAD: `fe0d1a6` | Wave 145 (Coverage reporting) | `vbs test --coverage DIR`; gcov JSON -> lcov + summary | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; E2E passes, full CTest 8/8) | `include/Void/Build/Report/Coverage.hpp`, `src/Report/Coverage.cpp`, `src/Main.cpp`, `tests/FullV1Tests.cpp`, docs | | Wave 146 (CI hardening, explainability, shared caches, CLI surface, migration breadth) | CI image tool upgrades + coverage lane; test `--repeat/--retry/--shuffle/--stop-on-failure`; `vbs explain`; `--trace` Chrome traces; shared descriptor/probe caches; `vbs completions`/`vbs man`; `vbs migrate --from meson`; `vbs init --template`; `vbs presets --export`; MSI installer | COMPLETE & VERIFIED (GCC 16.2; new FullV1Tests cases for every feature pass, CLI contract suite passes; cold build 3897 -> 755 ms measured) | `src/Main.cpp`, `src/Execution/Scheduler.{hpp,cpp}`, `src/Cli/CommandModel.{hpp,cpp}`, `src/Config/{Frontend,Scaffold,CmakeImport}.cpp`, `src/Toolchain/Driver.cpp`, `include/Void/Build/Util/UserCache.hpp`, `.gitea/workflows/ci.yml`, [Void/CI-Images](https://git.faumaray.com/Void/CI-Images), `tests/{FullV1Tests,CliContracts}`, docs | | Wave 147 (Lifecycle CLI + native caching + BEP) | `vbs run` (Void::Process inherited stdio, exit-code passthrough, Wine), `vbs metadata` (StrictJson schema v1), `vbs why`, `vbs tree`, `vbs fmt`/`vbs lint`, `vbs install-binary`, `vbs add`/`vbs remove` (Semver-validated manifest editing + lock refresh), `vbs new`, `--frozen`, `--bep` event stream, `--native-cache off/auto/ccache/sccache` with doctor reporting | COMPLETE & VERIFIED for the implemented commands (GCC 16.2; lifecycle, tree, fmt, BEP and native-cache tests pass; CLI contracts pass) | `src/Main.cpp`, `src/Toolchain/Driver.{hpp,cpp}`, `src/Package/Manifest.{hpp,cpp}`, `include/Void/Build/Package/Manifest.hpp`, `tests/{FullV1Tests,CliContracts}`, docs | +| Wave 148 (Hermetic sandboxing) | `Sandbox::sandbox_supported`, `Sandbox::apply_sandbox`, hidden `vbs __sandbox-exec` wrapper, `--sandbox=off|warn|strict`/`VBS_SANDBOX`, project read-only + build root writable + system/toolchain roots read-only, doctor reporting, CI strict smoke step | COMPLETE & VERIFIED (GCC 16.2; `sandbox_strict_allows_project_builds_and_hides_outside_files` passes: strict build succeeds and an action reading an outside file fails; CLI contracts pass) | `include/Void/Build/Sandbox/Sandbox.hpp`, `src/Sandbox/Linux/NamespaceSandbox.cpp`, `include/Void/Build/Execution/Scheduler.hpp`, `src/Execution/Scheduler.cpp`, `src/Main.cpp`, `.gitea/workflows/ci.yml`, `tests/{FullV1Tests,CliContracts}`, docs | | Future (Plans 23–24) | Gap closure and superiority tracks | PLANNED (see the plans for per-track acceptance gates) | [23-remaining-upgrade-plan.md](../roadmap/23-remaining-upgrade-plan.md), [24-superiority-tracks.md](../roadmap/24-superiority-tracks.md) | diff --git a/docs/roadmap/23-remaining-upgrade-plan.md b/docs/roadmap/23-remaining-upgrade-plan.md index 4aaefb8..eb3dad5 100644 --- a/docs/roadmap/23-remaining-upgrade-plan.md +++ b/docs/roadmap/23-remaining-upgrade-plan.md @@ -80,6 +80,16 @@ JUnit, CDash, coverage), all nine installer formats, pkg-config, ASM/shader bund ### F1 — Hermetic sandboxing *(L)* +**Status: implemented (Wave 148).** `vbs build|test|run --sandbox=off|warn|strict` (or +`VBS_SANDBOX`) runs actions through the hidden `vbs __sandbox-exec` wrapper: user/mount/network +namespaces, caller mapped to root, project read-only, build root (snapshots included) writable, +system/toolchain roots read-only, `/tmp` empty, `pivot_root` before exec. `/proc`, `/sys` and +`/dev` are bound read-write because their mounts cannot be remounted read-only from a user +namespace; read-only remounts the kernel refuses degrade to writable binds, while the project +remount is required. `vbs doctor` reports availability and CI runs a strict smoke build when +the runner allows user namespaces. Verified by +`FullV1Tests.sandbox_strict_allows_project_builds_and_hides_outside_files`. + **Goal.** Make "actions see only their snapshot inputs" a guarantee, not a convention: an action inherits a mount namespace in which the project snapshot tree is read-only, the profile build directory is writable, the toolchain and system libraries are read-only, and nothing else of the diff --git a/docs/roadmap/24-superiority-tracks.md b/docs/roadmap/24-superiority-tracks.md index 508fc38..206e46e 100644 --- a/docs/roadmap/24-superiority-tracks.md +++ b/docs/roadmap/24-superiority-tracks.md @@ -265,6 +265,10 @@ Fortran are cheap to add to images); each language's incremental model differs. ### G5 — Trust: enforced hermeticity, attestations, reproducibility, advisories *(L)* +**Status: partially implemented (Wave 148).** Done: the enforced hermetic sandbox (Plan 23 F1) +for compile/link/custom actions. Pending: SLSA/in-toto attestations, the sandboxed descriptor, +`vbs audit` advisories, dependency-confusion guards, policy-as-code (G11) and `verify-repro`. + **Beats:** all four. Cargo has `cargo-deny` externally; CMake/Meson/build2 have nothing built in. Plan 23 already schedules the sandbox (F1) and reproducibility (F11); this track adds the diff --git a/include/Void/Build/Execution/Scheduler.hpp b/include/Void/Build/Execution/Scheduler.hpp index 46c12ef..393ce23 100644 --- a/include/Void/Build/Execution/Scheduler.hpp +++ b/include/Void/Build/Execution/Scheduler.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include #include @@ -48,6 +49,12 @@ struct ExecutionOptions { bool use_cache{true}; std::vector selected_targets; std::chrono::milliseconds action_timeout{0}; + // Hermetic sandboxing (Linux): compile/link actions run through `vbs __sandbox-exec`, which + // unshares user/mount/network namespaces and pivots into a root containing only the project, + // the profile build directory and the toolchain/system roots. + Sandbox::SandboxMode sandbox_mode{Sandbox::SandboxMode::Off}; + Sandbox::SandboxOptions sandbox_options; + std::filesystem::path sandbox_executable; std::function on_event; }; diff --git a/include/Void/Build/Sandbox/Sandbox.hpp b/include/Void/Build/Sandbox/Sandbox.hpp new file mode 100644 index 0000000..a3cc5ea --- /dev/null +++ b/include/Void/Build/Sandbox/Sandbox.hpp @@ -0,0 +1,41 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +namespace Void::Build::Sandbox { + +enum class SandboxMode { Off, Warn, Strict }; + +[[nodiscard]] std::string_view sandbox_mode_name(SandboxMode mode) noexcept; +[[nodiscard]] bool parse_sandbox_mode(std::string_view text, SandboxMode &out) noexcept; + +struct SandboxOptions { + std::filesystem::path project_root; + std::filesystem::path build_root; + // Additional read-only roots (system/toolchain paths). /usr, /lib, /bin, /etc, /dev and /proc + // are added by the backends automatically; these are extra roots such as a sysroot or the + // Nix store. + std::vector read_only_roots; + bool allow_network{false}; +}; + +// Probes whether unprivileged user+mount namespaces are available on this host. +[[nodiscard]] bool sandbox_supported(); + +// Applies the sandbox to the *current* process (mount namespace, pivot root, bind mounts). +// Used by the hidden `vbs __sandbox-exec` wrapper just before exec. Never called in the parent. +[[nodiscard]] Void::Result::Result +apply_sandbox(const SandboxOptions &options); + +// Hidden wrapper mode: `vbs __sandbox-exec -- [args...]`. +// Reads VBS_SANDBOX_PROJECT, VBS_SANDBOX_BUILD, VBS_SANDBOX_ROOTS (colon-separated) and +// VBS_SANDBOX_NET from the environment, applies the sandbox and execs the command. +[[nodiscard]] int run_sandbox_exec(int argc, char **argv); + +} // namespace Void::Build::Sandbox diff --git a/src/Execution/Scheduler.cpp b/src/Execution/Scheduler.cpp index 3288dfc..a228efd 100644 --- a/src/Execution/Scheduler.cpp +++ b/src/Execution/Scheduler.cpp @@ -717,6 +717,31 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state, } preq.environment.mode = Platform::EnvPolicyMode::Inherit; preq.environment.set_vars = act.environment; + + // Hermetic sandboxing: wrap the action in `vbs __sandbox-exec`, which sets up the + // namespaces and pivots into an isolated root before exec'ing the real command. The + // wrapper is part of the action command, so keys and cached artifacts stay correct. + if (options.sandbox_mode != Sandbox::SandboxMode::Off && + !options.sandbox_executable.empty()) { + std::string roots; + for (const auto &root : options.sandbox_options.read_only_roots) { + if (!roots.empty()) { + roots += ':'; + } + roots += root.string(); + } + preq.environment.set_vars["VBS_SANDBOX_PROJECT"] = + options.sandbox_options.project_root.string(); + preq.environment.set_vars["VBS_SANDBOX_BUILD"] = + options.sandbox_options.build_root.string(); + preq.environment.set_vars["VBS_SANDBOX_ROOTS"] = roots; + preq.environment.set_vars["VBS_SANDBOX_NET"] = + options.sandbox_options.allow_network ? "1" : "0"; + std::vector wrapped{"__sandbox-exec", "--", act.executable.string()}; + wrapped.insert(wrapped.end(), act.arguments.begin(), act.arguments.end()); + preq.executable = options.sandbox_executable; + preq.arguments = std::move(wrapped); + } preq.timeout = options.action_timeout; auto proc = Platform::run_supervised(preq, internal_stop.get_token()); diff --git a/src/Main.cpp b/src/Main.cpp index 90189e4..0060dbd 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include #include #include @@ -456,6 +457,7 @@ struct BuildCmdOptions { std::vector run_args; bool frozen{false}; std::string native_cache_arg; + std::string sandbox_arg{"off"}; bool publish_editor_selection{true}; bool no_cache{false}; bool locked{false}; @@ -482,6 +484,36 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { << "' (expected auto, off, ccache or sccache)\n"; return 2; } + + Sandbox::SandboxMode sandbox_mode = Sandbox::SandboxMode::Off; + if (!Sandbox::parse_sandbox_mode(opts.sandbox_arg, sandbox_mode)) { + std::cerr << cmd_name << ": unsupported --sandbox '" << opts.sandbox_arg + << "' (expected off, warn or strict)\n"; + return 2; + } + std::filesystem::path sandbox_executable; + if (sandbox_mode != Sandbox::SandboxMode::Off) { + if (!Sandbox::sandbox_supported()) { + if (sandbox_mode == Sandbox::SandboxMode::Strict) { + std::cerr << cmd_name + << ": --sandbox=strict requires unprivileged user namespaces, which " + "this host does not allow\n"; + return 1; + } + Void::Log::warn("Sandbox", + "unprivileged user namespaces are unavailable; running without the " + "hermetic sandbox"); + sandbox_mode = Sandbox::SandboxMode::Off; + } else { + auto executable = Platform::current_executable_path(); + if (!executable) { + std::cerr << cmd_name << ": cannot resolve the vbs executable for sandboxing: " + << executable.error().message() << '\n'; + return 1; + } + sandbox_executable = *executable; + } + } int test_timeout_seconds = 300; if (!Void::Str::to_int(opts.test_timeout_arg, test_timeout_seconds) || test_timeout_seconds <= 0 || test_timeout_seconds > 86400) { @@ -1038,6 +1070,24 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { eopts.jobs = jobs; eopts.use_cache = !opts.no_cache; eopts.selected_targets = opts.targets; + if (sandbox_mode != Sandbox::SandboxMode::Off) { + eopts.sandbox_mode = sandbox_mode; + eopts.sandbox_executable = sandbox_executable; + eopts.sandbox_options.project_root = project_root; + // The writable root must be the build root: snapshots live in /.vbs, a sibling + // of the per-profile directory. + eopts.sandbox_options.build_root = + graph->profile_build_dir.parent_path().parent_path(); + eopts.sandbox_options.read_only_roots = {"/usr", "/lib", "/lib64", "/bin", + "/sbin", "/etc"}; + std::error_code sandbox_ec; + if (std::filesystem::exists("/nix/store", sandbox_ec)) { + eopts.sandbox_options.read_only_roots.emplace_back("/nix/store"); + } + if (!tc->sysroot.empty()) { + eopts.sandbox_options.read_only_roots.emplace_back(tc->sysroot); + } + } if (opts.trace_arg || opts.bep_arg) { eopts.on_event = [&](const Execution::ExecutionEvent &ev) { if (ev.kind == Execution::ExecutionEvent::Kind::ActionStarted) { @@ -4913,6 +4963,12 @@ int execute_doctor_command() { << ((has_ccache || has_sccache) ? " (use --native-cache or VBS_NATIVE_CACHE)" : " (install ccache or sccache)") << '\n'; + std::cout << " " << (Sandbox::sandbox_supported() ? "[ok] " : "[opt] ") + << " hermetic sandbox: " + << (Sandbox::sandbox_supported() + ? "user namespaces available (--sandbox=strict)" + : "unavailable on this host (requires unprivileged user namespaces)") + << '\n'; std::cout << " [ok] Void::Crypto built-in SHA-256: enabled\n"; std::cout << " [ok] Void::Archive built-in USTAR/PAX: enabled\n"; @@ -5368,6 +5424,10 @@ int execute_ide_command(std::string_view sub, const IdeCmdOptions &opts) { } // namespace int main(int argc, char **argv) { + // Hidden wrapper mode used by the hermetic sandbox scheduler path. + if (argc >= 3 && std::string_view{argv[1]} == "__sandbox-exec") { + return Sandbox::run_sandbox_exec(argc, argv); + } const std::string cwd = std::filesystem::current_path().string(); bool show_version = false; bool releases_unyank = false; @@ -5376,6 +5436,7 @@ int main(int argc, char **argv) { BuildCmdOptions build_opts; build_opts.project_arg = cwd; + build_opts.sandbox_arg = Void::Configuration::get_env_or("VBS_SANDBOX", "off"); CompDbCmdOptions compdb_opts; compdb_opts.project_arg = cwd; DescribeCmdOptions describe_opts; @@ -5445,6 +5506,7 @@ int main(int argc, char **argv) { }; auto configure_build_or_test = [&](Void::Argparse::Parser &p) { + const std::string sandbox_default = build_opts.sandbox_arg; p.option_default("--project", "-C", "Project directory", build_opts.project_arg, cwd) .option("--build-dir", "-B", "Build output directory", build_opts.build_arg) .option_many("--profile", "-p", "Profile to build", build_opts.profiles) @@ -5507,6 +5569,10 @@ int main(int argc, char **argv) { .option_default("--native-cache", "", "Native compiler cache: off (default), auto, ccache or sccache", build_opts.native_cache_arg, "") + .option_default_checked("--sandbox", "", + "Hermetic sandbox: off (default), warn or strict", + build_opts.sandbox_arg, sandbox_default, + {"off", "warn", "strict"}) .flag("--offline", "", "Disallow network fetches", build_opts.offline) .flag("--no-cache", "", "Bypass action cache reads", build_opts.no_cache) .flag("--native-foreign", "", diff --git a/src/Sandbox/Linux/NamespaceSandbox.cpp b/src/Sandbox/Linux/NamespaceSandbox.cpp new file mode 100644 index 0000000..b1f8910 --- /dev/null +++ b/src/Sandbox/Linux/NamespaceSandbox.cpp @@ -0,0 +1,332 @@ +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +#if defined(__linux__) +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +namespace Void::Build::Sandbox { +namespace { + +Void::Result::Error make_error(std::string message) { + return Void::System::make_system_error(Void::System::SystemErrorCode::io_error, + std::move(message)); +} + +} // namespace + +std::string_view sandbox_mode_name(SandboxMode mode) noexcept { + switch (mode) { + case SandboxMode::Warn: + return "warn"; + case SandboxMode::Strict: + return "strict"; + case SandboxMode::Off: + break; + } + return "off"; +} + +bool parse_sandbox_mode(std::string_view text, SandboxMode &out) noexcept { + if (text == "off" || text == "none" || text == "0") { + out = SandboxMode::Off; + return true; + } + if (text == "warn") { + out = SandboxMode::Warn; + return true; + } + if (text == "strict") { + out = SandboxMode::Strict; + return true; + } + return false; +} + +#if defined(__linux__) +namespace { + +bool write_text(const std::filesystem::path &path, std::string_view text) { + std::ofstream out{path, std::ios::trunc}; + if (!out) { + return false; + } + out << text; + return out.good(); +} + +// Raw mkdir -p: std::filesystem reports EOVERFLOW on some hosts for paths inside freshly mounted +// tmpfs trees, while mkdir(2) works. +bool ensure_directories(const std::filesystem::path &path, std::string &error) { + std::filesystem::path current; + for (const auto &part : path) { + current /= part; + if (::mkdir(current.c_str(), 0755) != 0 && errno != EEXIST) { + error = "mkdir " + current.string() + ": " + std::string{std::strerror(errno)}; + return false; + } + } + return true; +} + +bool touch_file(const std::filesystem::path &path, std::string &error) { + const int fd = ::open(path.c_str(), O_CREAT | O_WRONLY, 0644); + if (fd < 0) { + error = "create " + path.string() + ": " + std::string{std::strerror(errno)}; + return false; + } + ::close(fd); + return true; +} + +bool bind_mount(const std::filesystem::path &source, const std::filesystem::path &target, + bool read_only, bool require_read_only, std::string &error) { + std::error_code ec; + if (!std::filesystem::exists(source, ec)) { + return true; // Missing optional root: skip it. + } + if (!ensure_directories(target.parent_path(), error)) { + return false; + } + // Bind targets must exist; a regular-file source needs an empty file as the target. + if (std::filesystem::is_regular_file(source, ec)) { + if (!touch_file(target, error)) { + return false; + } + } else if (!ensure_directories(target, error)) { + return false; + } + if (::mount(source.c_str(), target.c_str(), nullptr, MS_BIND | MS_REC, nullptr) != 0) { + error = "bind mount " + source.string() + " -> " + target.string() + ": " + + std::string{std::strerror(errno)}; + return false; + } + if (read_only) { + if (::mount(nullptr, target.c_str(), nullptr, MS_BIND | MS_REMOUNT | MS_RDONLY, + nullptr) != 0) { + // Mounts inherited from the parent namespace can be locked; the source's own + // permissions still apply, so system roots degrade to a writable bind. + if (require_read_only) { + error = "remount read-only " + target.string() + ": " + + std::string{std::strerror(errno)}; + return false; + } + } + } + return true; +} + +bool mirror_symlink(const std::filesystem::path &root, const std::filesystem::path &path) { + std::error_code ec; + if (!std::filesystem::is_symlink(path, ec)) { + return true; + } + const auto target = std::filesystem::read_symlink(path, ec); + if (ec) { + return false; + } + const auto inside = root / path.relative_path(); + std::filesystem::create_directories(inside.parent_path(), ec); + std::filesystem::create_symlink(target, inside, ec); + return !ec; +} + +} // namespace + +bool sandbox_supported() { + const pid_t pid = ::fork(); + if (pid < 0) { + return false; + } + if (pid == 0) { + // Probe only: user and mount namespaces are what apply_sandbox needs. + _exit(::unshare(CLONE_NEWUSER | CLONE_NEWNS) == 0 ? 0 : 1); + } + int status = 0; + if (::waitpid(pid, &status, 0) < 0) { + return false; + } + return WIFEXITED(status) && WEXITSTATUS(status) == 0; +} + +Void::Result::Result +apply_sandbox(const SandboxOptions &options) { + std::error_code ec; + const auto original_cwd = std::filesystem::current_path(ec); + if (ec) { + return std::unexpected{make_error("sandbox: cannot read the working directory")}; + } + + unsigned long flags = CLONE_NEWUSER | CLONE_NEWNS; + if (!options.allow_network) { + flags |= CLONE_NEWNET; + } + if (::unshare(flags) != 0) { + return std::unexpected{ + make_error("sandbox: unshare failed: " + std::string{std::strerror(errno)})}; + } + // Map the current user to root inside the new user namespace. + (void)write_text("/proc/self/setgroups", "deny"); + const std::string uid = std::to_string(::getuid()); + const std::string gid = std::to_string(::getgid()); + if (!write_text("/proc/self/uid_map", "0 " + uid + " 1\n") || + !write_text("/proc/self/gid_map", "0 " + gid + " 1\n")) { + return std::unexpected{ + make_error("sandbox: cannot write the user namespace uid/gid maps")}; + } + if (::mount(nullptr, "/", nullptr, MS_REC | MS_PRIVATE, nullptr) != 0) { + return std::unexpected{make_error("sandbox: cannot make mounts private: " + + std::string{std::strerror(errno)})}; + } + + const auto root = options.build_root / ".sandbox" / + ("root-" + std::to_string(static_cast(::getpid()))); + std::string error; + if (!ensure_directories(root, error)) { + return std::unexpected{make_error("sandbox: " + error)}; + } + // pivot_root requires the new root to be a mount point. A self-bind is cheap and avoids + // tmpfs entirely (tmpfs inside a user namespace returns EOVERFLOW on this kernel). + if (::mount(root.c_str(), root.c_str(), nullptr, MS_BIND, nullptr) != 0) { + return std::unexpected{make_error("sandbox: cannot bind the sandbox root: " + + std::string{std::strerror(errno)})}; + } + + // The project is read-only; the profile build directory (including snapshots) is writable. + if (!bind_mount(options.project_root, root / options.project_root.relative_path(), true, + true, error)) { + return std::unexpected{make_error("sandbox: " + error)}; + } + if (!bind_mount(options.build_root, root / options.build_root.relative_path(), + false, false, error)) { + return std::unexpected{make_error("sandbox: " + error)}; + } + // System and toolchain roots are read-only; /proc, /sys and /dev are special filesystems + // whose mounts cannot be remounted read-only from a user namespace. + std::vector read_only{"/usr", "/lib", "/lib64", "/bin", "/sbin", + "/etc"}; + for (const auto &extra : options.read_only_roots) { + read_only.push_back(extra); + } + for (const auto &path : read_only) { + std::error_code symlink_ec; + if (std::filesystem::is_symlink(path, symlink_ec)) { + if (!mirror_symlink(root, path)) { + return std::unexpected{make_error("sandbox: cannot mirror the symlink '" + + path.string() + "'")}; + } + continue; + } + if (!bind_mount(path, root / path.relative_path(), true, false, error)) { + return std::unexpected{make_error("sandbox: " + error)}; + } + } + for (const char *special : {"/proc", "/sys", "/dev"}) { + if (!bind_mount(special, root / std::filesystem::path{special}.relative_path(), false, + false, error)) { + return std::unexpected{make_error("sandbox: " + error)}; + } + } + // A private, empty /tmp hides unrelated host temporary files. It is a plain directory in the + // build tree because tmpfs inside a user namespace is unusable on this kernel. + if (!ensure_directories(root / "tmp", error)) { + return std::unexpected{make_error("sandbox: " + error)}; + } + + // pivot_root into the isolated tree. + if (::chdir(root.c_str()) != 0) { + return std::unexpected{make_error("sandbox: chdir failed")}; + } + std::filesystem::create_directories(".oldroot", ec); + if (::syscall(SYS_pivot_root, ".", ".oldroot") != 0) { + return std::unexpected{make_error("sandbox: pivot_root failed: " + + std::string{std::strerror(errno)})}; + } + (void)::chdir("/"); + (void)::umount2("/.oldroot", MNT_DETACH); + (void)::rmdir("/.oldroot"); + if (::chdir(original_cwd.c_str()) != 0) { + return std::unexpected{make_error("sandbox: cannot restore the working directory '" + + original_cwd.string() + "'")}; + } + return {}; +} + +int run_sandbox_exec(int argc, char **argv) { + // Expected: vbs __sandbox-exec -- [args...] + int index = 2; + if (index < argc && std::string_view{argv[index]} == "--") { + ++index; + } + if (index >= argc) { + std::fprintf(stderr, "vbs __sandbox-exec: missing command\n"); + return 125; + } + SandboxOptions options; + options.project_root = Void::Configuration::get_env_or("VBS_SANDBOX_PROJECT", ""); + options.build_root = Void::Configuration::get_env_or("VBS_SANDBOX_BUILD", ""); + options.allow_network = Void::Configuration::get_env_or("VBS_SANDBOX_NET", "0") == "1"; + const std::string roots = Void::Configuration::get_env_or("VBS_SANDBOX_ROOTS", ""); + for (const auto part : Void::Str::split(roots, ':')) { + if (!part.empty()) { + options.read_only_roots.emplace_back(part); + } + } + auto applied = apply_sandbox(options); + if (!applied) { + std::fprintf(stderr, "%s\n", applied.error().message().c_str()); + return 125; + } + if (Void::Configuration::get_env_or("VBS_SANDBOX_DEBUG", "") == "1") { + std::error_code dbg; + std::array cwd{}; + (void)::getcwd(cwd.data(), cwd.size()); + std::fprintf(stderr, + "sandbox debug: cwd=%s project=%d build=%d snapshots=%d trees=%d\n", + cwd.data(), + static_cast(std::filesystem::exists(options.project_root, dbg)), + static_cast(std::filesystem::exists(options.build_root, dbg)), + static_cast(std::filesystem::exists(options.build_root / ".vbs" / + "snapshots", dbg)), + static_cast(std::filesystem::exists( + options.build_root / ".vbs" / "snapshots" / "trees", dbg))); + } + ::execv(argv[index], &argv[index]); + std::fprintf(stderr, "vbs __sandbox-exec: exec '%s' failed: %s\n", argv[index], + std::strerror(errno)); + return 125; +} + +#else + +bool sandbox_supported() { return false; } + +Void::Result::Result +apply_sandbox(const SandboxOptions &) { + return std::unexpected{make_error("sandbox: hermetic sandboxing requires a Linux host")}; +} + +int run_sandbox_exec(int, char **) { + std::fprintf(stderr, "vbs __sandbox-exec: hermetic sandboxing requires a Linux host\n"); + return 125; +} + +#endif + +} // namespace Void::Build::Sandbox diff --git a/tests/CliContracts.cmake b/tests/CliContracts.cmake index 96f63de..0224796 100644 --- a/tests/CliContracts.cmake +++ b/tests/CliContracts.cmake @@ -51,6 +51,8 @@ check_process(0 "Usage: vbs remove " "" remove --help) check_process(0 "--frozen" "" build --help) check_process(0 "--native-cache" "" build --help) check_process(0 "--bep" "" build --help) +check_process(0 "--sandbox" "" build --help) +check_process(2 "" "invalid value 'bogus' for '--sandbox'" build --sandbox bogus) check_process(0 "Usage: vbs new " "" new --help) check_process(2 "" "unsupported --native-cache" build --native-cache bogus) check_process(2 "" "invalid version range" add fmt@bad --no-lock) @@ -69,6 +71,7 @@ check_process(0 "Usage: vbs clean " "" clean --help) check_process(0 "Usage: vbs doctor " "" doctor --help) check_process(0 "host platform: (Linux|Windows)" "" doctor) check_process(0 "Void::Sqlite: (enabled|disabled)" "" doctor) +check_process(0 "hermetic sandbox: (user namespaces available|unavailable)" "" doctor) check_process(0 "Usage: vbs graph " "" graph --help) check_process(2 "" "unsupported --format" graph --format xml) check_process(2 "" "multi-profile build requires --editor-profile" build --profile debug --profile release) diff --git a/tests/FullV1Tests.cpp b/tests/FullV1Tests.cpp index 3564b41..4d8ce32 100644 --- a/tests/FullV1Tests.cpp +++ b/tests/FullV1Tests.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -4712,3 +4713,83 @@ void build(Void::Build::Project &p) { Void::Testing::expect(kinds.contains("build_finished")); Void::Testing::expect(saw_failing_test); } + +// === Hermetic sandboxing (F1): strict builds work, outside files are invisible === +VOID_TEST(FullV1Tests, sandbox_strict_allows_project_builds_and_hides_outside_files) { + const auto vbs_bin = locate_vbs_binary(); + Void::Testing::expect(!vbs_bin.empty() && std::filesystem::exists(vbs_bin)); + if (vbs_bin.empty() || !std::filesystem::exists(vbs_bin)) { + return; + } + if (!Sandbox::sandbox_supported()) { + return; // Unprivileged user namespaces are unavailable on this host. + } + Void::FileSystem::TempDir tmp{"vbs_sandbox_"}; + const auto proj = tmp / "proj"; + const auto outside = tmp / "outside"; + const auto build_off = tmp / "build-off"; + const auto build_strict = tmp / "build-strict"; + write_file(outside / "secret.txt", "SANDBOX_SECRET\n"); + const std::string secret = (outside / "secret.txt").string(); + const std::string off_out = (build_off / "leak.out").string(); + const std::string strict_out = (build_strict / "leak.out").string(); + + write_file(proj / "build.cpp", "#include \n" + "void build(Void::Build::Project &p) {\n" + " p.executable(\"app\").cxx_standard(Void::Build::CxxStandard::Cxx26)" + ".sources({\"src/main.cpp\"});\n" + " p.custom_action(\"leak_off\")\n" + " .command({\"/bin/sh\", \"-c\", \"cat " + + secret + " > " + off_out + + "\"})\n" + " .outputs({\"" + + off_out + + "\"})\n" + " .nondeterministic(true);\n" + " p.custom_action(\"leak_strict\")\n" + " .command({\"/bin/sh\", \"-c\", \"cat " + + secret + " > " + strict_out + + "\"})\n" + " .outputs({\"" + + strict_out + + "\"})\n" + " .nondeterministic(true);\n" + "}\n"); + write_file(proj / "src" / "main.cpp", "int main() { return 0; }\n"); + + auto run_vbs = [&](std::vector args) { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = std::move(args); + req.timeout = std::chrono::seconds{600}; + return Platform::run_supervised(req); + }; + + // A normal project builds inside the strict sandbox. + auto strict_build = run_vbs({"build", "--project", proj.string(), "--build-dir", + (tmp / "build-app").string(), "--target", "app", "--jobs", + "2", "--sandbox", "strict"}); + Void::Testing::expect(strict_build.has_value() && strict_build->succeeded()); + if (strict_build && !strict_build->succeeded()) { + std::cerr << "strict build failed:\n" << strict_build->stderr_data << '\n'; + } + + // Without the sandbox the action reads the outside file. + auto off = run_vbs({"build", "--project", proj.string(), "--build-dir", build_off.string(), + "--target", "leak_off", "--sandbox", "off"}); + Void::Testing::expect(off.has_value() && off->succeeded()); + auto leaked = Void::FileSystem::read_file(build_off / "leak.out"); + Void::Testing::require(leaked.has_value()); + Void::Testing::expect(leaked->find("SANDBOX_SECRET") != std::string::npos); + + // With the strict sandbox the same action cannot see the outside file. + auto strict_leak = run_vbs({"build", "--project", proj.string(), "--build-dir", + build_strict.string(), "--target", "leak_strict", "--sandbox", + "strict"}); + Void::Testing::expect(strict_leak.has_value() && !strict_leak->succeeded()); + if (strict_leak) { + const std::string output = strict_leak->stdout_data + strict_leak->stderr_data; + Void::Testing::expect(output.find("No such file") != std::string::npos || + output.find("not found") != std::string::npos); + } +}