From c553565b989b80132fb31f8d46192bb74137ca54 Mon Sep 17 00:00:00 2001 From: Dave Lane <42013603+ReenigneArcher@users.noreply.github.com> Date: Sun, 13 Sep 2026 16:37:49 -0400 Subject: [PATCH] Merge commit from fork Sanitize GUI loader and plugin environment variables before privileged initialization, failing closed when the environment cannot be cleaned. Retain CAP_SYS_ADMIN only on a dedicated DRM worker, route KMS and CUDA DRM access through it, reject queued work safely during overflow or shutdown, and drop the worker privileges when DRM access is no longer needed. Add Linux regression coverage for the sanitizer and document the new privileged-worker interfaces. Co-authored-by: Conn O'Griofa <749000+psyke83@users.noreply.github.com> Co-authored-by: Kishi <41839133+Kishi85@users.noreply.github.com> --- src/main.cpp | 32 ++++ src/platform/linux/cuda.cpp | 2 +- src/platform/linux/kmsgrab.cpp | 190 ++++++++++++++++++++---- src/platform/linux/misc.cpp | 43 +++++- src/platform/linux/misc.h | 36 +++++ src/thread_safe.h | 32 +++- tests/unit/platform/linux/test_misc.cpp | 95 ++++++++++++ 7 files changed, 389 insertions(+), 41 deletions(-) create mode 100644 tests/unit/platform/linux/test_misc.cpp diff --git a/src/main.cpp b/src/main.cpp index 22ede57d7..ff0f015e6 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3,15 +3,21 @@ * @brief Definitions for the main entry point for Sunshine. */ // standard includes +#include #include #include +#include #include #include #include +// platform includes #ifdef __APPLE__ #include #endif +#ifdef __linux__ + #include +#endif // lib includes #include @@ -33,6 +39,11 @@ #include "upnp.h" #include "video.h" +#ifdef __linux__ + #include "platform/common.h" + #include "platform/linux/misc.h" +#endif + using namespace std::literals; std::map> signal_handlers; ///< Signal handlers. @@ -166,6 +177,14 @@ void mainThreadLoop(const std::shared_ptr> &shutdown_event) * @return Process or platform callback exit code. */ int main(int argc, char *argv[]) { +#ifdef __linux__ + const bool privileged_execution = getauxval(AT_SECURE) != 0 || platf::has_elevated_privileges(true); + if (privileged_execution && !platf::sanitize_process_environment()) { + std::cerr << "Failed to sanitize the environment for privileged execution: " << std::strerror(errno) << '\n'; + return 1; + } +#endif + #ifdef __APPLE__ // Bundle assets are referenced relative to the executable // (e.g. ../Resources/assets), so anchor cwd to Contents/MacOS. @@ -184,6 +203,19 @@ int main(int argc, char *argv[]) { } } #endif +#if defined(__linux__) + // On Linux, child threads inherit capabilities from the parent at creation time. + // We ensure the privileged worker starts while capabilities are still held, + // and then immediately strip global privileges from the main thread and future tasks. + // Please ensure that these calls remain ordered as early as possible in startup initialization. + #if defined(SUNSHINE_BUILD_DRM) + platf::kms::ensure_privileged_drm_worker_started(); + #endif + // Check and drop capabilities but use 'false' to retain CAP_SYS_NICE for EGL high priority contexts + if (platf::has_elevated_privileges(false)) { + platf::drop_elevated_privileges(false); + } +#endif lifetime::argv = argv; diff --git a/src/platform/linux/cuda.cpp b/src/platform/linux/cuda.cpp index 7da5669d9..931f181e5 100644 --- a/src/platform/linux/cuda.cpp +++ b/src/platform/linux/cuda.cpp @@ -382,7 +382,7 @@ namespace cuda { fs::path dri_path {"/dev/dri"sv}; auto device_path = dri_path / file; - return platf::open_drm_card_fd(device_path); + return platf::kms::privileged_open_drm_card_fd(device_path); } } catch (const std::filesystem::filesystem_error &err) { BOOST_LOG(error) << "Failed to read sysfs: "sv << err.what(); diff --git a/src/platform/linux/kmsgrab.cpp b/src/platform/linux/kmsgrab.cpp index d106f4099..a3364b234 100644 --- a/src/platform/linux/kmsgrab.cpp +++ b/src/platform/linux/kmsgrab.cpp @@ -38,30 +38,171 @@ namespace platf { namespace kms { + namespace { // Keep privileged implementation details anonymous/local to this translation unit + +#if !defined(__FreeBSD__) + /** + * @brief Temporarily owns CAP_SYS_ADMIN while opening DRM capture resources. + */ + class cap_sys_admin { + public: + cap_sys_admin() { + caps = cap_get_proc(); + + cap_value_t sys_admin = CAP_SYS_ADMIN; + if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &sys_admin, CAP_SET) || cap_set_proc(caps)) { + BOOST_LOG(error) << "Failed to gain CAP_SYS_ADMIN"; + } + } + + ~cap_sys_admin() { + cap_value_t sys_admin = CAP_SYS_ADMIN; + if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &sys_admin, CAP_CLEAR) || cap_set_proc(caps)) { + BOOST_LOG(error) << "Failed to drop CAP_SYS_ADMIN"; + } + cap_free(caps); + } + + cap_t caps; ///< Caps. + }; +#endif + + /** + * @brief Set up privileged worker thread exclusively for handling DRM capture resources. + */ + class privileged_drm_worker { + public: + static void ensure_started() { + instance(); + } + + static void drop_worker_privileges() { + instance().drop_privileges(); + } + + // deliberately align prototype to match path signature via init(const char *path) + static int open_drm_card_fd_privileged(const char *path) { + try { + return instance().run([=]() -> int { + return platf::open_drm_card_fd(path); + }); + } catch (const std::runtime_error &) { + return -1; + } + } + + static drmModeFB2Ptr drmModeGetFB2_privileged(int fd, uint32_t bufferId) { + try { + return instance().run([&]() -> drmModeFB2Ptr { + return drmModeGetFB2(fd, bufferId); + }); + } catch (const std::runtime_error &) { + return nullptr; + } + } + + static drmModeFBPtr drmModeGetFB_privileged(int fd, uint32_t bufferId) { + try { + return instance().run([&]() -> drmModeFBPtr { + return drmModeGetFB(fd, bufferId); + }); + } catch (const std::runtime_error &) { + return nullptr; + } + } + + private: + static privileged_drm_worker &instance() { + static privileged_drm_worker w; + return w; + } + + void drop_privileges() { + instance().run([]() -> void { + platf::drop_elevated_privileges(true); + }); + } + + privileged_drm_worker() { + thread_ = std::thread([this] { + sigset_t all; + sigfillset(&all); + if (pthread_sigmask(SIG_BLOCK, &all, nullptr) != 0) { + BOOST_LOG(error) << "Failed to block signals in drm_worker"sv; + queue_.stop(); + return; + } + + platf::set_thread_name("drm_worker"); + for (;;) { + auto task = queue_.pop(); + if (!task) { + break; + } + (*task)(); + } + }); + } + + ~privileged_drm_worker() { + queue_.stop(); + if (thread_.joinable()) { + thread_.join(); + } + } + + template + auto run(F &&f) -> std::invoke_result_t { + using R = std::invoke_result_t; + auto task = std::make_shared>( + [f = std::forward(f)]() mutable -> R { +#if !defined(__FreeBSD__) + cap_sys_admin admin; +#endif + return f(); + } + ); + auto fut = task->get_future(); + + if (!queue_.raise([task]() mutable { + (*task)(); + })) { + throw std::runtime_error("privileged_drm_worker: task rejected (worker stopping)"); + } + + return fut.get(); + } + + safe::queue_t> queue_ {32, safe::queue_t>::overflow_policy_e::reject}; + std::thread thread_; + }; + } // namespace + +#if defined(__linux__) /** - * @brief Temporarily owns CAP_SYS_ADMIN while opening DRM capture resources. + * @brief Open a DRM card file descriptor using the privileged DRM worker. + * + * @param path Path to the DRM card node. + * @return A file descriptor on success, or `-1` on failure. */ - class cap_sys_admin { - public: - cap_sys_admin() { - caps = cap_get_proc(); + int privileged_open_drm_card_fd(const char *path) { + return privileged_drm_worker::open_drm_card_fd_privileged(path); + } - cap_value_t sys_admin = CAP_SYS_ADMIN; - if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &sys_admin, CAP_SET) || cap_set_proc(caps)) { - BOOST_LOG(error) << "Failed to gain CAP_SYS_ADMIN"; - } - } + /** + * @brief Allows the DRM privileged_drm_worker thread to be constructed early. + */ + void ensure_privileged_drm_worker_started() { + privileged_drm_worker::ensure_started(); + } - ~cap_sys_admin() { - cap_value_t sys_admin = CAP_SYS_ADMIN; - if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &sys_admin, CAP_CLEAR) || cap_set_proc(caps)) { - BOOST_LOG(error) << "Failed to drop CAP_SYS_ADMIN"; - } - cap_free(caps); - } - - cap_t caps; ///< Caps. - }; + /** + * @brief Allows the DRM privileged_drm_worker thread to drop privileges. + */ + void drop_drm_worker_privileges() { + privileged_drm_worker::drop_worker_privileges(); + } +#endif /** * @brief RAII wrapper for DRM framebuffer metadata and GEM handles. @@ -436,8 +577,7 @@ namespace platf { * @return 0 on success; nonzero or negative platform status on failure. */ int init(const char *path) { - cap_sys_admin admin; - fd.el = open_drm_card_fd(path); + fd.el = platf::kms::privileged_drm_worker::open_drm_card_fd_privileged(path); if (fd.el < 0) { return -1; } @@ -495,14 +635,12 @@ namespace platf { * @return Framebuffer metadata wrapper, or nullptr when the framebuffer cannot be read. */ fb_t fb(plane_t::pointer plane) { - cap_sys_admin admin; - - auto fb2 = drmModeGetFB2(fd.el, plane->fb_id); + auto fb2 = platf::kms::privileged_drm_worker::drmModeGetFB2_privileged(fd.el, plane->fb_id); if (fb2) { return std::make_unique(fd.el, fb2); } - auto fb = drmModeGetFB(fd.el, plane->fb_id); + auto fb = platf::kms::privileged_drm_worker::drmModeGetFB_privileged(fd.el, plane->fb_id); if (fb) { return std::make_unique(fd.el, fb); } diff --git a/src/platform/linux/misc.cpp b/src/platform/linux/misc.cpp index de36d54a4..ca32309da 100644 --- a/src/platform/linux/misc.cpp +++ b/src/platform/linux/misc.cpp @@ -13,6 +13,7 @@ #endif // standard includes +#include #include #include #include @@ -151,6 +152,33 @@ namespace dyn { } // namespace dyn namespace platf { + namespace { + constexpr std::array privileged_gui_environment_variables { + "GDK_PIXBUF_MODULEDIR", + "GDK_PIXBUF_MODULE_FILE", + "GIO_EXTRA_MODULES", + "GTK3_MODULES", + "GTK_EXE_PREFIX", + "GTK_IM_MODULE_FILE", + "GTK_MODULES", + "GTK_PATH", + "QML2_IMPORT_PATH", + "QML_IMPORT_PATH", + "QT_PLUGIN_PATH", + "QT_QPA_PLATFORM_PLUGIN_PATH", + }; + + } // namespace + + bool sanitize_process_environment() { + for (const auto *variable : privileged_gui_environment_variables) { + if (unsetenv(variable) != 0) { + return false; + } + } + return true; + } + /** * @brief Owning pointer for `getifaddrs` results. */ @@ -1262,7 +1290,9 @@ namespace platf { } std::shared_ptr display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config) { - // Keep KMS as first element to check before dropping CAP_SYS_ADMIN + // Please ensure that KMS followed by CUDA remains at the top so that we can + // drop DRM worker privileges once neither backend requires it. + #ifdef SUNSHINE_BUILD_DRM if (sources[source::KMS]) { BOOST_LOG(info) << "Screencasting with KMS"sv; @@ -1270,17 +1300,18 @@ namespace platf { } #endif - // KMS capture was passed; drop CAP_SYS_ADMIN only. - if (has_elevated_privileges(false)) { - drop_elevated_privileges(false); - } - #ifdef SUNSHINE_BUILD_CUDA if (sources[source::NVFBC] && hwdevice_type == mem_type_e::cuda) { BOOST_LOG(info) << "Screencasting with NvFBC"sv; return nvfbc_display(hwdevice_type, display_name, config); } #endif + +#ifdef SUNSHINE_BUILD_DRM + // Drop all DRM worker thread privileges if not needed for this process's lifetime. + platf::kms::drop_drm_worker_privileges(); +#endif + #ifdef SUNSHINE_BUILD_WAYLAND if (sources[source::WAYLAND]) { BOOST_LOG(info) << "Screencasting with Wayland's protocol"sv; diff --git a/src/platform/linux/misc.h b/src/platform/linux/misc.h index 5b8526768..c27932a3c 100644 --- a/src/platform/linux/misc.h +++ b/src/platform/linux/misc.h @@ -51,6 +51,16 @@ namespace dyn { } // namespace dyn namespace platf { + /** + * @brief Remove environment variables that can load untrusted GUI modules. + * + * Loader paths and module lists used by Qt, GTK, GIO, and GdkPixbuf are removed before any of those libraries + * can initialize. The caller determines whether privileged execution requires the policy. + * + * @return `true` when the environment is safe to use; `false` if a variable could not be removed. + */ + bool sanitize_process_environment(); + /** * @brief Open a DRM card node and drop implicit DRM master, if any. * @@ -93,4 +103,30 @@ namespace platf { next_frame = now + delay; } } + +#if defined(__linux__) && defined(SUNSHINE_BUILD_DRM) + namespace kms { + /** + * @brief Force-construct the DRM privileged worker thread while the calling + * thread still holds CAP_SYS_ADMIN in CAP_PERMITTED. + * + * This must be called before dropping CAP_SYS_ADMIN from the calling thread, + * since newly-created threads inherit its capability sets. + */ + void ensure_privileged_drm_worker_started(); + + /** + * @brief Drop the DRM worker thread's privileges. + */ + void drop_drm_worker_privileges(); + + /** + * @brief Open a DRM card file descriptor using the privileged DRM worker. + * + * @param path Path to the DRM card node. + * @return A file descriptor on success, or `-1` on failure. + */ + int privileged_open_drm_card_fd(const char *path); + } // namespace kms +#endif } // namespace platf diff --git a/src/thread_safe.h b/src/thread_safe.h index de0fa9ecc..a7e384fba 100644 --- a/src/thread_safe.h +++ b/src/thread_safe.h @@ -395,35 +395,50 @@ namespace safe { */ using status_t = util::optional_t; + /** + * @brief Behavior when raise() is called with the queue already at its bound. + */ + enum class overflow_policy_e { + drop_oldest, ///< Clear the queue and accept the new item (current default behavior) + reject ///< Refuse the new item, leaving existing queued items intact + }; + /** * @brief Construct a bounded blocking queue. * - * @param max_elements Maximum number of queued elements before producers block. + * @param max_elements Maximum number of elements that may be queued. + * @param overflow Behavior when the queue reaches its maximum size. */ - queue_t(std::uint32_t max_elements = 32): - _max_elements {max_elements} { + queue_t(std::uint32_t max_elements = 32, overflow_policy_e overflow = overflow_policy_e::drop_oldest): + _max_elements {max_elements}, + _overflow_policy {overflow} { } /** - * @brief Notify waiters that a new event value is available. + * @brief Notify waiters that a new event value may be available. * * @param args Arguments forwarded to the callable or parser. + * @return True if the item was queued, false if the queue is stopped or the + * configured overflow policy rejects the item. */ template - void raise(Args &&...args) { + bool raise(Args &&...args) { std::lock_guard ul {_lock}; if (!_continue) { - return; + return false; } - if (_queue.size() == _max_elements) { + if (_queue.size() >= _max_elements) { + if (_overflow_policy == overflow_policy_e::reject) { + return false; + } _queue.clear(); } _queue.emplace_back(std::forward(args)...); - _cv.notify_all(); + return true; } /** @@ -524,6 +539,7 @@ namespace safe { std::condition_variable _cv; std::vector _queue; + overflow_policy_e _overflow_policy; }; /** diff --git a/tests/unit/platform/linux/test_misc.cpp b/tests/unit/platform/linux/test_misc.cpp new file mode 100644 index 000000000..df6b25be4 --- /dev/null +++ b/tests/unit/platform/linux/test_misc.cpp @@ -0,0 +1,95 @@ +/** + * @file tests/unit/platform/linux/test_misc.cpp + * @brief Tests for Linux platform utility functions. + */ + +#ifdef __linux__ + + // standard includes + #include + #include + #include + #include + + // lib includes + #include + + // local includes + #include "src/platform/linux/misc.h" + +namespace { + /** + * @brief Restore one environment variable when a test scope ends. + */ + class environment_guard_t { + public: + /** + * @brief Save the current value of an environment variable. + * + * @param name Environment variable name to restore. + */ + explicit environment_guard_t(const char *name): + name_ {name} { + if (const char *value = std::getenv(name)) { + value_ = value; + } + } + + /** + * @brief Restore the saved value or remove the variable when it was originally absent. + */ + ~environment_guard_t() { + if (value_) { + setenv(name_.c_str(), value_->c_str(), 1); + } else { + unsetenv(name_.c_str()); + } + } + + private: + std::string name_; ///< Environment variable name. + std::optional value_; ///< Value present before the test changed the environment. + }; + + constexpr std::array unsafe_environment_variables { + "GDK_PIXBUF_MODULEDIR", + "GDK_PIXBUF_MODULE_FILE", + "GIO_EXTRA_MODULES", + "GTK3_MODULES", + "GTK_EXE_PREFIX", + "GTK_IM_MODULE_FILE", + "GTK_MODULES", + "GTK_PATH", + "QML2_IMPORT_PATH", + "QML_IMPORT_PATH", + "QT_PLUGIN_PATH", + "QT_QPA_PLATFORM_PLUGIN_PATH", + }; +} // namespace + +TEST(ProcessEnvironmentSecurity, RemovesModuleLoaders) { + std::array, unsafe_environment_variables.size()> guards; + for (std::size_t index = 0; index < unsafe_environment_variables.size(); ++index) { + const auto *variable = unsafe_environment_variables[index]; + guards[index].emplace(variable); + ASSERT_EQ(setenv(variable, "/tmp/untrusted-module", 1), 0); + } + + ASSERT_TRUE(platf::sanitize_process_environment()); + for (const auto *variable : unsafe_environment_variables) { + EXPECT_EQ(std::getenv(variable), nullptr) << variable; + } +} + +TEST(ProcessEnvironmentSecurity, PreservesTraySessionVariables) { + environment_guard_t platform_theme_guard {"QT_QPA_PLATFORMTHEME"}; + environment_guard_t wayland_display_guard {"WAYLAND_DISPLAY"}; + ASSERT_EQ(setenv("QT_QPA_PLATFORMTHEME", "gtk3", 1), 0); + ASSERT_EQ(setenv("WAYLAND_DISPLAY", "wayland-test", 1), 0); + + ASSERT_TRUE(platf::sanitize_process_environment()); + EXPECT_STREQ(std::getenv("QT_QPA_PLATFORMTHEME"), "gtk3"); + EXPECT_STREQ(std::getenv("WAYLAND_DISPLAY"), "wayland-test"); +} + +#endif // __linux__