diff --git a/src/slic3r/plugin/PluginAuditManager.cpp b/src/slic3r/plugin/PluginAuditManager.cpp index bd2ddf99e2..f96bbe4bb0 100644 --- a/src/slic3r/plugin/PluginAuditManager.cpp +++ b/src/slic3r/plugin/PluginAuditManager.cpp @@ -848,9 +848,78 @@ std::string event_grant_key(AuditEventCategory category, const std::string& even return std::string(category_name(category)) + ":" + event_name; } -bool has_permission(const std::vector& granted, const std::string& target) +// The directory named by a directory-tree grant, i.e. "/*". "*" is the only wildcard, and +// only as the grant's final path component; any other "*" is an ordinary character, so a grant +// can never widen into a pattern the plugin did not spell out. Returns false for a grant that is +// not a tree grant. +bool tree_grant_root(const std::string& grant, boost::filesystem::path& root) { - return std::find(granted.begin(), granted.end(), target) != granted.end(); + if (grant.size() < 2 || grant.back() != '*' || grant.find('*') != grant.size() - 1) + return false; + + const boost::filesystem::path path(grant); + if (path.filename() != "*") + return false; + + const boost::filesystem::path parent = path.parent_path(); + if (parent.empty()) + return false; + + // Never resolve ".." here: a grant shown to the user as "/a/../*" must not silently become + // the root or another ancestor. Without a wildcard the string still matches verbatim. + for (const boost::filesystem::path& component : parent) { + if (component == "..") + return false; + } + + // Rebuild from the components so "." and duplicate separators do not affect the canonical + // comparison below. + boost::filesystem::path normalized; + for (const boost::filesystem::path& component : parent.lexically_normal()) { + if (!component.empty()) + normalized /= component; + } + root = std::move(normalized); + return !root.empty(); +} + +// True when a filesystem grant covers a target: the exact string, or -- for a tree grant -- the +// granted folder itself and every path beneath it, at any depth. Components are compared one by +// one, so "/root/*" covers "/root/a/b" but not "/root-other/file". +// +// A tree grant and its target are both canonicalized before the comparison, so a symlink inside +// the granted folder cannot launder access to a path outside it, and a grant rooted at a symlink +// applies to the symlink's target. weakly_canonical keeps a write target whose tail does not +// exist yet matchable: it canonicalizes the existing prefix and appends the rest lexically. +bool fs_grant_covers(const std::string& grant, const std::string& target) +{ + if (grant == target) + return true; + if (target.empty()) + return false; + + boost::filesystem::path root; + if (!tree_grant_root(grant, root)) + return false; + + return is_inside_allowed_root(boost::filesystem::path(target), root); +} + +// True when `granted` already covers `target`. Only the filesystem buckets accept a tree grant: +// an event grant ("FsRead:open") and the non-filesystem buckets (URLs, socket addresses, +// commands) are matched verbatim, as before. +bool has_permission(AuditEventCategory category, bool by_event, const std::vector& granted, + const std::string& target) +{ + const bool fs_bucket = + !by_event && (category == AuditEventCategory::FsRead || category == AuditEventCategory::FsReadWrite); + for (const auto& grant : granted) { + if (grant == target) + return true; + if (fs_bucket && fs_grant_covers(grant, target)) + return true; + } + return false; } // A sandbox plugin may not have a sidecar yet. Seed the small amount of install metadata the @@ -869,6 +938,8 @@ void seed_install_metadata(const PluginDescriptor& descriptor, PluginInstallStat bool persist_permission(const std::string& plugin_key, PluginInstallState& state, + AuditEventCategory category, + bool by_event, std::vector& permission_list, const std::string& target) { @@ -878,7 +949,7 @@ bool persist_permission(const std::string& plugin_key, seed_install_metadata(descriptor, state); - if (!has_permission(permission_list, target)) + if (!has_permission(category, by_event, permission_list, target)) permission_list.push_back(target); return write_install_state(boost::filesystem::path(descriptor.plugin_root), state); } @@ -982,7 +1053,7 @@ void persist_grant(const std::string& plugin_key, AuditEventCategory category, b return; for (const auto& key : keys) - persist_permission(plugin_key, state, *permission_list, key); + persist_permission(plugin_key, state, category, by_event, *permission_list, key); } static PluginAuditManager::PermissionPrompt s_permission_prompt_for_testing; @@ -1067,7 +1138,7 @@ int decide_audited_event(PluginAuditManager& mgr, if (permission_list) { unresolved.clear(); for (const auto& key : keys) - if (!has_permission(*permission_list, key)) + if (!has_permission(category, by_event, *permission_list, key)) unresolved.push_back(key); if (unresolved.empty()) return 0; @@ -1083,7 +1154,7 @@ int decide_audited_event(PluginAuditManager& mgr, if (permission_list) for (const auto& key : unresolved) - persist_permission(plugin_key, state, *permission_list, key); + persist_permission(plugin_key, state, category, by_event, *permission_list, key); return 0; } @@ -1172,7 +1243,9 @@ bool PluginAuditManager::request_permissions(const std::string& plugin_key, cons for (const std::string& target : requested_targets) { if (target.empty()) continue; - if (std::find(granted_targets.begin(), granted_targets.end(), target) == granted_targets.end() && + // A saved wildcard already covers a more specific request. Deduplicate inside the + // request verbatim only: two requested entries may cover different sets. + if (!PluginAuditDetail::has_permission(category, /*by_event=*/false, granted_targets, target) && std::find(bucket.targets.begin(), bucket.targets.end(), target) == bucket.targets.end()) bucket.targets.push_back(target); } diff --git a/src/slic3r/plugin/PluginAuditManager.hpp b/src/slic3r/plugin/PluginAuditManager.hpp index 9c19d5d1dc..38b21a549b 100644 --- a/src/slic3r/plugin/PluginAuditManager.hpp +++ b/src/slic3r/plugin/PluginAuditManager.hpp @@ -145,6 +145,17 @@ public: // Targets already persisted for the plugin are not shown or asked for again. Returns true // only when every missing target was granted and persisted; denial aborts the plugin load // without adding a permission. + // + // A filesystem target may name a directory tree: a trailing "/*" (e.g. "/path/to/folder/*") + // grants the folder itself and every path beneath it, at any depth. "*" is the only wildcard + // and is only recognized as the final path component; elsewhere it is an ordinary character. + // The wildcard applies to fs_read and fs_readwrite only, never to event grants or the other + // buckets, and a read grant still never authorizes a write (or the reverse). Denied paths + // stay denied regardless of a covering wildcard. + // + // Tree grants are matched on canonical paths: a symlink below the granted folder does not + // extend the grant outside it, and a grant whose root is a symlink applies to its target. + // Exact (non-tree) grants keep their verbatim string comparison. bool request_permissions(const std::string& plugin_key, const PluginPermissions& requested); void report_violation(const AuditViolation& violation); diff --git a/src/slic3r/plugin/PluginFsUtils.hpp b/src/slic3r/plugin/PluginFsUtils.hpp index ee61d8c957..3fa83c8ed7 100644 --- a/src/slic3r/plugin/PluginFsUtils.hpp +++ b/src/slic3r/plugin/PluginFsUtils.hpp @@ -98,13 +98,17 @@ inline nlohmann::json py_to_json(const pybind11::handle& o, int depth = 0) struct PluginPermissions { + // Filesystem targets. A target ending in "/*" (e.g. "/path/to/folder/*") grants the folder + // and its whole subtree, at any depth; "*" is the only wildcard and only as the final path + // component. Reads and writes stay separate buckets: a wildcard in one never grants the other. std::vector fs_read; std::vector fs_readwrite; std::vector network_http; std::vector network_socket; std::vector process; std::vector threading; - // Grants for audit events that expose no target, keyed ":" (e.g. "Socket:socket.__new__"). + // Grants for audit events that expose no target, keyed ":" (e.g. + // "Socket:socket.__new__"). Matched verbatim; the filesystem wildcard does not apply. std::vector events; }; diff --git a/src/slic3r/plugin/PythonPluginBridge.cpp b/src/slic3r/plugin/PythonPluginBridge.cpp index 10739822bf..95cde3aa42 100644 --- a/src/slic3r/plugin/PythonPluginBridge.cpp +++ b/src/slic3r/plugin/PythonPluginBridge.cpp @@ -608,6 +608,15 @@ report: filesystem paths for fs_read and fs_readwrite, URLs for network_http, so for network_socket, and commands for process. threading=True requests permission to start threads. Targets already granted to the plugin are not asked for again. +A filesystem target may end in "/*" to grant a whole directory tree, for example +"/path/to/folder/*". That covers the folder itself and every path beneath it, at any depth. +"*" is the only wildcard and is recognized only as the final path component; a "*" anywhere +else in a target is an ordinary character. Wildcards apply to fs_read and fs_readwrite only, +and a grant in one of those buckets never authorizes the other direction. Tree grants are +matched on canonical paths, so a symlink below the granted folder does not extend the grant +outside it. Paths the host denies by name or keyword stay denied even when a wildcard covers +them. + The host presents one request to the user after register_capabilities() returns and before any capability instance is created. Denying the request aborts the plugin load.)pbdoc"); diff --git a/tests/slic3rutils/test_plugin_audit.cpp b/tests/slic3rutils/test_plugin_audit.cpp index 8b04e8faf5..8eb0fda6ce 100644 --- a/tests/slic3rutils/test_plugin_audit.cpp +++ b/tests/slic3rutils/test_plugin_audit.cpp @@ -1239,3 +1239,180 @@ site_packages_outcome = attempt(lambda: open(SITE_PACKAGE_FILE).close()) const std::string site_packages_prompt = "open: " + python.str("SITE_PACKAGE_FILE") + "\n"; CHECK(describe(harness.prompts) == write_prompt + site_packages_prompt); } + +TEST_CASE("A filesystem wildcard grant covers the folder and its descendants at any depth", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +DEEP_FILE = os.path.join(TREE, "one", "deep", "deeper", "f.txt") +os.makedirs(os.path.dirname(DEEP_FILE)) +with open(DEEP_FILE, "w") as f: + f.write("x") +NESTED_FILE = os.path.join(TREE, "one", "f.txt") +SIBLING = TREE + "-sibling" +SIBLING_FILE = os.path.join(SIBLING, "f.txt") +os.makedirs(SIBLING) +with open(SIBLING_FILE, "w") as f: + f.write("x") +# Lexically under TREE, but ".." resolves outside the granted folder. +ESCAPE_FILE = os.path.join(TREE, "..", "private.txt") +)PY"); + + const std::string tree = python.str("TREE"); + PluginPermissions permissions; + permissions.fs_read = {tree + "/*"}; + harness.save_permissions(PLUGIN, permissions); + + python.run_as(PLUGIN, R"PY( +deep_outcome = attempt(lambda: open(DEEP_FILE).read()) +root_outcome = attempt(lambda: os.listdir(TREE)) +sibling_outcome = attempt(lambda: open(SIBLING_FILE).read()) +escape_outcome = attempt(lambda: open(ESCAPE_FILE).read()) +)PY"); + + // The tree grant covers the folder itself (listing it) and a file two directories below it. + CHECK(python.str("deep_outcome") == "ok"); + CHECK(python.str("root_outcome") == "ok"); + // A path sharing the folder's prefix is not a descendant, and ".." is resolved before the + // comparison, so neither escapes the grant; both are asked about. + CHECK(python.str("sibling_outcome") == "denied"); + CHECK(python.str("escape_outcome") == "denied"); + const std::string sibling_prompt = "open: " + python.str("SIBLING_FILE") + "\n"; + const std::string escape_prompt = "open: " + python.str("ESCAPE_FILE") + "\n"; + CHECK(describe(harness.prompts) == sibling_prompt + escape_prompt); + + // Only the final component may be a wildcard: a "*" inside it is an ordinary character. + permissions.fs_read = {tree + "/*.txt"}; + harness.save_permissions(PLUGIN, permissions); + harness.prompts.clear(); + python.run_as(PLUGIN, "literal_outcome = attempt(lambda: open(NESTED_FILE).read())"); + CHECK(python.str("literal_outcome") == "denied"); + const std::string literal_prompt = "open: " + python.str("NESTED_FILE") + "\n"; + CHECK(describe(harness.prompts) == literal_prompt); +} + +TEST_CASE("A tree grant compares canonical paths on both sides", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + // A folder outside TREE, reached through a symlink planted inside it. + const fs::path tree = python.str("TREE"); + const fs::path outside_dir = harness.outside.path() / "symlink-target"; + const fs::path link = tree / "escape"; + fs::create_directories(outside_dir); + std::ofstream((outside_dir / "outside.txt").string(), std::ios::binary) << "x"; + + boost::system::error_code ec; + fs::create_directory_symlink(outside_dir, link, ec); + if (ec) + SKIP("Cannot create a directory symlink here: " + ec.message()); + + PluginPermissions permissions; + permissions.fs_read = {tree.string() + "/*"}; + harness.save_permissions(PLUGIN, permissions); + + const std::string escaped_file = (link / "outside.txt").string(); + python.globals["ESCAPED_FILE"] = escaped_file; + python.run_as(PLUGIN, "escaped_outcome = attempt(lambda: open(ESCAPED_FILE).read())"); + + // The target canonicalizes outside the canonical grant root, so the link does not inherit + // the tree grant. The read/write wildcard test covers a non-existing write tail. + CHECK(python.str("escaped_outcome") == "denied"); + CHECK(describe(harness.prompts) == "open: " + escaped_file + "\n"); + + // A grant rooted at the link applies to what the link points at, not just to its path. + permissions.fs_read = {link.string() + "/*"}; + harness.save_permissions(PLUGIN, permissions); + harness.prompts.clear(); + python.globals["TARGET_FILE"] = (outside_dir / "outside.txt").string(); + python.run_as(PLUGIN, "via_target_outcome = attempt(lambda: open(TARGET_FILE).read())"); + + CHECK(python.str("via_target_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); +} + +TEST_CASE("A filesystem wildcard keeps read and write grants separate", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +NESTED_FILE = os.path.join(TREE, "one", "f.txt") +NEW_FILE = os.path.join(TREE, "one", "new.txt") +)PY"); + const std::string tree = python.str("TREE"); + PluginPermissions permissions; + permissions.fs_read = {tree + "/*"}; + harness.save_permissions(PLUGIN, permissions); + + python.run_as(PLUGIN, R"PY( +read_outcome = attempt(lambda: open(NESTED_FILE).read()) +write_outcome = attempt(lambda: open(NEW_FILE, "w").close()) +)PY"); + CHECK(python.str("read_outcome") == "ok"); + CHECK(python.str("write_outcome") == "denied"); + // A read grant does not cover the write-shaped open, so that one is asked about. + const std::string write_prompt = "open: " + python.str("NEW_FILE") + "\n"; + CHECK(describe(harness.prompts) == write_prompt); + + // The reverse direction is separate too: a read/write wildcard leaves plain reads in the + // read bucket, which is now empty. + permissions.fs_read.clear(); + permissions.fs_readwrite = {tree + "/*"}; + harness.save_permissions(PLUGIN, permissions); + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +write_outcome = attempt(lambda: open(NEW_FILE, "w").close()) +reread_outcome = attempt(lambda: open(NESTED_FILE).read()) +)PY"); + CHECK(python.str("write_outcome") == "ok"); + CHECK(python.str("reread_outcome") == "denied"); + const std::string reread_prompt = "open: " + python.str("NESTED_FILE") + "\n"; + CHECK(describe(harness.prompts) == reread_prompt); +} + +TEST_CASE("A filesystem wildcard does not override a denied path", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + PluginAuditManager& mgr = PluginAuditManager::instance(); + + python.exec(R"PY( +DENIED_DIR = os.path.join(OUTSIDE, "secrets") +os.makedirs(DENIED_DIR) +with open(os.path.join(DENIED_DIR, "token.txt"), "w") as f: + f.write("x") +)PY"); + + // A grant wide enough to cover the deny registry's target still loses to the deny. + PluginPermissions permissions; + permissions.fs_read = {python.str("OUTSIDE") + "/*"}; + harness.save_permissions(PLUGIN, permissions); + + python.run_as(PLUGIN, "denied_outcome = attempt(lambda: open(os.path.join(DENIED_DIR, 'token.txt')).read())"); + + CHECK(python.str("denied_outcome") == "denied"); + CHECK(describe(harness.prompts).empty()); + AuditViolation violation; + REQUIRE(mgr.last_violation(violation)); + CHECK(violation.reason == "denied path"); +}