diff --git a/docs/HLSD/plugin-permissions.md b/docs/HLSD/plugin-permissions.md index 8c14679fbf..89fff7e7bf 100644 --- a/docs/HLSD/plugin-permissions.md +++ b/docs/HLSD/plugin-permissions.md @@ -29,7 +29,7 @@ Permissions are stored per plugin key. A plugin can hold: | `fs_delete` | folder list | Filesystem delete events such as `os.remove` and `shutil.rmtree`. | | `network_http` | target list | Network targets, consulted together with `network_socket` for both HTTP and socket events. A canonical `scheme://host` entry is host-wide and covers both layers; a URL with a path, port, query or trailing slash is exact; a bare host or legacy address tuple covers raw sockets. | | `network_socket` | target list | The same network matching, kept as a separate list so a plugin can declare socket access without an HTTP URL. | -| `process` | target list | Process creation and process replacement: `os.system`, `subprocess.Popen`, `os.spawn*`, `os.exec*`, `pty.spawn`, `_winapi.CreateProcess`, and similar. Targets match the audited value verbatim. | +| `process` | target list | Process creation and process replacement: `subprocess.Popen`, `os.spawn*`, `os.exec*`, `pty.spawn`, `_winapi.CreateProcess`, and similar. Targets name the tool, not its arguments. The exception is a Windows command line with an unquoted executable followed by arguments: it is stored as an exact full command line, because `CreateProcess` may resolve a longer executable prefix than the first token shows. `os.system` names the shell it runs (see "Target matching"). | | `threading` | boolean | Permission to start a Python thread with `_thread.start_new_thread`. | | `events` | target list | Audited events that expose no target, keyed as `:`, for example `Socket:socket.__new__`. Matched verbatim. | | `full_access` | boolean | Turns off the permission decision for the plugin. See "Full access". | @@ -89,8 +89,36 @@ that requested it and the nested deletes it performs inside that subtree. A canonical entry is host-wide and applies to HTTP and raw socket events for that host. A URL with a path, port, query, fragment or trailing slash that was stored without normalization remains an exact match. -- Process entries are compared verbatim with the string the audit event reports, - including Python representations of a command. +- Process entries name the tool an event runs, compared verbatim. When the event exposes + the executable or path, that argument is the target. For a command string or argv, the + first token or element is the target. Arguments after the tool are ignored, so one grant + covers repeated runs of the tool with different arguments. The exception is a Windows + command line whose executable is unquoted and followed by non-whitespace text. + `CreateProcess` resolves such a name by trying successively longer prefixes, so the first + whitespace-delimited token need not be the executable it starts: a command line + `C:\Program Files\app.exe --x` can start `C:\Program Files\app.exe`, not `C:\Program`. + The audit therefore stores the exact full command line instead of the first token, in a + reserved `CommandLine:` namespace in the `process` list. An exact entry matches only the + same full command line, compared verbatim, and a later run with different arguments asks + again. A quoted first argument, an explicit executable or application name, and a command + line that has no arguments keep the executable-only, argument-insensitive grant. The + command line is not parsed further, and the resolved executable is not checked: the same + approved command line can start a different binary if the working directory, `PATH`, or + the files it resolves through change. `os.system` works differently: + Python hands its whole string to the platform shell, so the target is every shell that may + run it. On POSIX that is `/bin/sh`. On Windows the C runtime runs the interpreter named by + `COMSPEC`, or `cmd.exe` when `COMSPEC` is unset or empty, and also falls back to `cmd.exe` + when it cannot open the configured file (ENOENT or EACCES). The configured interpreter and + the fallback are both required targets: a grant for a narrow `COMSPEC` does not authorize + the fallback shell. A `COMSPEC` that is already the bare name `cmd.exe`, in any casing, + names the fallback itself and is listed once. The value is read from the CRT environment + that `_wsystem` consults, not the process environment block, which can differ. The audit + does not test whether the `COMSPEC` file exists; the runtime decides that when it runs the + command, so a file present at prompt time can be gone by the call. The command string is + not parsed, and approving the shells covers every command and argument the plugin passes + to `os.system`. The targets are read when the event is raised, so a grant saved under one + `COMSPEC` value does not cover a run under another. Direct process creation, such as + `subprocess.Popen`, still names its executable. - An event with no target is granted by the `events` entry for its category and name. A targetless network event, such as `http.client.send`, is covered by any recorded network grant instead. @@ -191,8 +219,12 @@ whose denial aborted the load and then retry with the saved grant. Runtime approvals store the target observed by the audit hook, except that create and delete approvals store its parent folder. A URL with a path, port or -query is therefore an exact grant; a bare host remains usable for raw sockets. The -declared form and the runtime form are not normalized by the same code path. +query is therefore an exact grant; a bare host remains usable for raw sockets. A Windows +command line that needs the exact fallback is saved in the reserved `CommandLine:` namespace +as its full text, so the approval is argument-sensitive; the prompt shows the command line +without the storage marker and states that the full line, including any sensitive values in +its arguments, is shown and saved. The declared form and the runtime form are not normalized +by the same code path. A recursive delete is different: a Yes grants consent for the canonical target subtree for that operation only. The prompt shows the subtree root and states that the consent is not @@ -361,6 +393,15 @@ never treated as an opt-out. context, so its events are not attributed or restricted. - **Subprocesses leave the policy.** A process created by a granted or full-access plugin runs with the user's rights and is not covered by the parent's audit scope. +- **An `os.system` grant is a shell grant.** It authorizes every command string the plugin + passes to `os.system`, not only the one that triggered the prompt, because the shell + parses and runs the whole string. Arguments are not inspected or restricted. +- **An exact command line grant is command-sensitive, not binary-sensitive.** It is stored + and shown in full, so it can expose credentials or tokens passed as arguments to anyone + who sees the prompt or the sidecar. Approval covers only the same full command line. + `CreateProcess` still resolves the executable from the working directory, `PATH`, and the + filesystem, so the same approved command line can start a different binary later; the + grant does not pin the resolved image or verify it. - **Host APIs are not audit events.** Calls into OrcaSlicer's Python host APIs, such as preset updates or UI actions, execute C++ host code and follow that API's contract. The audit hook judges the Python-level filesystem, network, process and thread events it is diff --git a/resources/web/dialog/PluginsDialog/index.js b/resources/web/dialog/PluginsDialog/index.js index 27adc0c8eb..2c3efdc0d1 100644 --- a/resources/web/dialog/PluginsDialog/index.js +++ b/resources/web/dialog/PluginsDialog/index.js @@ -1115,7 +1115,7 @@ function RenderPermissions(plugin) { fs_readwrite: [null, ""], network_http: [null, "https://example.com"], network_socket: [null, "https://example.com"], - process: [T("permissions_process_help", "Enter the exact value recorded by the audit. It may be a Python representation of the command."), T("permissions_process_placeholder", "Exact audited value")], + process: [T("permissions_process_help", "Executable grants cover all arguments. CommandLine: entries cover only the exact command line."), T("permissions_process_placeholder", "Executable or command name")], threading: [T("permissions_threading_help_short", "Allow this plugin to create threads."), ""], events: [T("permissions_events_help", "Enter a category and event separated by a colon, such as Socket:socket.__new__."), T("permissions_events_placeholder", "Socket:socket.__new__")] }; diff --git a/src/slic3r/GUI/PluginsDialog.cpp b/src/slic3r/GUI/PluginsDialog.cpp index 9f023df0b4..5c4d1e951b 100644 --- a/src/slic3r/GUI/PluginsDialog.cpp +++ b/src/slic3r/GUI/PluginsDialog.cpp @@ -762,8 +762,8 @@ nlohmann::json PluginsDialog::localized_strings() const {"permissions_filesystem_placeholder", _u8L("/path/to/directory/*")}, #endif {"permissions_network_access_guidance", _u8L("Enter a full http:// or https:// URL; only its scheme and host are saved, so the grant covers every port, path, and query on that host. A network socket grant also accepts a bare host name or IP address, with or without a port, and covers every port on that host. Other schemes are not accepted. Grants in either list are checked for HTTP and socket access.")}, - {"permissions_process_help", _u8L("Enter the exact value recorded by the audit. It may be a Python representation of the command.")}, - {"permissions_process_placeholder", _u8L("Exact audited value")}, + {"permissions_process_help", _u8L("Executable grants cover all arguments. CommandLine: entries cover only the exact command line.")}, + {"permissions_process_placeholder", _u8L("Executable or command name")}, {"permissions_threading_help_short", _u8L("Allow this plugin to create threads.")}, {"permissions_events_help", _u8L("Enter a category and event separated by a colon, such as Socket:socket.__new__.")}, {"permissions_events_placeholder", _u8L("Socket:socket.__new__")}, diff --git a/src/slic3r/plugin/PluginAuditManager.cpp b/src/slic3r/plugin/PluginAuditManager.cpp index d04c0f2aaa..cf247043cc 100644 --- a/src/slic3r/plugin/PluginAuditManager.cpp +++ b/src/slic3r/plugin/PluginAuditManager.cpp @@ -177,7 +177,7 @@ static const std::unordered_set operation_root_events{ }; // True for the categories whose targets are filesystem paths, as opposed to a network -// address or a process command line -- the deny-path and allowed-root checks only make sense +// address or a process executable -- the deny-path and allowed-root checks only make sense // against a path. static bool is_fs_category(AuditEventCategory category) { @@ -1635,31 +1635,137 @@ static std::vector create_permission_targets(const std::string& eve return targets; } -static const std::unordered_map> audit_target_arg_indices{ - {"http.client.connect", {1}}, - {"urllib.Request", {0}}, +// Network events name their target directly: a host, an address tuple or a URL. +static const std::unordered_map network_target_arg_indices{ + {"http.client.connect", 1}, + {"urllib.Request", 0}, - {"socket.connect", {1}}, - {"socket.bind", {1}}, - {"socket.getaddrinfo", {0}}, - {"socket.gethostbyname", {0}}, - {"socket.gethostbyaddr", {0}}, - {"socket.getnameinfo", {0}}, - {"socket.getservbyname", {0}}, - {"socket.getservbyport", {0}}, - {"socket.sendto", {1}}, - {"socket.sendmsg", {1}}, + {"socket.connect", 1}, + {"socket.bind", 1}, + {"socket.getaddrinfo", 0}, + {"socket.gethostbyname", 0}, + {"socket.gethostbyaddr", 0}, + {"socket.getnameinfo", 0}, + {"socket.getservbyname", 0}, + {"socket.getservbyport", 0}, + {"socket.sendto", 1}, + {"socket.sendmsg", 1}, +}; - {"os.system", {0}}, - {"subprocess.Popen", {1, 0}}, - {"os.posix_spawn", {1, 0}}, - {"os.spawn", {2, 1}}, - {"os.startfile", {0}}, - {"os.startfile/2", {0}}, - {"pty.spawn", {0}}, - {"_winapi.CreateProcess", {1, 0}}, - {"_posixsubprocess.fork_exec", {0}}, - {"os.exec", {0}}, +// Process events each expose the executable in a different argument, and some pass the whole +// command line or argv. A grant normally names the tool only, so the arguments are dropped; the +// exception is a Windows command line whose executable is unquoted and followed by arguments +// (see windows_command_line_target). +enum class ProcessTargetFormat { + Path, // the argument is the executable path or name + FirstToken, // a command string or argv sequence: its first token or element + WindowsCommandLine, // a Windows command line: its first argument, possibly a quoted path +}; + +struct ProcessTargetSource { + Py_ssize_t index; + ProcessTargetFormat format; +}; + +// An exact-command entry shares the process list with executable entries. This reserved prefix +// keeps the two namespaces apart: an exact command line can never be mistaken for an executable +// name, and an existing executable grant (which does not carry the prefix) keeps its +// argument-insensitive meaning. It is stored in the sidecar and listed by the Plugins dialog; the +// permission prompt shows the command line without it. +static const std::string kWindowsCommandLineGrantPrefix = "CommandLine:"; + +static bool is_exact_command_grant(const std::string& target) +{ + return boost::algorithm::starts_with(target, kWindowsCommandLineGrantPrefix); +} + +static std::string exact_command_grant(const std::string& command_line) +{ + return kWindowsCommandLineGrantPrefix + command_line; +} + +// The prompt shows the command line the user is asked about, not the storage marker. +static std::string process_target_for_display(const std::string& target) +{ + return is_exact_command_grant(target) ? target.substr(kWindowsCommandLineGrantPrefix.size()) : target; +} + +// A process prompt can list executable grants and exact command lines together (a declaration may +// do so; a runtime event has one target). The wording must not claim argument-insensitive scope +// for an exact command line. +struct ProcessPromptScope { + bool exact_command = false; + bool executable = false; +}; + +static ProcessPromptScope process_prompt_scope(const std::vector& targets) +{ + ProcessPromptScope scope; + for (const std::string& target : targets) { + if (is_exact_command_grant(target)) + scope.exact_command = true; + else + scope.executable = true; + } + return scope; +} + +// os.system does not run a program named by its first token: it hands the whole string to the +// platform shell. POSIX passes it to /bin/sh. The Windows C runtime runs the command interpreter +// named by COMSPEC, or cmd.exe when COMSPEC is unset or empty, and also falls back to cmd.exe +// when it cannot open the configured file (ENOENT or EACCES). Either interpreter may therefore +// run the command, so every one of them is a required target: a narrow grant for a harmless +// COMSPEC target must not admit the fallback shell. Approving the shells covers every command +// string the plugin passes to os.system, because a shell parses and executes all of the string, +// arguments included. +// +// The runtime chooses the interpreter when it runs the command, so the audit names the possible +// interpreters instead of checking whether the COMSPEC file exists: a file that is present while +// the prompt is answered can be removed before the call. A COMSPEC that already is the bare name +// cmd.exe, in any casing, names the fallback itself and is listed once. +#ifdef _WIN32 +static std::vector system_shell_targets() +{ + constexpr const char* kFallbackShell = "cmd.exe"; + + // _wsystem reads COMSPEC through the CRT environment, which is the copy it consults; the + // process environment block can differ. Read the same value and copy it at once, because a + // concurrent _wputenv may replace the buffer the pointer names. + const wchar_t* const comspec_value = ::_wgetenv(L"COMSPEC"); + // An unset or empty COMSPEC leaves only the runtime's default interpreter. + if (comspec_value == nullptr || *comspec_value == L'\0') + return {kFallbackShell}; + + std::string comspec = wxString(comspec_value).utf8_string(); + // A bare cmd.exe is the fallback interpreter itself, whatever the casing, so one target stays. + if (comspec.find_first_of("/\\") == std::string::npos && + wxString::FromUTF8(comspec).CmpNoCase(wxString::FromUTF8(kFallbackShell)) == 0) + return {kFallbackShell}; + + return {std::move(comspec), kFallbackShell}; +} +#else +static std::vector system_shell_targets() +{ + return {"/bin/sh"}; +} +#endif + +static const std::unordered_map> process_target_sources{ + {"os.exec", {{0, ProcessTargetFormat::Path}}}, + {"os.posix_spawn", {{0, ProcessTargetFormat::Path}}}, + {"os.spawn", {{1, ProcessTargetFormat::Path}}}, + {"os.startfile", {{0, ProcessTargetFormat::Path}}}, + {"os.startfile/2", {{0, ProcessTargetFormat::Path}}}, + // executable is unresolved when the caller did not pass one, as on Windows, where args is + // then a single command line; on POSIX args is an argv sequence and executable is always set. + {"subprocess.Popen", {{0, ProcessTargetFormat::Path}, {1, ProcessTargetFormat::WindowsCommandLine}}}, + // application_name wins when it is given, so its source comes first; when it is omitted + // command_line is a Windows command line whose first argument names the executable. + {"_winapi.CreateProcess", {{0, ProcessTargetFormat::Path}, {1, ProcessTargetFormat::WindowsCommandLine}}}, + {"pty.spawn", {{0, ProcessTargetFormat::FirstToken}}}, + // The first argument is argv; its first element names the program. + {"_posixsubprocess.fork_exec", {{0, ProcessTargetFormat::FirstToken}}}, }; AuditEventCategory open_category(PyObject* args) @@ -1670,6 +1776,115 @@ AuditEventCategory open_category(PyObject* args) return AuditEventCategory::FsReadWrite; } +// The first token of a command string, or the first element of an argv sequence. A sequence +// element is kept whole, so an executable path may contain spaces. +std::string first_process_token(PyObject* object) +{ + if (!object) + return {}; + + std::string text; + if (python_text(object, text)) { + const size_t start = text.find_first_not_of(" \t\r\n"); + if (start == std::string::npos) + return {}; + const size_t end = text.find_first_of(" \t\r\n", start); + return text.substr(start, end == std::string::npos ? std::string::npos : end - start); + } + + if (!PySequence_Check(object)) + return python_path(object); + + PyObject* first = PySequence_GetItem(object, 0); // new reference + if (!first) { + PyErr_Clear(); + return {}; + } + std::string value = python_path(first); + Py_DECREF(first); + return value; +} + +// The grant target for a Windows command line. Windows does not split it like a POSIX shell: a +// path that contains spaces is enclosed in double quotes, and backslashes before a quote follow +// the CommandLineToArgvW rules (2n backslashes and a quote give n backslashes and end the +// argument, 2n+1 give n backslashes and a literal quote). +// +// A quoted first argument names the executable unambiguously and is returned alone, as is a +// command line that is only the executable: both keep the argument-insensitive executable grant. +// An unquoted first argument followed by more text is different. CreateProcess resolves it by +// trying successively longer prefixes of the name, so the first whitespace-delimited token need +// not be the executable it starts (the command line "C:\Program Files\app.exe --x" can start +// "C:\Program Files\app.exe", not "C:\Program"). Such a command line is returned as one exact +// grant instead, because granting the first token would describe a different program and would +// cover every later command line with that token. +std::string windows_command_line_target(const std::string& command_line) +{ + size_t index = command_line.find_first_not_of(" \t"); + if (index == std::string::npos) + return {}; + + if (command_line[index] != '"') { + const size_t end = command_line.find_first_of(" \t", index); + const size_t token_end = end == std::string::npos ? command_line.size() : end; + if (command_line.find_first_not_of(" \t", token_end) != std::string::npos) + return exact_command_grant(command_line.substr(index)); + return command_line.substr(index, token_end - index); + } + + std::string token; + ++index; // the opening quote is not part of the argument + while (index < command_line.size()) { + if (command_line[index] == '\\') { + size_t backslashes = 0; + while (index < command_line.size() && command_line[index] == '\\') { + ++backslashes; + ++index; + } + if (index < command_line.size() && command_line[index] == '"') { + token.append(backslashes / 2, '\\'); + if (backslashes % 2) { + token.push_back('"'); + ++index; + } else { + ++index; // the closing quote + break; + } + } else { + token.append(backslashes, '\\'); + } + continue; + } + if (command_line[index] == '"') { + ++index; // the closing quote + break; + } + token.push_back(command_line[index]); + ++index; + } + return token; +} + +std::string process_target(const ProcessTargetSource& source, PyObject* args) +{ + PyObject* const item = tuple_item(args, source.index); + if (!item || item == Py_None) + return {}; + switch (source.format) { + case ProcessTargetFormat::Path: + return python_path(item); + case ProcessTargetFormat::FirstToken: + return first_process_token(item); + case ProcessTargetFormat::WindowsCommandLine: { + std::string command_line; + if (python_text(item, command_line)) + return windows_command_line_target(command_line); + return first_process_token(item); + } + } + return {}; +} + std::vector audit_targets(const std::string& event_name, AuditEventCategory category, PyObject* args) { std::vector targets; @@ -1687,6 +1902,24 @@ std::vector audit_targets(const std::string& event_name, AuditEvent } return targets; } + case AuditEventCategory::ProcessCreate: + case AuditEventCategory::ProcessReplace: { + // The shells a command string may run in, not the command itself. Every possible + // interpreter has to be granted before the event is allowed. + if (event_name == "os.system") + return system_shell_targets(); + const auto it = process_target_sources.find(event_name); + if (it == process_target_sources.end()) + return targets; + for (const ProcessTargetSource& source : it->second) { + std::string value = process_target(source, args); + if (!value.empty()) { + targets.push_back(std::move(value)); + break; + } + } + return targets; + } case AuditEventCategory::Threading: // Thread creation exposes no user-supplied target. Use a fixed sentinel so the grant // persists per plugin: the permission list matches targets by exact string, and the @@ -1697,18 +1930,14 @@ std::vector audit_targets(const std::string& event_name, AuditEvent break; } - const auto it = audit_target_arg_indices.find(event_name); - if (it != audit_target_arg_indices.end()) { - for (const Py_ssize_t index : it->second) { - // None is an argument left out (sendmsg without an address), not a target named "None". - PyObject* const item = tuple_item(args, index); - if (item == Py_None) - continue; + const auto it = network_target_arg_indices.find(event_name); + if (it != network_target_arg_indices.end()) { + // None is an argument left out (sendmsg without an address), not a target named "None". + PyObject* const item = tuple_item(args, it->second); + if (item != Py_None) { std::string value = python_str(item); - if (!value.empty()) { + if (!value.empty()) targets.push_back(std::move(value)); - break; - } } } @@ -2369,7 +2598,8 @@ int report_denied(PluginAuditManager& mgr, wxString audit_message(AuditEventCategory category, const wxString& plugin_name, const wxString& event_name, const wxString& target_list, size_t target_count, bool full_fs_scope = false, - bool tree_scope = false, bool root_tree_scope = false) + bool tree_scope = false, bool root_tree_scope = false, bool exact_process_command = false, + bool executable_process_target = false) { // Create and delete grants name folders, and a declaration may ask for the whole filesystem // with a sole "*". Describe that scope instead of printing the marker as a folder. @@ -2509,13 +2739,43 @@ wxString audit_message(AuditEventCategory category, const wxString& plugin_name, "Approval covers raw network connections to the listed hosts. It does not restrict ports."), plugin_name, target_list); case AuditEventCategory::ProcessCreate: - return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to run the following command:\n%s", - "Plugin \"%s\" is requesting to run the following commands:\n%s", target_count), + // An exact command line is saved with its arguments rather than as a tool name, so the + // prompt must not promise that approval covers any arguments. The full line is stored, + // which can include credentials or tokens in its arguments. + if (exact_process_command && !executable_process_target) + return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to run the following exact command line:\n%s\n\n" + "Approval is saved for this exact command line, including its arguments, and covers " + "only it. A different command line, including different arguments, asks again. The " + "full command line is shown and saved, so it may contain sensitive values.", + "Plugin \"%s\" is requesting to run the following exact command lines:\n%s\n\n" + "Approval is saved for each exact command line, including its arguments, and covers " + "only that line. A different command line, including different arguments, asks again. " + "The full command lines are shown and saved, so they may contain sensitive values.", + target_count), + plugin_name, target_list); + if (exact_process_command) + return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to run the following commands:\n%s\n\n" + "Approval covers the listed executables with any arguments. A listed exact command " + "line is saved with its arguments and covers only that command line. Exact command " + "lines are shown and saved in full, so they may contain sensitive values. Approving a " + "shell allows it to run any command.", + "Plugin \"%s\" is requesting to run the following commands:\n%s\n\n" + "Approval covers the listed executables with any arguments. Each listed exact command " + "line is saved with its arguments and covers only that command line. Exact command " + "lines are shown and saved in full, so they may contain sensitive values. Approving a " + "shell allows it to run any command.", + target_count), + plugin_name, target_list); + return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to run the following command:\n%s\n\n" + "Approval covers any arguments. Approving a shell allows it to run any command.", + "Plugin \"%s\" is requesting to run the following commands:\n%s\n\n" + "Approval covers any arguments. Approving a shell allows it to run any command.", target_count), plugin_name, target_list); case AuditEventCategory::Threading: return wxString::Format(_L("Plugin \"%s\" is requesting permission to create a thread."), plugin_name); case AuditEventCategory::ProcessReplace: - return wxString::Format(_L("Plugin \"%s\" is requesting to replace the running application with:\n%s"), plugin_name, target_list); + return wxString::Format(_L("Plugin \"%s\" is requesting to replace the running application with:\n%s\n\n" + "Approval covers any arguments. Approving a shell allows it to run any command."), plugin_name, target_list); default: return wxString::Format(_L("Plugin \"%s\" is requesting permission for the Python audit event \"%s\"."), plugin_name, event_name); } @@ -2525,17 +2785,19 @@ wxString audit_message(AuditEventCategory category, const wxString& plugin_name, PermissionMessage formatted_audit_message(AuditEventCategory category, const wxString& plugin_name, const wxString& event_name, const wxString& targets, size_t count, bool full_fs_scope = false, bool tree_scope = false, - bool root_tree_scope = false) + bool root_tree_scope = false, bool exact_process_command = false, + bool executable_process_target = false) { if (targets.empty()) return {audit_message(category, plugin_name, event_name, targets, count, full_fs_scope, tree_scope, - root_tree_scope), {}}; + root_tree_scope, exact_process_command, executable_process_target), {}}; wxString marker = "__ORCA_PERMISSION_TARGETS__"; while (plugin_name.Contains(marker) || event_name.Contains(marker) || targets.Contains(marker)) marker += "_"; PermissionMessage message{ - audit_message(category, plugin_name, event_name, marker, count, full_fs_scope, tree_scope, root_tree_scope), {}}; + audit_message(category, plugin_name, event_name, marker, count, full_fs_scope, tree_scope, root_tree_scope, + exact_process_command, executable_process_target), {}}; const size_t pos = message.text.find(marker); if (pos != wxString::npos) { message.text.replace(pos, marker.length(), targets); @@ -2620,9 +2882,16 @@ bool prompt_for_targets(AuditEventCategory category, const std::string& plugin_n return show_permission_dialog(message, _L("Plugin permission request")); } + const bool process_category = + category == AuditEventCategory::ProcessCreate || category == AuditEventCategory::ProcessReplace; + const ProcessPromptScope process_scope = + process_category ? process_prompt_scope(unresolved) : ProcessPromptScope{}; + wxString target_list; - for (const auto& target : unresolved) - target_list += wxString::FromUTF8(target.c_str()) + "\n"; + for (const auto& target : unresolved) { + const std::string shown = process_category ? process_target_for_display(target) : target; + target_list += wxString::FromUTF8(shown.c_str()) + "\n"; + } const bool tree_scope = std::any_of(unresolved.begin(), unresolved.end(), [](const std::string& target) { boost::filesystem::path root; @@ -2632,7 +2901,8 @@ bool prompt_for_targets(AuditEventCategory category, const std::string& plugin_n PermissionMessage message = formatted_audit_message(category, wxString::FromUTF8(plugin_name.c_str()), wxString::FromUTF8(event_name.c_str()), target_list, unresolved.size(), /*full_fs_scope=*/false, tree_scope, - /*root_tree_scope=*/false); + /*root_tree_scope=*/false, process_scope.exact_command, + process_scope.executable); return show_permission_dialog(message, _L("Plugin permission request")); } @@ -2664,16 +2934,24 @@ PermissionMessage build_permission_message(const std::string& plugin_name, const return tree_grant_root(target, root) && is_filesystem_root(root); }); + const bool process_category = + bucket.category == AuditEventCategory::ProcessCreate || bucket.category == AuditEventCategory::ProcessReplace; + const ProcessPromptScope process_scope = + process_category ? process_prompt_scope(bucket.targets) : ProcessPromptScope{}; + wxString targets; if (!full_fs_scope) - for (const std::string& target : bucket.targets) - targets += wxString::FromUTF8(target.c_str()) + "\n"; + for (const std::string& target : bucket.targets) { + const std::string shown = process_category ? process_target_for_display(target) : target; + targets += wxString::FromUTF8(shown.c_str()) + "\n"; + } if (!message.text.IsEmpty()) message.text += "\n\n"; PermissionMessage part = formatted_audit_message(bucket.category, wxString::FromUTF8(plugin_name.c_str()), wxEmptyString, targets, bucket.targets.size(), - full_fs_scope, tree_scope, root_tree_scope); + full_fs_scope, tree_scope, root_tree_scope, + process_scope.exact_command, process_scope.executable); for (const auto& range : part.targets) message.targets.emplace_back(message.text.length() + range.first, range.second); message.text += part.text; diff --git a/src/slic3r/plugin/PluginFsUtils.hpp b/src/slic3r/plugin/PluginFsUtils.hpp index 5845aa3acf..add3887a2a 100644 --- a/src/slic3r/plugin/PluginFsUtils.hpp +++ b/src/slic3r/plugin/PluginFsUtils.hpp @@ -39,6 +39,8 @@ struct PluginPermissions std::vector fs_delete; std::vector network_http; std::vector network_socket; + // Executables or command names. Arguments are ignored, so one entry covers every call of + // the tool. std::vector process; // Thread creation is a yes/no grant. Newer sidecars store a boolean; older ones stored an // array (empty when denied, nonempty when granted), and nonempty strings are accepted by the diff --git a/src/slic3r/plugin/PythonPluginBridge.cpp b/src/slic3r/plugin/PythonPluginBridge.cpp index 050a60a285..86ab02b0d6 100644 --- a/src/slic3r/plugin/PythonPluginBridge.cpp +++ b/src/slic3r/plugin/PythonPluginBridge.cpp @@ -663,8 +663,8 @@ void bind_python_api(pybind11::module_& m) Each bucket takes the target strings the plugin expects the corresponding audit event to report: filesystem paths for fs_read and fs_readwrite, URLs for network_http, socket addresses -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. +for network_socket, and executables or command names for process. threading=True requests +permission to start threads. Targets already granted to the plugin are not asked for again. fs_create and fs_delete take folders rather than files. A literal folder entry grants creating or deleting entries directly inside that folder, not inside its subfolders. An entry ending in diff --git a/tests/slic3rutils/test_plugin_audit.cpp b/tests/slic3rutils/test_plugin_audit.cpp index 98b3c2e05a..a295230db3 100644 --- a/tests/slic3rutils/test_plugin_audit.cpp +++ b/tests/slic3rutils/test_plugin_audit.cpp @@ -1432,6 +1432,17 @@ PRIVATE = os.path.join(OUTSIDE, "private.txt") MISSING = os.path.join(OUTSIDE, "missing") TREE = os.path.join(OUTSIDE, "tree") TRUE_COMMAND = ["cmd", "/c", "exit 0"] if os.name == "nt" else ["true"] + +# The shells os.system may run a command in. On Windows the runtime uses COMSPEC or cmd.exe, +# and falls back to cmd.exe when COMSPEC names a file it cannot open, so both are targets. A +# bare cmd.exe COMSPEC is the fallback itself. +if os.name != "nt": + SYSTEM_SHELLS = ["/bin/sh"] +else: + COMSPEC = os.environ.get("COMSPEC") or "" + SYSTEM_SHELLS = (["cmd.exe"] if not COMSPEC or + ("/" not in COMSPEC and "\\" not in COMSPEC and COMSPEC.lower() == "cmd.exe") + else [COMSPEC, "cmd.exe"]) for path in (APPROVED, PRIVATE): with open(path, "w") as f: f.write("x") @@ -1525,6 +1536,23 @@ std::string describe(const std::vector& prompts) return text; } +// The line describe() prints for an os.system prompt, whose target is every possible shell. +std::string describe_system_prompt(const std::vector& shells) +{ + std::string text = "os.system:"; + for (const std::string& shell : shells) + text += " " + shell; + return text + "\n"; +} + +// The process grants a successful os.system approval adds to the ones already saved. +std::vector with_shell_grants(std::vector grants, + const std::vector& shells) +{ + grants.insert(grants.end(), shells.begin(), shells.end()); + return grants; +} + // The plugin system with the audit hook installed, and the permission dialog replaced by a // recorder that answers with `approve`. Declare it first in a test, so it is destroyed last. // @@ -1863,10 +1891,11 @@ TEST_CASE("A freshly approved operation covers its nested events", "[audit][Pyth const char* prompts; const char* code; }; - // Each case starts with no saved grants, so its root event is asked once. A freshly approved - // create or delete saves the parent folder, so the stored grants are reset between cases. - // Only the expected prompts are approved, so a nested event left uncovered fails the - // operation. + // Each case starts with no saved grants, so its root event is asked once; a freshly approved + // create or delete saves the parent folder, so the stored grants are reset between cases. A + // process grant names the executable, so pty.spawn's own approval covers the exec in the + // forked child. Only the expected prompts are approved, so a nested event left uncovered + // fails the operation. std::vector cases = { {"shutil.copytree", "shutil.copytree(TREE, os.path.join(OUTSIDE, 'copy'))"}, {"shutil.copyfile", "shutil.copyfile(APPROVED, os.path.join(OUTSIDE, 'copied.txt'))"}, @@ -2027,7 +2056,7 @@ fd_outcomes = [attempt(lambda: open(READ_FD, "r", closefd=False).close()), CHECK(describe(harness.prompts) == "open:\nopen:\n"); CHECK(harness.saved_permissions(PLUGIN).events == std::vector{"FsRead:open"}); - // A saved os.fork event grant is not an os.system command named "os.fork". + // A saved os.fork event grant is not the shell os.system runs. PluginPermissions permissions; permissions.events = {"FsRead:open", "ProcessCreate:os.fork"}; harness.save_permissions(PLUGIN, permissions); @@ -2045,6 +2074,377 @@ os.close(WRITE_FD) CHECK(harness.saved_permissions(PLUGIN).process.empty()); } +TEST_CASE("A process grant names the executable, or the exact Windows command line", "[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); + const std::vector shells = python.strings("SYSTEM_SHELLS"); +#ifdef _WIN32 + // subprocess.run() joins argv into one command line before the audit event. Its executable + // "cmd" is unquoted and followed by arguments, so the documented grant keeps the whole exact + // line instead of the first token. + const std::string popen_target = R"(CommandLine:cmd /c "exit 0")"; +#else + // POSIX keeps the executable in its own argv element, so only the executable is granted. + const std::string popen_target = python.eval("TRUE_COMMAND[0]"); +#endif + + // Refused, so nothing runs: the prompts show the target each event reports. A direct process + // event names the executable, except a Windows command line whose unquoted executable is + // followed by arguments, which is the exact command line. os.system names every shell that may + // parse its command string. + python.run_as(PLUGIN, R"PY( +popen_outcome = attempt(lambda: subprocess.run(TRUE_COMMAND, check=True)) +system_outcome = attempt(lambda: os.system(" ".join(TRUE_COMMAND) + " ignored")) +)PY"); + CHECK(python.str("popen_outcome") == "denied"); + CHECK(python.str("system_outcome") == "denied"); + CHECK(describe(harness.prompts) == + "subprocess.Popen: " + popen_target + "\n" + describe_system_prompt(shells)); + +#ifndef _WIN32 + harness.prompts.clear(); + python.run_as(PLUGIN, "spawn_outcome = attempt(lambda: spawn_checked(TRUE_COMMAND + ['spawned']))"); + CHECK(python.str("spawn_outcome") == "denied"); + CHECK(describe(harness.prompts) == "pty.spawn: " + popen_target + "\n"); +#endif + + // Approving the direct process event grants its target alone: on Windows the exact command + // line, elsewhere the executable. The approval also opens an operation frame that covers the + // runtime's nested CreateProcess event, so the run asks once. Neither target is a shell grant, + // so a later os.system is asked for on its own. + harness.approve = [](const Prompt&) { return true; }; + harness.prompts.clear(); + python.run_as(PLUGIN, "popen_outcome = attempt(lambda: subprocess.run(TRUE_COMMAND, check=True))"); + CHECK(python.str("popen_outcome") == "ok"); + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().targets == std::vector{popen_target}); + CHECK(harness.saved_permissions(PLUGIN).process == std::vector{popen_target}); + + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +system_outcome = attempt(lambda: os.system(" ".join(TRUE_COMMAND) + " ignored")) +)PY"); + CHECK(python.str("system_outcome") == "ok"); + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().targets == shells); + CHECK(harness.saved_permissions(PLUGIN).process == + with_shell_grants({popen_target}, shells)); + + // The shell grant covers a different command string, arguments included. + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +repeat_outcome = attempt(lambda: os.system(" ".join(TRUE_COMMAND) + " another argument")) +)PY"); + CHECK(python.str("repeat_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); +} + +TEST_CASE("A subprocess grant names the executable from a Windows command line", "[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); + + // The event Windows subprocess.Popen raises: the executable is unresolved unless the caller + // passed one, and the arguments are a single command line. Raising it directly checks the + // target the hook reads without creating a process. + python.run_as(PLUGIN, R"PY( +def raise_popen(executable, command_line): + try: + sys.audit("subprocess.Popen", executable, command_line, None, None) + return "ok" + except PermissionError: + return "denied" + +quoted_outcome = raise_popen(None, r'"C:\Program Files\Tool\tool.exe" --flag') +explicit_outcome = raise_popen(r"D:\other\tool.exe", r'"C:\Program Files\Tool\tool.exe" --flag') +unquoted_outcome = raise_popen(None, r"plain-tool.exe --flag") +)PY"); + CHECK(python.str("quoted_outcome") == "denied"); + CHECK(python.str("explicit_outcome") == "denied"); + CHECK(python.str("unquoted_outcome") == "denied"); + CHECK(describe(harness.prompts) == + "subprocess.Popen: C:\\Program Files\\Tool\\tool.exe\n" + "subprocess.Popen: D:\\other\\tool.exe\n" + "subprocess.Popen: CommandLine:plain-tool.exe --flag\n"); +} + +TEST_CASE("An unquoted Windows command line is granted as one exact command", "[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); + + // An existing executable grant for the first token must not authorize the longer executable + // that CreateProcess may resolve from an unquoted command line. + PluginPermissions legacy; + legacy.process = {R"(C:\Program)"}; + harness.save_permissions(PLUGIN, legacy); + + python.run_as(PLUGIN, R"PY( +def raise_popen(executable, command_line): + try: + sys.audit("subprocess.Popen", executable, command_line, None, None) + return "ok" + except PermissionError: + return "denied" + +tool_a_one = r"C:\Program Files\ToolA\a.exe --one" +)PY"); + + // The legacy C:\Program grant is the first token of ToolA, but the command line is asked for + // as one exact command instead. + python.run_as(PLUGIN, R"PY( +denied_outcome = raise_popen(None, tool_a_one) +)PY"); + CHECK(python.str("denied_outcome") == "denied"); + CHECK(describe(harness.prompts) == + "subprocess.Popen: CommandLine:C:\\Program Files\\ToolA\\a.exe --one\n"); + CHECK(harness.saved_permissions(PLUGIN).process == std::vector{R"(C:\Program)"}); + + // Approving saves that exact command line beside the unrelated legacy grant. + harness.approve = [](const Prompt& prompt) { + return prompt.targets == + std::vector{R"(CommandLine:C:\Program Files\ToolA\a.exe --one)"}; + }; + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +approved_outcome = raise_popen(None, tool_a_one) +)PY"); + CHECK(python.str("approved_outcome") == "ok"); + CHECK(describe(harness.prompts) == + "subprocess.Popen: CommandLine:C:\\Program Files\\ToolA\\a.exe --one\n"); + CHECK(harness.saved_permissions(PLUGIN).process == + std::vector{R"(C:\Program)", R"(CommandLine:C:\Program Files\ToolA\a.exe --one)"}); + + // The same exact command line reuses the saved exact grant. + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +repeat_outcome = raise_popen(None, tool_a_one) +)PY"); + CHECK(python.str("repeat_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); + + // The saved exact grant covers neither changed arguments nor the same arguments on another + // executable, and the legacy C:\Program grant does not cover either exact command line. + harness.approve = [](const Prompt&) { return false; }; + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +changed_arguments_outcome = raise_popen(None, r"C:\Program Files\ToolA\a.exe --two") +other_executable_outcome = raise_popen(None, r"C:\Program Files\ToolB\b.exe --one") +)PY"); + CHECK(python.str("changed_arguments_outcome") == "denied"); + CHECK(python.str("other_executable_outcome") == "denied"); + CHECK(describe(harness.prompts) == + "subprocess.Popen: CommandLine:C:\\Program Files\\ToolA\\a.exe --two\n" + "subprocess.Popen: CommandLine:C:\\Program Files\\ToolB\\b.exe --one\n"); + + // A quoted executable and an explicit executable remain argument-insensitive grants. + PluginPermissions permissions; + permissions.process = {R"(C:\Program Files\Tool\tool.exe)", R"(D:\other\tool.exe)"}; + harness.save_permissions(PLUGIN, permissions); + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +quoted_outcome = raise_popen(None, r'"C:\Program Files\Tool\tool.exe" --changed') +explicit_outcome = raise_popen(r"D:\other\tool.exe", r'"C:\Program Files\Tool\tool.exe" --changed') +)PY"); + CHECK(python.str("quoted_outcome") == "ok"); + CHECK(python.str("explicit_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); +} + +TEST_CASE("A Windows command line grant names one quoted executable, not another 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); + + // The event _winapi.CreateProcess raises, with application_name left out as it may be, so no + // process is created. The quoted paths contain spaces, which a whitespace split would cut. + python.run_as(PLUGIN, R"PY( +def raise_create_process(application_name, command_line): + try: + sys.audit("_winapi.CreateProcess", application_name, command_line, None) + return "ok" + except PermissionError: + return "denied" + +first_outcome = raise_create_process(None, r'"C:\Program Files\ToolA\a.exe" --one') +other_outcome = raise_create_process(None, r'"C:\Program Files\ToolB\b.exe" --one') +explicit_outcome = raise_create_process(r"D:\tools\other.exe", r'"C:\Program Files\ToolA\a.exe" --one') +)PY"); + CHECK(python.str("first_outcome") == "denied"); + CHECK(python.str("other_outcome") == "denied"); + CHECK(python.str("explicit_outcome") == "denied"); + CHECK(describe(harness.prompts) == + "_winapi.CreateProcess: C:\\Program Files\\ToolA\\a.exe\n" + "_winapi.CreateProcess: C:\\Program Files\\ToolB\\b.exe\n" + "_winapi.CreateProcess: D:\\tools\\other.exe\n"); + + // A grant for one quoted path covers that executable with other arguments, never another path. + harness.approve = [](const Prompt& prompt) { + return prompt.targets == std::vector{R"(C:\Program Files\ToolA\a.exe)"}; + }; + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +repeat_outcome = raise_create_process(None, r'"C:\Program Files\ToolA\a.exe" --two') +distinct_outcome = raise_create_process(None, r'"C:\Program Files\ToolB\b.exe" --one') +)PY"); + CHECK(python.str("repeat_outcome") == "ok"); + CHECK(python.str("distinct_outcome") == "denied"); + CHECK(describe(harness.prompts) == + "_winapi.CreateProcess: C:\\Program Files\\ToolA\\a.exe\n" + "_winapi.CreateProcess: C:\\Program Files\\ToolB\\b.exe\n"); + CHECK(harness.saved_permissions(PLUGIN).process == + std::vector{R"(C:\Program Files\ToolA\a.exe)"}); + + // The saved grant covers the same executable again, still without spanning to ToolB. + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +saved_outcome = raise_create_process(None, r'"C:\Program Files\ToolA\a.exe" --three') +other_saved_outcome = raise_create_process(None, r'"C:\Program Files\ToolB\b.exe" --two') +)PY"); + CHECK(python.str("saved_outcome") == "ok"); + CHECK(python.str("other_saved_outcome") == "denied"); + CHECK(describe(harness.prompts) == "_winapi.CreateProcess: C:\\Program Files\\ToolB\\b.exe\n"); +} + +TEST_CASE("An os.system grant names the shell and covers every command", "[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); + const std::vector shells = python.strings("SYSTEM_SHELLS"); + + // Raising the event directly exercises the targets the hook reads without running the command. + // The grants name the shells, not the command string's first token, on every platform. + python.run_as(PLUGIN, R"PY( +def raise_system(command): + try: + sys.audit("os.system", command) + return "ok" + except PermissionError: + return "denied" + +plain_outcome = raise_system("plain-tool --one") +quoted_outcome = raise_system(r'"C:\Program Files\ToolA\a.exe" --one') +other_outcome = raise_system("other-tool") +)PY"); + CHECK(python.str("plain_outcome") == "denied"); + CHECK(python.str("quoted_outcome") == "denied"); + CHECK(python.str("other_outcome") == "denied"); + CHECK(describe(harness.prompts) == + describe_system_prompt(shells) + describe_system_prompt(shells) + describe_system_prompt(shells)); + + // Approving the shells covers every command string, arguments included. + harness.approve = [](const Prompt&) { return true; }; + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +repeat_outcome = raise_system("plain-tool --two") +)PY"); + CHECK(python.str("repeat_outcome") == "ok"); + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().targets == shells); + CHECK(harness.saved_permissions(PLUGIN).process == shells); + + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +quoted_repeat_outcome = raise_system(r'"C:\Program Files\ToolB\b.exe" --flag') +other_repeat_outcome = raise_system("third-tool --three") +)PY"); + CHECK(python.str("quoted_repeat_outcome") == "ok"); + CHECK(python.str("other_repeat_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); +} + +#ifdef _WIN32 +TEST_CASE("An os.system grant for COMSPEC alone does not authorize the fallback shell", "[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); + + // Pin the configured interpreter, so the case does not depend on the machine's COMSPEC. + python.run_as(PLUGIN, R"PY( +saved_comspec = os.environ.get("COMSPEC") +NARROW_SHELL = r"C:\narrow\narrow-shell.exe" +os.environ["COMSPEC"] = NARROW_SHELL + +def raise_system(command): + try: + sys.audit("os.system", command) + return "ok" + except PermissionError: + return "denied" +)PY"); + const std::string narrow_shell = python.str("NARROW_SHELL"); + const std::vector both_shells{narrow_shell, "cmd.exe"}; + + // The runtime falls back to cmd.exe when it cannot open COMSPEC, so the configured + // interpreter's grant alone leaves the event unresolved by the fallback shell. + PluginPermissions permissions; + permissions.process = {narrow_shell}; + harness.save_permissions(PLUGIN, permissions); + python.run_as(PLUGIN, "narrow_outcome = raise_system('anything')"); + CHECK(python.str("narrow_outcome") == "denied"); + CHECK(describe(harness.prompts) == "os.system: cmd.exe\n"); + CHECK(harness.saved_permissions(PLUGIN).process == std::vector{narrow_shell}); + + // One approval saves the missing fallback interpreter, so the next run does not ask again. + harness.approve = [](const Prompt&) { return true; }; + harness.prompts.clear(); + python.run_as(PLUGIN, "approved_outcome = raise_system('anything')"); + CHECK(python.str("approved_outcome") == "ok"); + CHECK(harness.prompts.size() == 1); + if (harness.prompts.size() == 1) + CHECK(harness.prompts.front().targets == std::vector{"cmd.exe"}); + CHECK(harness.saved_permissions(PLUGIN).process == both_shells); + + harness.prompts.clear(); + python.run_as(PLUGIN, "repeat_outcome = raise_system('anything else')"); + CHECK(python.str("repeat_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); + + // A COMSPEC that is the bare fallback name names one interpreter, whatever its casing. + harness.save_permissions(PLUGIN, {}); + harness.approve = [](const Prompt&) { return false; }; + python.run_as(PLUGIN, R"PY( +os.environ["COMSPEC"] = "CmD.eXe" +bare_outcome = raise_system("anything") +)PY"); + CHECK(python.str("bare_outcome") == "denied"); + CHECK(describe(harness.prompts) == "os.system: cmd.exe\n"); + CHECK(harness.saved_permissions(PLUGIN).process.empty()); + + python.run_as(PLUGIN, R"PY( +if saved_comspec is None: + os.environ.pop("COMSPEC", None) +else: + os.environ["COMSPEC"] = saved_comspec +)PY"); +} +#endif + TEST_CASE("A finalizer run when a root frame is let go is judged as the plugin without a prompt", "[audit][Python]") { AuditHarness harness;