mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Apply remote platform semantics to exec safety checks (#42113)
## Why Unified exec can run commands on an OS that differs from the Codex host. Using host path and shell semantics for approval checks can therefore miss dangerous Windows and PowerShell commands sent to a remote executor. ## What changed - Thread the executor platform through command parsing, executable-name normalization, and dangerous-command classification. Legacy executors fall back to the host platform, while unknown reported platforms use Windows rules conservatively. - Bound model-facing `exec_command` rejection messages and avoid echoing the rejected command into the error. - Keep deterministic process IDs reserved after release so rejected test commands cannot reuse an earlier ID. ## Testing - Add coverage that a long dangerous PowerShell command targeting a remote Windows executor is rejected with a bounded response. - Verify deterministic process IDs advance after release. GitOrigin-RevId: a26b4a63ea3d6df7140032b88b3e7aec0b85b948
This commit is contained in:
1 parent
c7c824dce4
commit
1f4c47343a
9 files changed
+259
-113
No files matched your search
@@ -25,7 +25,8 @@ use codex_protocol::models::PermissionProfile;
|
|||||||
use codex_protocol::permissions::FileSystemSandboxKind;
|
use codex_protocol::permissions::FileSystemSandboxKind;
|
||||||
use codex_protocol::protocol::AskForApproval;
|
use codex_protocol::protocol::AskForApproval;
|
||||||
use codex_shell_command::is_dangerous_command::DangerousCommandMatch;
|
use codex_shell_command::is_dangerous_command::DangerousCommandMatch;
|
||||||
use codex_shell_command::is_dangerous_command::dangerous_command_match;
|
use codex_shell_command::is_dangerous_command::DangerousCommandPlatform;
|
||||||
|
use codex_shell_command::is_dangerous_command::dangerous_command_match_for_platform;
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
use tokio::fs;
|
use tokio::fs;
|
||||||
use tokio::sync::Semaphore;
|
use tokio::sync::Semaphore;
|
||||||
@@ -156,7 +157,6 @@ pub(crate) static BANNED_PREFIX_SUGGESTIONS: &[&[&str]] = &[
|
|||||||
pub(crate) enum ExecPolicyCommandOrigin {
|
pub(crate) enum ExecPolicyCommandOrigin {
|
||||||
/// Use the generic unmatched-command heuristics.
|
/// Use the generic unmatched-command heuristics.
|
||||||
Generic,
|
Generic,
|
||||||
#[cfg(windows)]
|
|
||||||
/// The command words came from the `-Command` body of a top-level
|
/// The command words came from the `-Command` body of a top-level
|
||||||
/// PowerShell wrapper, so use PowerShell-specific unmatched-command
|
/// PowerShell wrapper, so use PowerShell-specific unmatched-command
|
||||||
/// heuristics for the lowered words.
|
/// heuristics for the lowered words.
|
||||||
@@ -312,12 +312,25 @@ impl ExecPolicyManager {
|
|||||||
self.policy.load_full()
|
self.policy.load_full()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
pub(crate) async fn create_exec_approval_requirement_for_command(
|
pub(crate) async fn create_exec_approval_requirement_for_command(
|
||||||
&self,
|
&self,
|
||||||
req: ExecApprovalRequest<'_>,
|
req: ExecApprovalRequest<'_>,
|
||||||
) -> ExecApprovalRequirement {
|
) -> ExecApprovalRequirement {
|
||||||
let commands = commands_for_exec_policy(req.command);
|
self.create_exec_approval_requirement_for_command_platform(
|
||||||
self.create_exec_approval_requirement_for_parsed_commands(req, commands)
|
req,
|
||||||
|
DangerousCommandPlatform::host(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn create_exec_approval_requirement_for_command_platform(
|
||||||
|
&self,
|
||||||
|
req: ExecApprovalRequest<'_>,
|
||||||
|
command_platform: DangerousCommandPlatform,
|
||||||
|
) -> ExecApprovalRequirement {
|
||||||
|
let commands = commands_for_exec_policy_for_platform(req.command, command_platform);
|
||||||
|
self.create_exec_approval_requirement_for_parsed_commands(req, commands, command_platform)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -328,6 +341,7 @@ impl ExecPolicyManager {
|
|||||||
commands,
|
commands,
|
||||||
command_origin,
|
command_origin,
|
||||||
}: ExecPolicyCommands,
|
}: ExecPolicyCommands,
|
||||||
|
command_platform: DangerousCommandPlatform,
|
||||||
) -> ExecApprovalRequirement {
|
) -> ExecApprovalRequirement {
|
||||||
let ExecApprovalRequest {
|
let ExecApprovalRequest {
|
||||||
command,
|
command,
|
||||||
@@ -343,7 +357,7 @@ impl ExecPolicyManager {
|
|||||||
// Avoid reusable approvals when this model does not honor prefix rules.
|
// Avoid reusable approvals when this model does not honor prefix rules.
|
||||||
let auto_amendment_allowed = allow_prefix_rules == AllowPrefixRules::Honor;
|
let auto_amendment_allowed = allow_prefix_rules == AllowPrefixRules::Honor;
|
||||||
let exec_policy_fallback = |cmd: &[String]| {
|
let exec_policy_fallback = |cmd: &[String]| {
|
||||||
render_decision_for_unmatched_command(
|
render_decision_for_unmatched_command_for_platform(
|
||||||
cmd,
|
cmd,
|
||||||
UnmatchedCommandContext {
|
UnmatchedCommandContext {
|
||||||
approval_policy,
|
approval_policy,
|
||||||
@@ -352,6 +366,7 @@ impl ExecPolicyManager {
|
|||||||
sandbox_permissions,
|
sandbox_permissions,
|
||||||
command_origin,
|
command_origin,
|
||||||
},
|
},
|
||||||
|
command_platform,
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
let match_options = MatchOptions {
|
let match_options = MatchOptions {
|
||||||
@@ -385,6 +400,7 @@ impl ExecPolicyManager {
|
|||||||
&evaluation,
|
&evaluation,
|
||||||
Decision::Forbidden,
|
Decision::Forbidden,
|
||||||
command_origin,
|
command_origin,
|
||||||
|
command_platform,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
@@ -403,6 +419,7 @@ impl ExecPolicyManager {
|
|||||||
&evaluation,
|
&evaluation,
|
||||||
Decision::Prompt,
|
Decision::Prompt,
|
||||||
command_origin,
|
command_origin,
|
||||||
|
command_platform,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
@@ -701,12 +718,17 @@ pub async fn load_exec_policy(config_stack: &ConfigLayerStack) -> Result<Policy,
|
|||||||
fn dangerous_command_match_for_origin(
|
fn dangerous_command_match_for_origin(
|
||||||
command: &[String],
|
command: &[String],
|
||||||
command_origin: ExecPolicyCommandOrigin,
|
command_origin: ExecPolicyCommandOrigin,
|
||||||
|
command_platform: DangerousCommandPlatform,
|
||||||
) -> Option<DangerousCommandMatch> {
|
) -> Option<DangerousCommandMatch> {
|
||||||
match command_origin {
|
match command_origin {
|
||||||
ExecPolicyCommandOrigin::Generic => dangerous_command_match(command),
|
ExecPolicyCommandOrigin::Generic => {
|
||||||
#[cfg(windows)]
|
dangerous_command_match_for_platform(command, command_platform)
|
||||||
|
}
|
||||||
ExecPolicyCommandOrigin::PowerShell => {
|
ExecPolicyCommandOrigin::PowerShell => {
|
||||||
codex_shell_command::is_dangerous_command::dangerous_powershell_words_match(command)
|
codex_shell_command::is_dangerous_command::dangerous_powershell_words_match(
|
||||||
|
command,
|
||||||
|
command_platform,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -716,6 +738,7 @@ fn dangerous_command_match_for_heuristics(
|
|||||||
evaluation: &Evaluation,
|
evaluation: &Evaluation,
|
||||||
decision: Decision,
|
decision: Decision,
|
||||||
command_origin: ExecPolicyCommandOrigin,
|
command_origin: ExecPolicyCommandOrigin,
|
||||||
|
command_platform: DangerousCommandPlatform,
|
||||||
) -> Option<DangerousCommandMatch> {
|
) -> Option<DangerousCommandMatch> {
|
||||||
evaluation
|
evaluation
|
||||||
.matched_rules
|
.matched_rules
|
||||||
@@ -725,19 +748,32 @@ fn dangerous_command_match_for_heuristics(
|
|||||||
command,
|
command,
|
||||||
decision: matched_decision,
|
decision: matched_decision,
|
||||||
} if *matched_decision == decision => {
|
} if *matched_decision == decision => {
|
||||||
dangerous_command_match_for_origin(command, command_origin)
|
dangerous_command_match_for_origin(command, command_origin, command_platform)
|
||||||
}
|
}
|
||||||
_ => None,
|
_ => None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// If a command is not matched by any execpolicy rule, derive a [`Decision`].
|
/// If a command is not matched by any execpolicy rule, derive a [`Decision`].
|
||||||
|
#[cfg(any(test, unix))]
|
||||||
pub(crate) fn render_decision_for_unmatched_command(
|
pub(crate) fn render_decision_for_unmatched_command(
|
||||||
command: &[String],
|
command: &[String],
|
||||||
context: UnmatchedCommandContext<'_>,
|
context: UnmatchedCommandContext<'_>,
|
||||||
|
) -> Decision {
|
||||||
|
render_decision_for_unmatched_command_for_platform(
|
||||||
|
command,
|
||||||
|
context,
|
||||||
|
DangerousCommandPlatform::host(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_decision_for_unmatched_command_for_platform(
|
||||||
|
command: &[String],
|
||||||
|
context: UnmatchedCommandContext<'_>,
|
||||||
|
command_platform: DangerousCommandPlatform,
|
||||||
) -> Decision {
|
) -> Decision {
|
||||||
let dangerous_command_match =
|
let dangerous_command_match =
|
||||||
dangerous_command_match_for_origin(command, context.command_origin);
|
dangerous_command_match_for_origin(command, context.command_origin, command_platform);
|
||||||
let UnmatchedCommandContext {
|
let UnmatchedCommandContext {
|
||||||
approval_policy,
|
approval_policy,
|
||||||
permission_profile,
|
permission_profile,
|
||||||
@@ -832,7 +868,15 @@ pub(crate) fn default_policy_path(codex_home: &Path) -> PathBuf {
|
|||||||
codex_home.join(RULES_DIR_NAME).join(DEFAULT_POLICY_FILE)
|
codex_home.join(RULES_DIR_NAME).join(DEFAULT_POLICY_FILE)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
fn commands_for_exec_policy(command: &[String]) -> ExecPolicyCommands {
|
fn commands_for_exec_policy(command: &[String]) -> ExecPolicyCommands {
|
||||||
|
commands_for_exec_policy_for_platform(command, DangerousCommandPlatform::host())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn commands_for_exec_policy_for_platform(
|
||||||
|
command: &[String],
|
||||||
|
command_platform: DangerousCommandPlatform,
|
||||||
|
) -> ExecPolicyCommands {
|
||||||
if let Some(commands) = parse_shell_lc_plain_commands(command)
|
if let Some(commands) = parse_shell_lc_plain_commands(command)
|
||||||
&& !commands.is_empty()
|
&& !commands.is_empty()
|
||||||
{
|
{
|
||||||
@@ -842,17 +886,15 @@ fn commands_for_exec_policy(command: &[String]) -> ExecPolicyCommands {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(windows)]
|
if command_platform == DangerousCommandPlatform::Windows
|
||||||
{
|
&& let Some(commands) =
|
||||||
if let Some(commands) =
|
|
||||||
codex_shell_command::powershell::parse_powershell_command_into_plain_commands(command)
|
codex_shell_command::powershell::parse_powershell_command_into_plain_commands(command)
|
||||||
&& !commands.is_empty()
|
&& !commands.is_empty()
|
||||||
{
|
{
|
||||||
return ExecPolicyCommands {
|
return ExecPolicyCommands {
|
||||||
commands,
|
commands,
|
||||||
command_origin: ExecPolicyCommandOrigin::PowerShell,
|
command_origin: ExecPolicyCommandOrigin::PowerShell,
|
||||||
};
|
};
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ExecPolicyCommands {
|
ExecPolicyCommands {
|
||||||
|
|||||||
@@ -1,15 +1,12 @@
|
|||||||
use super::ExecApprovalRequest;
|
use super::ExecApprovalRequest;
|
||||||
#[cfg(windows)]
|
|
||||||
use super::ExecPolicyCommandOrigin;
|
use super::ExecPolicyCommandOrigin;
|
||||||
#[cfg(windows)]
|
|
||||||
use super::ExecPolicyCommands;
|
use super::ExecPolicyCommands;
|
||||||
use super::ExecPolicyManager;
|
use super::ExecPolicyManager;
|
||||||
use super::commands_for_exec_policy;
|
use super::commands_for_exec_policy_for_platform;
|
||||||
use crate::shell::Shell;
|
use crate::shell::Shell;
|
||||||
use crate::tools::sandboxing::ExecApprovalRequirement;
|
use crate::tools::sandboxing::ExecApprovalRequirement;
|
||||||
#[cfg(windows)]
|
use codex_shell_command::is_dangerous_command::DangerousCommandPlatform;
|
||||||
use codex_shell_command::powershell::extract_powershell_command;
|
use codex_shell_command::powershell::extract_powershell_command;
|
||||||
#[cfg(windows)]
|
|
||||||
use codex_shell_command::powershell::parse_powershell_script_into_plain_commands;
|
use codex_shell_command::powershell::parse_powershell_script_into_plain_commands;
|
||||||
use codex_tools::UnifiedExecShellMode;
|
use codex_tools::UnifiedExecShellMode;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
@@ -20,34 +17,39 @@ impl ExecPolicyManager {
|
|||||||
mut request: ExecApprovalRequest<'_>,
|
mut request: ExecApprovalRequest<'_>,
|
||||||
configured_shell: &Shell,
|
configured_shell: &Shell,
|
||||||
shell_mode: &UnifiedExecShellMode,
|
shell_mode: &UnifiedExecShellMode,
|
||||||
|
command_platform: DangerousCommandPlatform,
|
||||||
) -> ExecApprovalRequirement {
|
) -> ExecApprovalRequirement {
|
||||||
let command = request.command;
|
let command = request.command;
|
||||||
let executable = shell_approval_command(command, configured_shell, shell_mode);
|
let executable = shell_approval_command(command, configured_shell, shell_mode);
|
||||||
if executable.len() == command.len() {
|
if executable.len() == command.len() {
|
||||||
return self
|
return self
|
||||||
.create_exec_approval_requirement_for_command(request)
|
.create_exec_approval_requirement_for_command_platform(request, command_platform)
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(windows)]
|
let mut policy_commands = if command_platform == DangerousCommandPlatform::Windows {
|
||||||
let mut policy_commands = match extract_powershell_command(command) {
|
match extract_powershell_command(command) {
|
||||||
Some((_, script)) => ExecPolicyCommands {
|
Some((_, script)) => ExecPolicyCommands {
|
||||||
commands: parse_powershell_script_into_plain_commands(script)
|
commands: parse_powershell_script_into_plain_commands(script)
|
||||||
.unwrap_or_else(|| vec![command.to_vec()]),
|
.unwrap_or_else(|| vec![command.to_vec()]),
|
||||||
command_origin: ExecPolicyCommandOrigin::PowerShell,
|
command_origin: ExecPolicyCommandOrigin::PowerShell,
|
||||||
},
|
},
|
||||||
None => commands_for_exec_policy(command),
|
None => commands_for_exec_policy_for_platform(command, command_platform),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
commands_for_exec_policy_for_platform(command, command_platform)
|
||||||
};
|
};
|
||||||
|
|
||||||
#[cfg(not(windows))]
|
|
||||||
let mut policy_commands = commands_for_exec_policy(command);
|
|
||||||
|
|
||||||
// Evaluate the executable alongside its apparent commands. Inner
|
// Evaluate the executable alongside its apparent commands. Inner
|
||||||
// commands can add restrictions, but cannot grant the executable trust.
|
// commands can add restrictions, but cannot grant the executable trust.
|
||||||
policy_commands.commands.insert(0, executable.to_vec());
|
policy_commands.commands.insert(0, executable.to_vec());
|
||||||
request.command = executable;
|
request.command = executable;
|
||||||
self.create_exec_approval_requirement_for_parsed_commands(request, policy_commands)
|
self.create_exec_approval_requirement_for_parsed_commands(
|
||||||
.await
|
request,
|
||||||
|
policy_commands,
|
||||||
|
command_platform,
|
||||||
|
)
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ use codex_tools::ToolName;
|
|||||||
use codex_tools::ToolSpec;
|
use codex_tools::ToolSpec;
|
||||||
use codex_utils_output_truncation::approx_token_count;
|
use codex_utils_output_truncation::approx_token_count;
|
||||||
use codex_utils_path_uri::PathConvention;
|
use codex_utils_path_uri::PathConvention;
|
||||||
|
use codex_utils_string::truncate_middle_chars;
|
||||||
|
|
||||||
use super::super::shell_spec::CommandToolOptions;
|
use super::super::shell_spec::CommandToolOptions;
|
||||||
use super::super::shell_spec::create_exec_command_tool_with_environment_id;
|
use super::super::shell_spec::create_exec_command_tool_with_environment_id;
|
||||||
@@ -52,6 +53,9 @@ use super::get_command;
|
|||||||
use super::post_unified_exec_tool_use_payload;
|
use super::post_unified_exec_tool_use_payload;
|
||||||
use super::shell_mode_for_environment;
|
use super::shell_mode_for_environment;
|
||||||
|
|
||||||
|
// A byte limit is a conservative hard token bound even for byte-fallback tokenizers.
|
||||||
|
const EXEC_COMMAND_REJECTION_MAX_BYTES: usize = 900;
|
||||||
|
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
pub(crate) struct ExecCommandHandlerOptions {
|
pub(crate) struct ExecCommandHandlerOptions {
|
||||||
pub(crate) allow_login_shell: bool,
|
pub(crate) allow_login_shell: bool,
|
||||||
@@ -276,8 +280,6 @@ impl ExecCommandHandler {
|
|||||||
.map_err(FunctionCallError::RespondToModel)?;
|
.map_err(FunctionCallError::RespondToModel)?;
|
||||||
let command = resolved_command.command;
|
let command = resolved_command.command;
|
||||||
let shell_type = resolved_command.shell_type;
|
let shell_type = resolved_command.shell_type;
|
||||||
let command_for_display = codex_shell_command::parse_command::shlex_join(&command);
|
|
||||||
|
|
||||||
let ExecCommandArgs {
|
let ExecCommandArgs {
|
||||||
mut tty,
|
mut tty,
|
||||||
yield_time_ms,
|
yield_time_ms,
|
||||||
@@ -454,9 +456,13 @@ impl ExecCommandHandler {
|
|||||||
hook_command: Some(hook_command),
|
hook_command: Some(hook_command),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
Err(err) => Err(FunctionCallError::RespondToModel(format!(
|
Err(err) => {
|
||||||
"exec_command failed for `{command_for_display}`: {err:?}"
|
let message = format!("exec_command failed: {err:?}");
|
||||||
))),
|
Err(FunctionCallError::RespondToModel(truncate_middle_chars(
|
||||||
|
&message,
|
||||||
|
EXEC_COMMAND_REJECTION_MAX_BYTES,
|
||||||
|
)))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -81,6 +81,7 @@ use codex_protocol::protocol::ExecCommandSource;
|
|||||||
use codex_protocol::protocol::TerminalInteractionEvent;
|
use codex_protocol::protocol::TerminalInteractionEvent;
|
||||||
use codex_protocol::shell_environment::is_non_inheritable_env_var;
|
use codex_protocol::shell_environment::is_non_inheritable_env_var;
|
||||||
use codex_sandboxing::SandboxCommand;
|
use codex_sandboxing::SandboxCommand;
|
||||||
|
use codex_shell_command::is_dangerous_command::DangerousCommandPlatform;
|
||||||
use codex_tools::ToolName;
|
use codex_tools::ToolName;
|
||||||
use codex_utils_output_truncation::approx_tokens_from_byte_count;
|
use codex_utils_output_truncation::approx_tokens_from_byte_count;
|
||||||
use codex_utils_path_uri::PathUri;
|
use codex_utils_path_uri::PathUri;
|
||||||
@@ -462,7 +463,11 @@ impl UnifiedExecProcessManager {
|
|||||||
pub(crate) async fn release_process_id(&self, process_id: i32) {
|
pub(crate) async fn release_process_id(&self, process_id: i32) {
|
||||||
let removed = {
|
let removed = {
|
||||||
let mut store = self.process_store.lock().await;
|
let mut store = self.process_store.lock().await;
|
||||||
store.remove(process_id)
|
let entry = store.processes.remove(&process_id);
|
||||||
|
if !should_use_deterministic_process_ids() {
|
||||||
|
store.reserved_process_ids.remove(&process_id);
|
||||||
|
}
|
||||||
|
entry
|
||||||
};
|
};
|
||||||
if let Some(entry) = removed {
|
if let Some(entry) = removed {
|
||||||
unregister_network_approval_for_entry(&entry).await;
|
unregister_network_approval_for_entry(&entry).await;
|
||||||
@@ -1369,6 +1374,13 @@ impl UnifiedExecProcessManager {
|
|||||||
.shell
|
.shell
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.unwrap_or(session_shell.as_ref());
|
.unwrap_or(session_shell.as_ref());
|
||||||
|
// Legacy executors omit the platform. Unknown reported platforms use the
|
||||||
|
// more conservative Windows rules rather than silently weakening checks.
|
||||||
|
let command_platform = match request.turn_environment.executor_platform_os.as_deref() {
|
||||||
|
Some("linux" | "macos") => DangerousCommandPlatform::Posix,
|
||||||
|
Some("windows") | Some(_) => DangerousCommandPlatform::Windows,
|
||||||
|
None => DangerousCommandPlatform::host(),
|
||||||
|
};
|
||||||
let exec_approval_requirement = context
|
let exec_approval_requirement = context
|
||||||
.session
|
.session
|
||||||
.services
|
.services
|
||||||
@@ -1390,6 +1402,7 @@ impl UnifiedExecProcessManager {
|
|||||||
},
|
},
|
||||||
configured_shell,
|
configured_shell,
|
||||||
&request.shell_mode,
|
&request.shell_mode,
|
||||||
|
command_platform,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
let req = UnifiedExecToolRequest {
|
let req = UnifiedExecToolRequest {
|
||||||
|
|||||||
@@ -37,6 +37,16 @@ fn unified_exec_env_overrides_existing_values() {
|
|||||||
assert_eq!(env.get("PATH"), Some(&"/usr/bin".to_string()));
|
assert_eq!(env.get("PATH"), Some(&"/usr/bin".to_string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn deterministic_process_ids_are_not_reused_after_release() {
|
||||||
|
let manager = UnifiedExecProcessManager::default();
|
||||||
|
let first = manager.allocate_process_id().await;
|
||||||
|
manager.release_process_id(first).await;
|
||||||
|
let second = manager.allocate_process_id().await;
|
||||||
|
|
||||||
|
assert_eq!((first, second), (1000, 1001));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn env_overlay_for_exec_server_keeps_runtime_changes_only() {
|
fn env_overlay_for_exec_server_keeps_runtime_changes_only() {
|
||||||
let local_policy_env = HashMap::from([
|
let local_policy_env = HashMap::from([
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ async fn windows_exec_server_runs_with_native_shell_and_cwd() -> Result<()> {
|
|||||||
const VERIFY_CALL_ID: &str = "wine-verify-patch";
|
const VERIFY_CALL_ID: &str = "wine-verify-patch";
|
||||||
const PATCH_FILE: &str = "codex-apply-patch-smoke.txt";
|
const PATCH_FILE: &str = "codex-apply-patch-smoke.txt";
|
||||||
const COMMAND: &str = r#"if ((Get-Location).Path -ne 'C:\windows') { exit 1 }"#;
|
const COMMAND: &str = r#"if ((Get-Location).Path -ne 'C:\windows') { exit 1 }"#;
|
||||||
const VERIFY_COMMAND: &str = r#"$path = Join-Path (Get-Location) 'codex-apply-patch-smoke.txt'; if (-not (Test-Path $path)) { exit 1 }; if ([IO.File]::ReadAllText($path) -ne "patched through unified exec`n") { exit 2 }; Remove-Item $path; Write-Output 'PATCH_VERIFIED'"#;
|
const VERIFY_COMMAND: &str = r#"$path = Join-Path (Get-Location) 'codex-apply-patch-smoke.txt'; if (-not (Test-Path $path)) { exit 1 }; if ([IO.File]::ReadAllText($path) -ne "patched through unified exec`n") { exit 2 }; Remove-Item $path"#;
|
||||||
|
|
||||||
WineExecServer
|
WineExecServer
|
||||||
.scope(|exec_server_url, _wine_prefix| async move {
|
.scope(|exec_server_url, _wine_prefix| async move {
|
||||||
@@ -197,13 +197,6 @@ async fn windows_exec_server_runs_with_native_shell_and_cwd() -> Result<()> {
|
|||||||
verify_success != Some(false),
|
verify_success != Some(false),
|
||||||
"verification command failed: {verify_output:?}"
|
"verification command failed: {verify_output:?}"
|
||||||
);
|
);
|
||||||
anyhow::ensure!(
|
|
||||||
verify_output
|
|
||||||
.as_deref()
|
|
||||||
.is_some_and(|output| output.contains("PATCH_VERIFIED")),
|
|
||||||
"verification command did not confirm the patched file: {verify_output:?}"
|
|
||||||
);
|
|
||||||
|
|
||||||
let (_output, success) = request
|
let (_output, success) = request
|
||||||
.function_call_output_content_and_success(CALL_ID)
|
.function_call_output_content_and_success(CALL_ID)
|
||||||
.context("command output should be present")?;
|
.context("command output should be present")?;
|
||||||
|
|||||||
@@ -66,6 +66,7 @@ enum PushedExecScenario {
|
|||||||
Complete,
|
Complete,
|
||||||
DirectDenied,
|
DirectDenied,
|
||||||
ElevatedPowerShell,
|
ElevatedPowerShell,
|
||||||
|
RejectedLongWindowsDangerousCommand,
|
||||||
SandboxedInterceptedPatch,
|
SandboxedInterceptedPatch,
|
||||||
SandboxedDirectPatch,
|
SandboxedDirectPatch,
|
||||||
SandboxedDirectPatchDenied,
|
SandboxedDirectPatchDenied,
|
||||||
@@ -153,17 +154,27 @@ async fn respond_environment_info(
|
|||||||
id: &Value,
|
id: &Value,
|
||||||
scenario: PushedExecScenario,
|
scenario: PushedExecScenario,
|
||||||
) {
|
) {
|
||||||
let shell = if matches!(scenario, PushedExecScenario::ElevatedPowerShell) {
|
let shell = if matches!(
|
||||||
|
scenario,
|
||||||
|
PushedExecScenario::ElevatedPowerShell
|
||||||
|
| PushedExecScenario::RejectedLongWindowsDangerousCommand
|
||||||
|
) {
|
||||||
json!({ "name": "powershell", "path": "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" })
|
json!({ "name": "powershell", "path": "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" })
|
||||||
} else {
|
} else {
|
||||||
json!({ "name": "zsh", "path": "/bin/zsh" })
|
json!({ "name": "zsh", "path": "/bin/zsh" })
|
||||||
};
|
};
|
||||||
|
let platform_os = matches!(
|
||||||
|
scenario,
|
||||||
|
PushedExecScenario::RejectedLongWindowsDangerousCommand
|
||||||
|
)
|
||||||
|
.then_some("windows");
|
||||||
send_exec_server_json(
|
send_exec_server_json(
|
||||||
websocket,
|
websocket,
|
||||||
json!({
|
json!({
|
||||||
"id": id,
|
"id": id,
|
||||||
"result": {
|
"result": {
|
||||||
"shell": shell,
|
"shell": shell,
|
||||||
|
"platformOs": platform_os,
|
||||||
"capabilities": { "networkProxyLaunch": true }
|
"capabilities": { "networkProxyLaunch": true }
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
@@ -390,6 +401,9 @@ async fn serve_exec_with_pushed_events(
|
|||||||
send_exec_server_json(&mut websocket, message).await;
|
send_exec_server_json(&mut websocket, message).await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
PushedExecScenario::RejectedLongWindowsDangerousCommand => {
|
||||||
|
panic!("dangerous command must not reach the executor")
|
||||||
|
}
|
||||||
PushedExecScenario::DirectDenied => {
|
PushedExecScenario::DirectDenied => {
|
||||||
send_exec_server_json(
|
send_exec_server_json(
|
||||||
&mut websocket,
|
&mut websocket,
|
||||||
@@ -464,6 +478,9 @@ async fn serve_exec_with_pushed_events(
|
|||||||
PushedExecScenario::ElevatedPowerShell => {
|
PushedExecScenario::ElevatedPowerShell => {
|
||||||
panic!("elevated remote PowerShell must not read a remote process")
|
panic!("elevated remote PowerShell must not read a remote process")
|
||||||
}
|
}
|
||||||
|
PushedExecScenario::RejectedLongWindowsDangerousCommand => {
|
||||||
|
panic!("dangerous command must not read a remote process")
|
||||||
|
}
|
||||||
PushedExecScenario::SandboxedInterceptedPatch
|
PushedExecScenario::SandboxedInterceptedPatch
|
||||||
| PushedExecScenario::SandboxedDirectPatch
|
| PushedExecScenario::SandboxedDirectPatch
|
||||||
| PushedExecScenario::SandboxedDirectPatchDenied
|
| PushedExecScenario::SandboxedDirectPatchDenied
|
||||||
@@ -555,6 +572,7 @@ async fn serve_exec_with_pushed_events(
|
|||||||
#[cfg_attr(not(windows), test_case(PushedExecScenario::Complete, ManagedNetworkScenario::Enabled { policy_callbacks: true }, true ; "foreign_windows_managed_network_preserves_approval_registration"))]
|
#[cfg_attr(not(windows), test_case(PushedExecScenario::Complete, ManagedNetworkScenario::Enabled { policy_callbacks: true }, true ; "foreign_windows_managed_network_preserves_approval_registration"))]
|
||||||
#[cfg_attr(not(windows), test_case(PushedExecScenario::Complete, ManagedNetworkScenario::None, true ; "foreign_windows_workspace_sandbox"))]
|
#[cfg_attr(not(windows), test_case(PushedExecScenario::Complete, ManagedNetworkScenario::None, true ; "foreign_windows_workspace_sandbox"))]
|
||||||
#[test_case(PushedExecScenario::ElevatedPowerShell, ManagedNetworkScenario::None, true ; "windows_elevated_powershell_disables_profile")]
|
#[test_case(PushedExecScenario::ElevatedPowerShell, ManagedNetworkScenario::None, true ; "windows_elevated_powershell_disables_profile")]
|
||||||
|
#[cfg_attr(not(windows), test_case(PushedExecScenario::RejectedLongWindowsDangerousCommand, ManagedNetworkScenario::None, true ; "remote_windows_dangerous_command_rejection_is_bounded"))]
|
||||||
#[cfg_attr(not(windows), test_case(PushedExecScenario::SandboxedInterceptedPatch, ManagedNetworkScenario::None, true ; "foreign_windows_intercepted_patch_is_sandboxed"))]
|
#[cfg_attr(not(windows), test_case(PushedExecScenario::SandboxedInterceptedPatch, ManagedNetworkScenario::None, true ; "foreign_windows_intercepted_patch_is_sandboxed"))]
|
||||||
#[cfg_attr(not(windows), test_case(PushedExecScenario::SandboxedDirectPatch, ManagedNetworkScenario::None, true ; "foreign_windows_direct_patch_is_sandboxed"))]
|
#[cfg_attr(not(windows), test_case(PushedExecScenario::SandboxedDirectPatch, ManagedNetworkScenario::None, true ; "foreign_windows_direct_patch_is_sandboxed"))]
|
||||||
#[cfg_attr(not(windows), test_case(PushedExecScenario::SandboxedDirectPatchDenied, ManagedNetworkScenario::None, true ; "foreign_windows_direct_patch_denial_requests_approval"))]
|
#[cfg_attr(not(windows), test_case(PushedExecScenario::SandboxedDirectPatchDenied, ManagedNetworkScenario::None, true ; "foreign_windows_direct_patch_denial_requests_approval"))]
|
||||||
@@ -590,13 +608,17 @@ async fn exec_command_consumes_pushed_remote_process_events(
|
|||||||
&json!({
|
&json!({
|
||||||
"cmd": match scenario {
|
"cmd": match scenario {
|
||||||
PushedExecScenario::SandboxedInterceptedPatch => {
|
PushedExecScenario::SandboxedInterceptedPatch => {
|
||||||
"apply_patch <<'PATCH'\n*** Begin Patch\n*** Update File: secret.txt\n@@\n-old\n+new\n*** End Patch\nPATCH"
|
"apply_patch <<'PATCH'\n*** Begin Patch\n*** Update File: secret.txt\n@@\n-old\n+new\n*** End Patch\nPATCH".to_string()
|
||||||
}
|
}
|
||||||
PushedExecScenario::UnsandboxedInterceptedPatch
|
PushedExecScenario::UnsandboxedInterceptedPatch
|
||||||
| PushedExecScenario::FullDiskInterceptedPatch => {
|
| PushedExecScenario::FullDiskInterceptedPatch => {
|
||||||
"apply_patch <<'PATCH'\n*** Begin Patch\n*** Add File: allowed.txt\n+allowed\n*** End Patch\nPATCH"
|
"apply_patch <<'PATCH'\n*** Begin Patch\n*** Add File: allowed.txt\n+allowed\n*** End Patch\nPATCH".to_string()
|
||||||
}
|
}
|
||||||
_ => "pwd",
|
PushedExecScenario::RejectedLongWindowsDangerousCommand => format!(
|
||||||
|
"Remove-Item test -Force; {}",
|
||||||
|
"Write-Output filler; ".repeat(2_000)
|
||||||
|
),
|
||||||
|
_ => "pwd".to_string(),
|
||||||
},
|
},
|
||||||
"yield_time_ms": 1_000,
|
"yield_time_ms": 1_000,
|
||||||
})
|
})
|
||||||
@@ -805,6 +827,23 @@ timeout = 900
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if matches!(
|
||||||
|
scenario,
|
||||||
|
PushedExecScenario::RejectedLongWindowsDangerousCommand
|
||||||
|
) {
|
||||||
|
let request = response_mock
|
||||||
|
.last_request()
|
||||||
|
.context("model should receive the dangerous-command rejection")?;
|
||||||
|
let (output, success) = request
|
||||||
|
.function_call_output_content_and_success(CALL_ID)
|
||||||
|
.context("dangerous-command rejection should be model visible")?;
|
||||||
|
assert_ne!(success, Some(true));
|
||||||
|
let output = output.context("dangerous-command rejection should contain text")?;
|
||||||
|
assert!(output.len() < 1_000);
|
||||||
|
assert!(output.contains("chars truncated"));
|
||||||
|
exec_server.abort();
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
if matches!(
|
if matches!(
|
||||||
scenario,
|
scenario,
|
||||||
PushedExecScenario::SandboxedDirectPatchDenied
|
PushedExecScenario::SandboxedDirectPatchDenied
|
||||||
@@ -995,6 +1034,9 @@ timeout = 900
|
|||||||
assert!(output.contains(COMPLETE_OUTPUT));
|
assert!(output.contains(COMPLETE_OUTPUT));
|
||||||
assert_eq!(process_read_requests, 0, "unexpected compatibility read");
|
assert_eq!(process_read_requests, 0, "unexpected compatibility read");
|
||||||
}
|
}
|
||||||
|
PushedExecScenario::RejectedLongWindowsDangerousCommand => {
|
||||||
|
unreachable!("dangerous command returned early")
|
||||||
|
}
|
||||||
PushedExecScenario::DirectDenied => {
|
PushedExecScenario::DirectDenied => {
|
||||||
assert!(!saw_exec_command_begin);
|
assert!(!saw_exec_command_begin);
|
||||||
assert!(output.contains("Process exited with code 1"));
|
assert!(output.contains("Process exited with code 1"));
|
||||||
|
|||||||
@@ -1,9 +1,27 @@
|
|||||||
use crate::bash::parse_shell_lc_literal_commands;
|
use crate::bash::parse_shell_lc_literal_commands;
|
||||||
use std::path::Path;
|
|
||||||
#[cfg(windows)]
|
|
||||||
#[path = "windows_dangerous_commands.rs"]
|
#[path = "windows_dangerous_commands.rs"]
|
||||||
mod windows_dangerous_commands;
|
mod windows_dangerous_commands;
|
||||||
|
|
||||||
|
/// The platform whose command semantics should be used for safety checks.
|
||||||
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||||
|
pub enum DangerousCommandPlatform {
|
||||||
|
/// POSIX command and path semantics.
|
||||||
|
Posix,
|
||||||
|
/// Windows command and path semantics.
|
||||||
|
Windows,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DangerousCommandPlatform {
|
||||||
|
/// Returns the platform where the classifier is running.
|
||||||
|
pub fn host() -> Self {
|
||||||
|
if cfg!(windows) {
|
||||||
|
Self::Windows
|
||||||
|
} else {
|
||||||
|
Self::Posix
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Identifies the dangerous-command rule matched by a command invocation.
|
/// Identifies the dangerous-command rule matched by a command invocation.
|
||||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||||
pub enum DangerousCommandMatch {
|
pub enum DangerousCommandMatch {
|
||||||
@@ -17,89 +35,99 @@ const MAX_DANGEROUS_COMMAND_WRAPPER_DEPTH: usize = 8;
|
|||||||
|
|
||||||
/// Returns the dangerous-command rule matched by an already-tokenized command.
|
/// Returns the dangerous-command rule matched by an already-tokenized command.
|
||||||
pub fn dangerous_command_match(command: &[String]) -> Option<DangerousCommandMatch> {
|
pub fn dangerous_command_match(command: &[String]) -> Option<DangerousCommandMatch> {
|
||||||
dangerous_command_match_with_depth(command, /*wrapper_depth*/ 0)
|
dangerous_command_match_for_platform(command, DangerousCommandPlatform::host())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the dangerous-command rule matched using the target platform's semantics.
|
||||||
|
pub fn dangerous_command_match_for_platform(
|
||||||
|
command: &[String],
|
||||||
|
platform: DangerousCommandPlatform,
|
||||||
|
) -> Option<DangerousCommandMatch> {
|
||||||
|
dangerous_command_match_with_depth(command, /*wrapper_depth*/ 0, platform)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn dangerous_command_match_with_depth(
|
fn dangerous_command_match_with_depth(
|
||||||
command: &[String],
|
command: &[String],
|
||||||
wrapper_depth: usize,
|
wrapper_depth: usize,
|
||||||
|
platform: DangerousCommandPlatform,
|
||||||
) -> Option<DangerousCommandMatch> {
|
) -> Option<DangerousCommandMatch> {
|
||||||
if wrapper_depth > MAX_DANGEROUS_COMMAND_WRAPPER_DEPTH {
|
if wrapper_depth > MAX_DANGEROUS_COMMAND_WRAPPER_DEPTH {
|
||||||
return Some(DangerousCommandMatch::Other);
|
return Some(DangerousCommandMatch::Other);
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(dangerous_match) = dangerous_command_match_for_exec(command, wrapper_depth) {
|
if let Some(dangerous_match) =
|
||||||
|
dangerous_command_match_for_exec(command, wrapper_depth, platform)
|
||||||
|
{
|
||||||
return Some(dangerous_match);
|
return Some(dangerous_match);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Support shell scripts where any literal command might be dangerous,
|
// Support shell scripts where any literal command might be dangerous,
|
||||||
// including commands nested in control flow or substitutions.
|
// including commands nested in control flow or substitutions.
|
||||||
if let Some(dangerous_match) = parse_shell_lc_literal_commands(command).and_then(|commands| {
|
if let Some(dangerous_match) = parse_shell_lc_literal_commands(command).and_then(|commands| {
|
||||||
commands
|
commands.iter().find_map(|command| {
|
||||||
.iter()
|
dangerous_command_match_with_depth(command, wrapper_depth + 1, platform)
|
||||||
.find_map(|command| dangerous_command_match_with_depth(command, wrapper_depth + 1))
|
})
|
||||||
}) {
|
}) {
|
||||||
return Some(dangerous_match);
|
return Some(dangerous_match);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(windows)]
|
if platform == DangerousCommandPlatform::Windows
|
||||||
|
&& windows_dangerous_commands::is_dangerous_command_windows(command)
|
||||||
{
|
{
|
||||||
if windows_dangerous_commands::is_dangerous_command_windows(command) {
|
return Some(DangerousCommandMatch::Other);
|
||||||
return Some(DangerousCommandMatch::Other);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the dangerous-command rule matched by tokenized PowerShell words.
|
/// Returns the PowerShell-specific rule matched using the target platform's semantics.
|
||||||
pub fn dangerous_powershell_words_match(command: &[String]) -> Option<DangerousCommandMatch> {
|
pub fn dangerous_powershell_words_match(
|
||||||
#[cfg(windows)]
|
command: &[String],
|
||||||
{
|
platform: DangerousCommandPlatform,
|
||||||
|
) -> Option<DangerousCommandMatch> {
|
||||||
|
if platform == DangerousCommandPlatform::Windows {
|
||||||
windows_dangerous_commands::is_dangerous_powershell_words(command)
|
windows_dangerous_commands::is_dangerous_powershell_words(command)
|
||||||
.then_some(DangerousCommandMatch::Other)
|
.then_some(DangerousCommandMatch::Other)
|
||||||
}
|
} else {
|
||||||
|
|
||||||
#[cfg(not(windows))]
|
|
||||||
{
|
|
||||||
let _ = command;
|
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn executable_name_lookup_key(raw: &str) -> Option<String> {
|
fn executable_name_lookup_key(raw: &str, platform: DangerousCommandPlatform) -> Option<String> {
|
||||||
#[cfg(windows)]
|
match platform {
|
||||||
{
|
DangerousCommandPlatform::Posix => raw
|
||||||
Path::new(raw)
|
.rsplit('/')
|
||||||
.file_name()
|
.next()
|
||||||
.and_then(|name| name.to_str())
|
.filter(|name| !name.is_empty())
|
||||||
.map(|name| {
|
.map(str::to_owned),
|
||||||
let name = name.to_ascii_lowercase();
|
DangerousCommandPlatform::Windows => {
|
||||||
for suffix in [".exe", ".cmd", ".bat", ".com"] {
|
let name = raw
|
||||||
if let Some(stripped) = name.strip_suffix(suffix) {
|
.rsplit(['/', '\\'])
|
||||||
return stripped.to_string();
|
.next()
|
||||||
}
|
.filter(|name| !name.is_empty())?;
|
||||||
|
let name = match name.as_bytes() {
|
||||||
|
[drive, b':', ..] if drive.is_ascii_alphabetic() => &name[2..],
|
||||||
|
_ => name,
|
||||||
|
};
|
||||||
|
let name = name.to_ascii_lowercase();
|
||||||
|
for suffix in [".exe", ".cmd", ".bat", ".com"] {
|
||||||
|
if let Some(stripped) = name.strip_suffix(suffix) {
|
||||||
|
return Some(stripped.to_string());
|
||||||
}
|
}
|
||||||
name
|
}
|
||||||
})
|
(!name.is_empty()).then_some(name)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(windows))]
|
|
||||||
{
|
|
||||||
Path::new(raw)
|
|
||||||
.file_name()
|
|
||||||
.and_then(|name| name.to_str())
|
|
||||||
.map(std::borrow::ToOwned::to_owned)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn dangerous_command_match_for_exec(
|
fn dangerous_command_match_for_exec(
|
||||||
command: &[String],
|
command: &[String],
|
||||||
wrapper_depth: usize,
|
wrapper_depth: usize,
|
||||||
|
platform: DangerousCommandPlatform,
|
||||||
) -> Option<DangerousCommandMatch> {
|
) -> Option<DangerousCommandMatch> {
|
||||||
let cmd0 = command
|
let cmd0 = command
|
||||||
.first()
|
.first()
|
||||||
.and_then(|command| executable_name_lookup_key(command));
|
.and_then(|command| executable_name_lookup_key(command, platform));
|
||||||
|
|
||||||
match cmd0.as_deref() {
|
match cmd0.as_deref() {
|
||||||
Some("rm") if rm_args_include_force_option(&command[1..]) => {
|
Some("rm") if rm_args_include_force_option(&command[1..]) => {
|
||||||
@@ -107,13 +135,15 @@ fn dangerous_command_match_for_exec(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// For sudo <cmd>, simply check <cmd>.
|
// For sudo <cmd>, simply check <cmd>.
|
||||||
Some("sudo") => dangerous_command_match_with_depth(&command[1..], wrapper_depth + 1),
|
Some("sudo") => {
|
||||||
|
dangerous_command_match_with_depth(&command[1..], wrapper_depth + 1, platform)
|
||||||
|
}
|
||||||
|
|
||||||
// Skip environment assignments before checking the command run by env.
|
// Skip environment assignments before checking the command run by env.
|
||||||
Some("env") => dangerous_command_match_for_env(command, wrapper_depth),
|
Some("env") => dangerous_command_match_for_env(command, wrapper_depth, platform),
|
||||||
|
|
||||||
// A trap action is shell source stored in the first operand.
|
// A trap action is shell source stored in the first operand.
|
||||||
Some("trap") => dangerous_command_match_for_trap(command, wrapper_depth),
|
Some("trap") => dangerous_command_match_for_trap(command, wrapper_depth, platform),
|
||||||
|
|
||||||
// ── anything else ─────────────────────────────────────────────────
|
// ── anything else ─────────────────────────────────────────────────
|
||||||
_ => None,
|
_ => None,
|
||||||
@@ -123,6 +153,7 @@ fn dangerous_command_match_for_exec(
|
|||||||
fn dangerous_command_match_for_env(
|
fn dangerous_command_match_for_env(
|
||||||
command: &[String],
|
command: &[String],
|
||||||
wrapper_depth: usize,
|
wrapper_depth: usize,
|
||||||
|
platform: DangerousCommandPlatform,
|
||||||
) -> Option<DangerousCommandMatch> {
|
) -> Option<DangerousCommandMatch> {
|
||||||
let mut command_index = 1;
|
let mut command_index = 1;
|
||||||
while let Some(argument) = command.get(command_index) {
|
while let Some(argument) = command.get(command_index) {
|
||||||
@@ -140,12 +171,13 @@ fn dangerous_command_match_for_env(
|
|||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
dangerous_command_match_with_depth(&command[command_index..], wrapper_depth + 1)
|
dangerous_command_match_with_depth(&command[command_index..], wrapper_depth + 1, platform)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn dangerous_command_match_for_trap(
|
fn dangerous_command_match_for_trap(
|
||||||
command: &[String],
|
command: &[String],
|
||||||
wrapper_depth: usize,
|
wrapper_depth: usize,
|
||||||
|
platform: DangerousCommandPlatform,
|
||||||
) -> Option<DangerousCommandMatch> {
|
) -> Option<DangerousCommandMatch> {
|
||||||
let mut action_index = 1;
|
let mut action_index = 1;
|
||||||
if command
|
if command
|
||||||
@@ -158,7 +190,7 @@ fn dangerous_command_match_for_trap(
|
|||||||
.get(action_index)
|
.get(action_index)
|
||||||
.filter(|action| !action.starts_with('-'))?;
|
.filter(|action| !action.starts_with('-'))?;
|
||||||
let shell_command = vec!["sh".to_string(), "-c".to_string(), action.clone()];
|
let shell_command = vec!["sh".to_string(), "-c".to_string(), action.clone()];
|
||||||
dangerous_command_match_with_depth(&shell_command, wrapper_depth + 1)
|
dangerous_command_match_with_depth(&shell_command, wrapper_depth + 1, platform)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn rm_args_include_force_option(args: &[String]) -> bool {
|
fn rm_args_include_force_option(args: &[String]) -> bool {
|
||||||
@@ -278,11 +310,14 @@ mod tests {
|
|||||||
|
|
||||||
if cfg!(windows) {
|
if cfg!(windows) {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
dangerous_powershell_words_match(&command),
|
dangerous_powershell_words_match(&command, DangerousCommandPlatform::host()),
|
||||||
Some(DangerousCommandMatch::Other)
|
Some(DangerousCommandMatch::Other)
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
assert_eq!(dangerous_powershell_words_match(&command), None);
|
assert_eq!(
|
||||||
|
dangerous_powershell_words_match(&command, DangerousCommandPlatform::host()),
|
||||||
|
None
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,3 @@
|
|||||||
use std::path::Path;
|
|
||||||
|
|
||||||
use once_cell::sync::Lazy;
|
use once_cell::sync::Lazy;
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
use shlex::split as shlex_split;
|
use shlex::split as shlex_split;
|
||||||
@@ -335,10 +333,15 @@ fn looks_like_url(token: &str) -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn executable_basename(exe: &str) -> Option<String> {
|
fn executable_basename(exe: &str) -> Option<String> {
|
||||||
Path::new(exe)
|
let name = exe
|
||||||
.file_name()
|
.rsplit(['/', '\\'])
|
||||||
.and_then(|osstr| osstr.to_str())
|
.next()
|
||||||
.map(str::to_ascii_lowercase)
|
.filter(|name| !name.is_empty())?;
|
||||||
|
let name = match name.as_bytes() {
|
||||||
|
[drive, b':', ..] if drive.is_ascii_alphabetic() => &name[2..],
|
||||||
|
_ => name,
|
||||||
|
};
|
||||||
|
(!name.is_empty()).then(|| name.to_ascii_lowercase())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_powershell_executable(exe: &str) -> bool {
|
fn is_powershell_executable(exe: &str) -> bool {
|
||||||
|
|||||||
Reference in new issue
Block a user