diff --git a/CMakeLists.txt b/CMakeLists.txt index 6d28b35..b018190 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -27,6 +27,8 @@ target_sources( browser-client.hpp browser-dummy-client.cpp browser-dummy-client.hpp + browser-sandbox.cpp + browser-sandbox.hpp browser-scheme.cpp browser-scheme.hpp browser-version.h diff --git a/browser-sandbox.cpp b/browser-sandbox.cpp new file mode 100644 index 0000000..079d8d4 --- /dev/null +++ b/browser-sandbox.cpp @@ -0,0 +1,182 @@ +/****************************************************************************** + Copyright (C) 2026 by Volker Pacher + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + ******************************************************************************/ + +#include "browser-sandbox.hpp" + +#ifdef __linux__ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +SandboxDecision DecideSandbox(const SandboxProbe &probe) +{ + if (!probe.supported) { + return {SandboxMode::Off, "no sandbox probe on this platform"}; + } + + /* Chromium does not run sandboxed as root: it exits the process. */ + if (probe.root) { + return {SandboxMode::Off, "OBS runs as root"}; + } + + /* Chromium prefers the namespace sandbox and then ignores the helper. */ + if (probe.user_namespaces) { + return {SandboxMode::Namespaces, "user namespaces are available"}; + } + + switch (probe.helper) { + case SandboxHelper::SetuidRoot: + return {SandboxMode::SetuidHelper, "no user namespaces; chrome-sandbox is setuid root"}; + case SandboxHelper::NotSetuid: + /* Chromium aborts on a helper it cannot use, instead of + * running without the sandbox. */ + return {SandboxMode::Off, "no user namespaces, and chrome-sandbox is not setuid root"}; + case SandboxHelper::Absent: + break; + } + return {SandboxMode::Off, "no user namespaces and no chrome-sandbox"}; +} + +bool SandboxFallback(const SandboxProbe &probe, const SandboxDecision &decision) +{ + return probe.supported && decision.mode == SandboxMode::Off; +} + +#ifdef __linux__ +namespace { + +/* Only async-signal-safe calls: the child of fork in a threaded process. */ +bool WriteAll(const char *path, const char *text) +{ + int fd = open(path, O_WRONLY | O_CLOEXEC); + if (fd < 0) { + return false; + } + size_t len = strlen(text); + bool ok = write(fd, text, len) == static_cast(len); + close(fd); + return ok; +} + +/* "0 1" into buf, without snprintf (not async-signal-safe). */ +void FormatMap(char *buf, unsigned id) +{ + char digits[16]; + int n = 0; + do { + digits[n++] = static_cast('0' + id % 10); + id /= 10; + } while (id); + char *p = buf; + *p++ = '0'; + *p++ = ' '; + while (n) { + *p++ = digits[--n]; + } + *p++ = ' '; + *p++ = '1'; + *p = 0; +} + +/* What Chromium's namespace sandbox does: new user, PID and network + * namespaces, then a map of its own uid and gid. A sysctl alone misses the + * AppArmor restriction (Ubuntu 24.04+) and seccomp filters (systemd + * RestrictNamespaces); this runs the operations themselves, in a child. */ +bool ProbeUserNamespaces() +{ + unsigned uid = geteuid(); + unsigned gid = getegid(); + char uid_map[32]; + char gid_map[32]; + FormatMap(uid_map, uid); + FormatMap(gid_map, gid); + + pid_t pid = fork(); + if (pid < 0) { + return false; + } + if (pid == 0) { + if (unshare(CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNET) != 0) { + _exit(1); + } + if (!WriteAll("/proc/self/setgroups", "deny")) { + _exit(2); + } + if (!WriteAll("/proc/self/uid_map", uid_map)) { + _exit(3); + } + if (!WriteAll("/proc/self/gid_map", gid_map)) { + _exit(4); + } + _exit(0); + } + + int status = 0; + while (waitpid(pid, &status, 0) < 0) { + if (errno != EINTR) { + return false; + } + } + return WIFEXITED(status) && WEXITSTATUS(status) == 0; +} + +/* Chromium looks for chrome-sandbox next to libcef, or at + * CHROME_DEVEL_SANDBOX. The kernel ignores the setuid bit on a nosuid + * mount. */ +SandboxHelper ProbeHelper(const std::string &cef_dir) +{ + const char *devel = getenv("CHROME_DEVEL_SANDBOX"); + std::string path = devel && *devel ? devel : cef_dir + "/chrome-sandbox"; + + struct stat st; + if (stat(path.c_str(), &st) != 0) { + return SandboxHelper::Absent; + } + + struct statvfs vfs; + bool nosuid = statvfs(path.c_str(), &vfs) == 0 && (vfs.f_flag & ST_NOSUID); + if (S_ISREG(st.st_mode) && st.st_uid == 0 && (st.st_mode & S_ISUID) && (st.st_mode & S_IXOTH) && !nosuid) { + return SandboxHelper::SetuidRoot; + } + return SandboxHelper::NotSetuid; +} + +} // namespace + +SandboxProbe ProbeSandbox(const std::string &cef_dir) +{ + SandboxProbe probe; + probe.supported = true; + probe.root = geteuid() == 0; + /* As root the decision is off anyway; do not fork for nothing. */ + probe.user_namespaces = !probe.root && ProbeUserNamespaces(); + probe.helper = ProbeHelper(cef_dir); + return probe; +} +#else +SandboxProbe ProbeSandbox(const std::string &) +{ + return {}; +} +#endif diff --git a/browser-sandbox.hpp b/browser-sandbox.hpp new file mode 100644 index 0000000..f904505 --- /dev/null +++ b/browser-sandbox.hpp @@ -0,0 +1,62 @@ +/****************************************************************************** + Copyright (C) 2026 by Volker Pacher + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + ******************************************************************************/ + +#pragma once + +#include + +/* Whether the CEF sandbox can work, decided before CefInitialize + * (obs-rust/obs-studio#1092). With the sandbox on, Chromium exits the whole + * process when it cannot sandbox: as root, and when it finds no user + * namespaces and a chrome-sandbox helper that is not setuid root. */ + +enum class SandboxHelper { + Absent, /* no chrome-sandbox next to libcef */ + SetuidRoot, /* owned by root, setuid, executable */ + NotSetuid, /* present, but Chromium cannot use it */ +}; + +/* The facts the decision uses. ProbeSandbox fills them on Linux. */ +struct SandboxProbe { + bool supported = false; /* a probe exists for this platform */ + bool root = false; /* the effective user is root */ + bool user_namespaces = false; /* a child can create user, PID and network namespaces and map its uid */ + SandboxHelper helper = SandboxHelper::Absent; +}; + +enum class SandboxMode { + Off, /* settings.no_sandbox = true */ + Namespaces, /* Chromium's user namespace sandbox */ + SetuidHelper, /* Chromium's setuid chrome-sandbox helper */ +}; + +struct SandboxDecision { + SandboxMode mode; + const char *reason; /* for the log */ +}; + +/* Pure: the same probe gives the same decision. */ +SandboxDecision DecideSandbox(const SandboxProbe &probe); + +/* The fallback (B in obs-rust/obs-studio#1092): a probe says the sandbox + * cannot work, so the browser runs without it, and the user is warned. + * Without a probe (Windows, macOS for now) the sandbox is off as before, + * and only the log says so. */ +bool SandboxFallback(const SandboxProbe &probe, const SandboxDecision &decision); + +/* cef_dir: the directory of libcef (and of chrome-sandbox). */ +SandboxProbe ProbeSandbox(const std::string &cef_dir); diff --git a/obs-browser-plugin.cpp b/obs-browser-plugin.cpp index a26112f..358e4ed 100644 --- a/obs-browser-plugin.cpp +++ b/obs-browser-plugin.cpp @@ -33,6 +33,7 @@ #include "obs-browser-source.hpp" #include "browser-scheme.hpp" #include "browser-app.hpp" +#include "browser-sandbox.hpp" #include "browser-version.h" #include "cef-headers.hpp" @@ -57,6 +58,7 @@ #if !defined(_WIN32) && !defined(__APPLE__) #include "drm-format.hpp" +#include #endif OBS_DECLARE_MODULE() @@ -275,6 +277,32 @@ static obs_missing_files_t *browser_source_missingfiles(void *data) static CefRefPtr app; +/* The CEF sandbox only where it can work (obs-rust/obs-studio#1092); + * otherwise as before, with the reason in the log. When a probe says it + * cannot work, the reason is an error line, which also goes to stderr. */ +static bool UseCefSandbox(void) +{ + std::string cef_dir; +#if !defined(_WIN32) && !defined(__APPLE__) + Dl_info info; + if (dladdr(reinterpret_cast(&cef_version_info), &info) && info.dli_fname) { + cef_dir = info.dli_fname; + cef_dir = cef_dir.substr(0, cef_dir.find_last_of('/')); + } +#endif + SandboxProbe probe = ProbeSandbox(cef_dir); + SandboxDecision decision = DecideSandbox(probe); + if (SandboxFallback(probe, decision)) { + /* LOG_ERROR: OBS echoes it to stderr; the browser continues. */ + blog(LOG_ERROR, "[obs-browser]: CEF sandbox off: %s. Browser sources run without the sandbox.", + decision.reason); + } else { + blog(LOG_INFO, "[obs-browser]: CEF sandbox %s: %s", decision.mode == SandboxMode::Off ? "off" : "on", + decision.reason); + } + return decision.mode != SandboxMode::Off; +} + static bool BrowserInit(void) { string path = obs_get_module_binary_path(obs_current_module()); @@ -299,7 +327,7 @@ static bool BrowserInit(void) BPtr log_path_abs = os_get_abs_path_ptr(log_path); CefString(&settings.log_file) = log_path_abs; settings.windowless_rendering_enabled = true; - settings.no_sandbox = true; + settings.no_sandbox = !UseCefSandbox(); #if CHROME_VERSION_BUILD > 6533 && CHROME_VERSION_BUILD <= 6613 settings.chrome_runtime = true; #endif diff --git a/tests/README.md b/tests/README.md index 4e90d56..1bde383 100644 --- a/tests/README.md +++ b/tests/README.md @@ -58,3 +58,33 @@ This case requires a Chrome-runtime CEF profile singleton (validated with CEF releases shutdown, separating this path from the pre-initialization task race. It passes against both the original and fixed modules: this is characterization coverage for preserved failure behavior, not an additional unique RED case. + +## Sandbox decision + +`sandbox_decision.py` compiles `browser-sandbox.cpp` with +`sandbox-decision.cpp` and runs every case of the decision whether the CEF +sandbox can work (obs-rust/obs-studio#1092): root, user namespaces, and the +state of the `chrome-sandbox` helper. The decision is a pure function, so the +test needs no CEF, no libobs and no display, and runs on any platform: + +```sh +uv run --no-project python tests/sandbox_decision.py --output-dir /path/to/new-output +``` + +## Sandbox probe + +`sandbox_probe.py` compiles `browser-sandbox.cpp` with `sandbox-probe.cpp` and +prints what `ProbeSandbox` finds in this environment and the decision. Run it +as the user and in the setup to check; a command prefix after `--` runs the +probe through it: + +```sh +uv run --no-project python tests/sandbox_probe.py --output-dir /tmp/out --cef-dir /path/to/cef/dir \ + -- systemd-run --pipe --wait --quiet -p User=someone -p RestrictNamespaces=~user -- +``` + +Linux x86_64 (Debian 13 LXC container, kernel 7.0.14, CEF 7871 +`chrome-sandbox`): as root, off for every helper state; as a normal user, the +namespace sandbox for every helper state; as a normal user with +`RestrictNamespaces=~user`, off without a helper or with a helper that is not +setuid, and the setuid helper with a helper that is setuid root. diff --git a/tests/sandbox-decision.cpp b/tests/sandbox-decision.cpp new file mode 100644 index 0000000..6696e9b --- /dev/null +++ b/tests/sandbox-decision.cpp @@ -0,0 +1,86 @@ +#include +#include + +#include "browser-sandbox.hpp" + +namespace { + +int failures = 0; + +void Expect(const char *name, const SandboxProbe &probe, SandboxMode mode, const char *reason_part) +{ + SandboxDecision decision = DecideSandbox(probe); + bool reason_ok = decision.reason && std::strstr(decision.reason, reason_part); + if (decision.mode != mode || !reason_ok) { + std::fprintf(stderr, "FAIL %s: mode %d (expected %d), reason \"%s\" (expected to contain \"%s\")\n", + name, static_cast(decision.mode), static_cast(mode), + decision.reason ? decision.reason : "(null)", reason_part); + failures++; + } else { + std::printf("ok %s\n", name); + } +} + +void ExpectFallback(const char *name, const SandboxProbe &probe, bool fallback) +{ + bool got = SandboxFallback(probe, DecideSandbox(probe)); + if (got != fallback) { + std::fprintf(stderr, "FAIL fallback %s: %d (expected %d)\n", name, got, fallback); + failures++; + } else { + std::printf("ok fallback %s\n", name); + } +} + +SandboxProbe Probe(bool root, bool user_namespaces, SandboxHelper helper) +{ + SandboxProbe probe; + probe.supported = true; + probe.root = root; + probe.user_namespaces = user_namespaces; + probe.helper = helper; + return probe; +} + +} // namespace + +int main() +{ + /* No probe (Windows, macOS for now): as today. */ + Expect("unsupported platform", SandboxProbe{}, SandboxMode::Off, "platform"); + + /* Chromium exits the process when it runs sandboxed as root. */ + Expect("root, namespaces", Probe(true, true, SandboxHelper::Absent), SandboxMode::Off, "root"); + Expect("root, setuid helper", Probe(true, false, SandboxHelper::SetuidRoot), SandboxMode::Off, "root"); + + /* User namespaces: no helper needed. A helper that is not setuid does + * not matter here (measured on CEF 7871: renders sandboxed). */ + Expect("user, namespaces", Probe(false, true, SandboxHelper::Absent), SandboxMode::Namespaces, "namespace"); + Expect("user, namespaces, helper not setuid", Probe(false, true, SandboxHelper::NotSetuid), + SandboxMode::Namespaces, "namespace"); + Expect("user, namespaces, setuid helper", Probe(false, true, SandboxHelper::SetuidRoot), + SandboxMode::Namespaces, "namespace"); + + /* No user namespaces: only a setuid root helper works. Chromium aborts + * when it finds a helper that is not setuid. */ + Expect("user, no namespaces, setuid helper", Probe(false, false, SandboxHelper::SetuidRoot), + SandboxMode::SetuidHelper, "chrome-sandbox"); + Expect("user, no namespaces, helper not setuid", Probe(false, false, SandboxHelper::NotSetuid), + SandboxMode::Off, "not setuid"); + Expect("user, no namespaces, no helper", Probe(false, false, SandboxHelper::Absent), SandboxMode::Off, + "no user namespaces"); + + /* The fallback warns only where a probe said the sandbox cannot work. */ + ExpectFallback("unsupported platform", SandboxProbe{}, false); + ExpectFallback("root", Probe(true, true, SandboxHelper::Absent), true); + ExpectFallback("user, namespaces", Probe(false, true, SandboxHelper::Absent), false); + ExpectFallback("user, no namespaces, setuid helper", Probe(false, false, SandboxHelper::SetuidRoot), false); + ExpectFallback("user, no namespaces, helper not setuid", Probe(false, false, SandboxHelper::NotSetuid), true); + ExpectFallback("user, no namespaces, no helper", Probe(false, false, SandboxHelper::Absent), true); + + if (failures) { + std::fprintf(stderr, "%d case(s) failed\n", failures); + return 1; + } + return 0; +} diff --git a/tests/sandbox-probe.cpp b/tests/sandbox-probe.cpp new file mode 100644 index 0000000..7333ee3 --- /dev/null +++ b/tests/sandbox-probe.cpp @@ -0,0 +1,23 @@ +#include + +#include "browser-sandbox.hpp" + +/* Prints what ProbeSandbox finds here and what DecideSandbox makes of it. + * Argument: the directory to look for chrome-sandbox in. */ +int main(int argc, char **argv) +{ + if (argc != 2) { + std::fputs("usage: sandbox-probe \n", stderr); + return 2; + } + + static const char *helpers[] = {"absent", "setuid-root", "not-setuid"}; + static const char *modes[] = {"off", "namespaces", "setuid-helper"}; + + SandboxProbe probe = ProbeSandbox(argv[1]); + SandboxDecision decision = DecideSandbox(probe); + std::printf("supported=%d root=%d user_namespaces=%d helper=%s -> %s (%s)\n", probe.supported, probe.root, + probe.user_namespaces, helpers[static_cast(probe.helper)], + modes[static_cast(decision.mode)], decision.reason); + return 0; +} diff --git a/tests/sandbox_decision.py b/tests/sandbox_decision.py new file mode 100644 index 0000000..04ab5c9 --- /dev/null +++ b/tests/sandbox_decision.py @@ -0,0 +1,24 @@ +#!/usr/bin/env -S uv run --script +"""Compile the sandbox decision with its test and run every case.""" +import argparse +from pathlib import Path +import subprocess + +parser = argparse.ArgumentParser() +parser.add_argument("--output-dir", type=Path, required=True) +parser.add_argument("--cxx", default="c++") +args = parser.parse_args() +root = Path(__file__).resolve().parent.parent +output = args.output_dir.resolve() +output.mkdir(parents=True, exist_ok=True) +executable = output / "sandbox-decision" +subprocess.run( + [args.cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror", f"-I{root}", + str(root / "tests" / "sandbox-decision.cpp"), str(root / "browser-sandbox.cpp"), "-o", str(executable)], + check=True, +) +result = subprocess.run([str(executable)], capture_output=True, text=True, timeout=30) +print(result.stdout, end="") +print(result.stderr, end="") +if result.returncode: + raise SystemExit(f"sandbox decision check failed: exit {result.returncode}") diff --git a/tests/sandbox_probe.py b/tests/sandbox_probe.py new file mode 100644 index 0000000..f641a5f --- /dev/null +++ b/tests/sandbox_probe.py @@ -0,0 +1,31 @@ +#!/usr/bin/env -S uv run --script +"""Compile the sandbox probe and print what it finds in this environment.""" +import argparse +from pathlib import Path +import subprocess +import sys + +parser = argparse.ArgumentParser() +parser.add_argument("--output-dir", type=Path, required=True) +parser.add_argument("--cef-dir", type=Path, required=True, help="directory to look for chrome-sandbox in") +parser.add_argument("--cxx", default="c++") +# After "--": a command prefix to run the probe with, e.g. -- runuser -u someone -- +argv = sys.argv[1:] +run_as = argv[argv.index("--") + 1:] if "--" in argv else [] +args = parser.parse_args(argv[:argv.index("--")] if "--" in argv else argv) +root = Path(__file__).resolve().parent.parent +output = args.output_dir.resolve() +output.mkdir(parents=True, exist_ok=True) +executable = output / "sandbox-probe" +subprocess.run( + [args.cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror", f"-I{root}", + str(root / "tests" / "sandbox-probe.cpp"), str(root / "browser-sandbox.cpp"), "-o", str(executable)], + check=True, +) +executable.chmod(0o755) +result = subprocess.run([*run_as, str(executable), str(args.cef_dir.resolve())], capture_output=True, text=True, + timeout=30) +print(result.stdout, end="") +print(result.stderr, end="") +if result.returncode: + raise SystemExit(f"sandbox probe failed: exit {result.returncode}")