Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Apply remote platform semantics to exec safety checks (#42113)

iceweasel-oai1f4c47343a1b
diff --git a/codex-rs/core/src/exec_policy.rs b/codex-rs/core/src/exec_policy.rs
index bbbe6a27ca..21e414ed01 100644
--- a/codex-rs/core/src/exec_policy.rs
+++ b/codex-rs/core/src/exec_policy.rs
@@ -25,7 +25,8 @@ use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemSandboxKind;
use codex_protocol::protocol::AskForApproval;
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 tokio::fs;
use tokio::sync::Semaphore;
@@ -156,7 +157,6 @@ pub(crate) static BANNED_PREFIX_SUGGESTIONS: &[&[&str]] = &[
pub(crate) enum ExecPolicyCommandOrigin {
/// Use the generic unmatched-command heuristics.
Generic,
- #[cfg(windows)]
/// The command words came from the `-Command` body of a top-level
/// PowerShell wrapper, so use PowerShell-specific unmatched-command
/// heuristics for the lowered words.
@@ -312,12 +312,25 @@ impl ExecPolicyManager {
self.policy.load_full()
}
+ #[cfg(test)]
pub(crate) async fn create_exec_approval_requirement_for_command(
&self,
req: ExecApprovalRequest<'_>,
) -> ExecApprovalRequirement {
- let commands = commands_for_exec_policy(req.command);
- self.create_exec_approval_requirement_for_parsed_commands(req, commands)
+ self.create_exec_approval_requirement_for_command_platform(
+ 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
}
@@ -328,6 +341,7 @@ impl ExecPolicyManager {
commands,
command_origin,
}: ExecPolicyCommands,
+ command_platform: DangerousCommandPlatform,
) -> ExecApprovalRequirement {
let ExecApprovalRequest {
command,
@@ -343,7 +357,7 @@ impl ExecPolicyManager {
// Avoid reusable approvals when this model does not honor prefix rules.
let auto_amendment_allowed = allow_prefix_rules == AllowPrefixRules::Honor;
let exec_policy_fallback = |cmd: &[String]| {
- render_decision_for_unmatched_command(
+ render_decision_for_unmatched_command_for_platform(
cmd,
UnmatchedCommandContext {
approval_policy,
@@ -352,6 +366,7 @@ impl ExecPolicyManager {
sandbox_permissions,
command_origin,
},
+ command_platform,
)
};
let match_options = MatchOptions {
@@ -385,6 +400,7 @@ impl ExecPolicyManager {
&evaluation,
Decision::Forbidden,
command_origin,
+ command_platform,
),
),
},
@@ -403,6 +419,7 @@ impl ExecPolicyManager {
&evaluation,
Decision::Prompt,
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(
command: &[String],
command_origin: ExecPolicyCommandOrigin,
+ command_platform: DangerousCommandPlatform,
) -> Option<DangerousCommandMatch> {
match command_origin {
- ExecPolicyCommandOrigin::Generic => dangerous_command_match(command),
- #[cfg(windows)]
+ ExecPolicyCommandOrigin::Generic => {
+ dangerous_command_match_for_platform(command, command_platform)
+ }
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,
decision: Decision,
command_origin: ExecPolicyCommandOrigin,
+ command_platform: DangerousCommandPlatform,
) -> Option<DangerousCommandMatch> {
evaluation
.matched_rules
@@ -725,19 +748,32 @@ fn dangerous_command_match_for_heuristics(
command,
decision: matched_decision,
} if *matched_decision == decision => {
- dangerous_command_match_for_origin(command, command_origin)
+ dangerous_command_match_for_origin(command, command_origin, command_platform)
}
_ => None,
})
}
/// 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(
command: &[String],
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 {
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 {
approval_policy,
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)
}
+#[cfg(test)]
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)
&& !commands.is_empty()
{
@@ -842,17 +886,15 @@ fn commands_for_exec_policy(command: &[String]) -> ExecPolicyCommands {
};
}
- #[cfg(windows)]
- {
- if let Some(commands) =
+ if command_platform == DangerousCommandPlatform::Windows
+ && let Some(commands) =
codex_shell_command::powershell::parse_powershell_command_into_plain_commands(command)
- && !commands.is_empty()
- {
- return ExecPolicyCommands {
- commands,
- command_origin: ExecPolicyCommandOrigin::PowerShell,
- };
- }
+ && !commands.is_empty()
+ {
+ return ExecPolicyCommands {
+ commands,
+ command_origin: ExecPolicyCommandOrigin::PowerShell,
+ };
}
ExecPolicyCommands {
diff --git a/codex-rs/core/src/exec_policy/executable_identity.rs b/codex-rs/core/src/exec_policy/executable_identity.rs
index 80d7ab8fc5..47363da0e0 100644
--- a/codex-rs/core/src/exec_policy/executable_identity.rs
+++ b/codex-rs/core/src/exec_policy/executable_identity.rs
@@ -1,15 +1,12 @@
use super::ExecApprovalRequest;
-#[cfg(windows)]
use super::ExecPolicyCommandOrigin;
-#[cfg(windows)]
use super::ExecPolicyCommands;
use super::ExecPolicyManager;
-use super::commands_for_exec_policy;
+use super::commands_for_exec_policy_for_platform;
use crate::shell::Shell;
use crate::tools::sandboxing::ExecApprovalRequirement;
-#[cfg(windows)]
+use codex_shell_command::is_dangerous_command::DangerousCommandPlatform;
use codex_shell_command::powershell::extract_powershell_command;
-#[cfg(windows)]
use codex_shell_command::powershell::parse_powershell_script_into_plain_commands;
use codex_tools::UnifiedExecShellMode;
use std::path::Path;
@@ -20,34 +17,39 @@ impl ExecPolicyManager {
mut request: ExecApprovalRequest<'_>,
configured_shell: &Shell,
shell_mode: &UnifiedExecShellMode,
+ command_platform: DangerousCommandPlatform,
) -> ExecApprovalRequirement {
let command = request.command;
let executable = shell_approval_command(command, configured_shell, shell_mode);
if executable.len() == command.len() {
return self
- .create_exec_approval_requirement_for_command(request)
+ .create_exec_approval_requirement_for_command_platform(request, command_platform)
.await;
}
- #[cfg(windows)]
- let mut policy_commands = match extract_powershell_command(command) {
- Some((_, script)) => ExecPolicyCommands {
- commands: parse_powershell_script_into_plain_commands(script)
- .unwrap_or_else(|| vec![command.to_vec()]),
- command_origin: ExecPolicyCommandOrigin::PowerShell,
- },
- None => commands_for_exec_policy(command),
+ let mut policy_commands = if command_platform == DangerousCommandPlatform::Windows {
+ match extract_powershell_command(command) {
+ Some((_, script)) => ExecPolicyCommands {
+ commands: parse_powershell_script_into_plain_commands(script)
+ .unwrap_or_else(|| vec![command.to_vec()]),
+ command_origin: ExecPolicyCommandOrigin::PowerShell,
+ },
+ 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
// commands can add restrictions, but cannot grant the executable trust.
policy_commands.commands.insert(0, executable.to_vec());
request.command = executable;
- self.create_exec_approval_requirement_for_parsed_commands(request, policy_commands)
- .await
+ self.create_exec_approval_requirement_for_parsed_commands(
+ request,
+ policy_commands,
+ command_platform,
+ )
+ .await
}
}
diff --git a/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs b/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs
index 2c7b7a2ef8..8b97ff06b2 100644
--- a/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs
+++ b/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs
@@ -43,6 +43,7 @@ use codex_tools::ToolName;
use codex_tools::ToolSpec;
use codex_utils_output_truncation::approx_token_count;
use codex_utils_path_uri::PathConvention;
+use codex_utils_string::truncate_middle_chars;
use super::super::shell_spec::CommandToolOptions;
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::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)]
pub(crate) struct ExecCommandHandlerOptions {
pub(crate) allow_login_shell: bool,
@@ -276,8 +280,6 @@ impl ExecCommandHandler {
.map_err(FunctionCallError::RespondToModel)?;
let command = resolved_command.command;
let shell_type = resolved_command.shell_type;
- let command_for_display = codex_shell_command::parse_command::shlex_join(&command);
-
let ExecCommandArgs {
mut tty,
yield_time_ms,
@@ -454,9 +456,13 @@ impl ExecCommandHandler {
hook_command: Some(hook_command),
}))
}
- Err(err) => Err(FunctionCallError::RespondToModel(format!(
- "exec_command failed for `{command_for_display}`: {err:?}"
- ))),
+ Err(err) => {
+ let message = format!("exec_command failed: {err:?}");
+ Err(FunctionCallError::RespondToModel(truncate_middle_chars(
+ &message,
+ EXEC_COMMAND_REJECTION_MAX_BYTES,
+ )))
+ }
}
}
}
diff --git a/codex-rs/core/src/unified_exec/process_manager.rs b/codex-rs/core/src/unified_exec/process_manager.rs
index 565f9f5ce4..1a0d829949 100644
--- a/codex-rs/core/src/unified_exec/process_manager.rs
+++ b/codex-rs/core/src/unified_exec/process_manager.rs
@@ -81,6 +81,7 @@ use codex_protocol::protocol::ExecCommandSource;
use codex_protocol::protocol::TerminalInteractionEvent;
use codex_protocol::shell_environment::is_non_inheritable_env_var;
use codex_sandboxing::SandboxCommand;
+use codex_shell_command::is_dangerous_command::DangerousCommandPlatform;
use codex_tools::ToolName;
use codex_utils_output_truncation::approx_tokens_from_byte_count;
use codex_utils_path_uri::PathUri;
@@ -462,7 +463,11 @@ impl UnifiedExecProcessManager {
pub(crate) async fn release_process_id(&self, process_id: i32) {
let removed = {
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 {
unregister_network_approval_for_entry(&entry).await;
@@ -1369,6 +1374,13 @@ impl UnifiedExecProcessManager {
.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
.session
.services
@@ -1390,6 +1402,7 @@ impl UnifiedExecProcessManager {
},
configured_shell,
&request.shell_mode,
+ command_platform,
)
.await;
let req = UnifiedExecToolRequest {
diff --git a/codex-rs/core/src/unified_exec/process_manager_tests.rs b/codex-rs/core/src/unified_exec/process_manager_tests.rs
index 3151f5f8e8..523e7eb513 100644
--- a/codex-rs/core/src/unified_exec/process_manager_tests.rs
+++ b/codex-rs/core/src/unified_exec/process_manager_tests.rs
@@ -37,6 +37,16 @@ fn unified_exec_env_overrides_existing_values() {
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]
fn env_overlay_for_exec_server_keeps_runtime_changes_only() {
let local_policy_env = HashMap::from([
diff --git a/codex-rs/core/tests/remote_env_windows/remote_env_windows_test.rs b/codex-rs/core/tests/remote_env_windows/remote_env_windows_test.rs
index 3035df13b1..98b3fa0200 100644
--- a/codex-rs/core/tests/remote_env_windows/remote_env_windows_test.rs
+++ b/codex-rs/core/tests/remote_env_windows/remote_env_windows_test.rs
@@ -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 PATCH_FILE: &str = "codex-apply-patch-smoke.txt";
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
.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),
"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
.function_call_output_content_and_success(CALL_ID)
.context("command output should be present")?;
diff --git a/codex-rs/core/tests/suite/unified_exec_process_events.rs b/codex-rs/core/tests/suite/unified_exec_process_events.rs
index 89c6e28f83..8a529ab34e 100644
--- a/codex-rs/core/tests/suite/unified_exec_process_events.rs
+++ b/codex-rs/core/tests/suite/unified_exec_process_events.rs
@@ -66,6 +66,7 @@ enum PushedExecScenario {
Complete,
DirectDenied,
ElevatedPowerShell,
+ RejectedLongWindowsDangerousCommand,
SandboxedInterceptedPatch,
SandboxedDirectPatch,
SandboxedDirectPatchDenied,
@@ -153,17 +154,27 @@ async fn respond_environment_info(
id: &Value,
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" })
} else {
json!({ "name": "zsh", "path": "/bin/zsh" })
};
+ let platform_os = matches!(
+ scenario,
+ PushedExecScenario::RejectedLongWindowsDangerousCommand
+ )
+ .then_some("windows");
send_exec_server_json(
websocket,
json!({
"id": id,
"result": {
"shell": shell,
+ "platformOs": platform_os,
"capabilities": { "networkProxyLaunch": true }
}
}),
@@ -390,6 +401,9 @@ async fn serve_exec_with_pushed_events(
send_exec_server_json(&mut websocket, message).await;
}
}
+ PushedExecScenario::RejectedLongWindowsDangerousCommand => {
+ panic!("dangerous command must not reach the executor")
+ }
PushedExecScenario::DirectDenied => {
send_exec_server_json(
&mut websocket,
@@ -464,6 +478,9 @@ async fn serve_exec_with_pushed_events(
PushedExecScenario::ElevatedPowerShell => {
panic!("elevated remote PowerShell must not read a remote process")
}
+ PushedExecScenario::RejectedLongWindowsDangerousCommand => {
+ panic!("dangerous command must not read a remote process")
+ }
PushedExecScenario::SandboxedInterceptedPatch
| PushedExecScenario::SandboxedDirectPatch
| 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::None, true ; "foreign_windows_workspace_sandbox"))]
#[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::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"))]
@@ -590,13 +608,17 @@ async fn exec_command_consumes_pushed_remote_process_events(
&json!({
"cmd": match scenario {
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::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,
})
@@ -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!(
scenario,
PushedExecScenario::SandboxedDirectPatchDenied
@@ -995,6 +1034,9 @@ timeout = 900
assert!(output.contains(COMPLETE_OUTPUT));
assert_eq!(process_read_requests, 0, "unexpected compatibility read");
}
+ PushedExecScenario::RejectedLongWindowsDangerousCommand => {
+ unreachable!("dangerous command returned early")
+ }
PushedExecScenario::DirectDenied => {
assert!(!saw_exec_command_begin);
assert!(output.contains("Process exited with code 1"));
diff --git a/codex-rs/shell-command/src/command_safety/is_dangerous_command.rs b/codex-rs/shell-command/src/command_safety/is_dangerous_command.rs
index d689afdccb..aa2f4d50a3 100644
--- a/codex-rs/shell-command/src/command_safety/is_dangerous_command.rs
+++ b/codex-rs/shell-command/src/command_safety/is_dangerous_command.rs
@@ -1,9 +1,27 @@
use crate::bash::parse_shell_lc_literal_commands;
-use std::path::Path;
-#[cfg(windows)]
#[path = "windows_dangerous_commands.rs"]
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.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
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.
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(
command: &[String],
wrapper_depth: usize,
+ platform: DangerousCommandPlatform,
) -> Option<DangerousCommandMatch> {
if wrapper_depth > MAX_DANGEROUS_COMMAND_WRAPPER_DEPTH {
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);
}
// Support shell scripts where any literal command might be dangerous,
// including commands nested in control flow or substitutions.
if let Some(dangerous_match) = parse_shell_lc_literal_commands(command).and_then(|commands| {
- commands
- .iter()
- .find_map(|command| dangerous_command_match_with_depth(command, wrapper_depth + 1))
+ commands.iter().find_map(|command| {
+ dangerous_command_match_with_depth(command, wrapper_depth + 1, platform)
+ })
}) {
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
}
-/// Returns the dangerous-command rule matched by tokenized PowerShell words.
-pub fn dangerous_powershell_words_match(command: &[String]) -> Option<DangerousCommandMatch> {
- #[cfg(windows)]
- {
+/// Returns the PowerShell-specific rule matched using the target platform's semantics.
+pub fn dangerous_powershell_words_match(
+ command: &[String],
+ platform: DangerousCommandPlatform,
+) -> Option<DangerousCommandMatch> {
+ if platform == DangerousCommandPlatform::Windows {
windows_dangerous_commands::is_dangerous_powershell_words(command)
.then_some(DangerousCommandMatch::Other)
- }
-
- #[cfg(not(windows))]
- {
- let _ = command;
+ } else {
None
}
}
-pub(crate) fn executable_name_lookup_key(raw: &str) -> Option<String> {
- #[cfg(windows)]
- {
- Path::new(raw)
- .file_name()
- .and_then(|name| name.to_str())
- .map(|name| {
- let name = name.to_ascii_lowercase();
- for suffix in [".exe", ".cmd", ".bat", ".com"] {
- if let Some(stripped) = name.strip_suffix(suffix) {
- return stripped.to_string();
- }
+fn executable_name_lookup_key(raw: &str, platform: DangerousCommandPlatform) -> Option<String> {
+ match platform {
+ DangerousCommandPlatform::Posix => raw
+ .rsplit('/')
+ .next()
+ .filter(|name| !name.is_empty())
+ .map(str::to_owned),
+ DangerousCommandPlatform::Windows => {
+ let name = raw
+ .rsplit(['/', '\\'])
+ .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
- })
- }
-
- #[cfg(not(windows))]
- {
- Path::new(raw)
- .file_name()
- .and_then(|name| name.to_str())
- .map(std::borrow::ToOwned::to_owned)
+ }
+ (!name.is_empty()).then_some(name)
+ }
}
}
fn dangerous_command_match_for_exec(
command: &[String],
wrapper_depth: usize,
+ platform: DangerousCommandPlatform,
) -> Option<DangerousCommandMatch> {
let cmd0 = command
.first()
- .and_then(|command| executable_name_lookup_key(command));
+ .and_then(|command| executable_name_lookup_key(command, platform));
match cmd0.as_deref() {
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>.
- 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.
- 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.
- Some("trap") => dangerous_command_match_for_trap(command, wrapper_depth),
+ Some("trap") => dangerous_command_match_for_trap(command, wrapper_depth, platform),
// ── anything else ─────────────────────────────────────────────────
_ => None,
@@ -123,6 +153,7 @@ fn dangerous_command_match_for_exec(
fn dangerous_command_match_for_env(
command: &[String],
wrapper_depth: usize,
+ platform: DangerousCommandPlatform,
) -> Option<DangerousCommandMatch> {
let mut command_index = 1;
while let Some(argument) = command.get(command_index) {
@@ -140,12 +171,13 @@ fn dangerous_command_match_for_env(
}
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(
command: &[String],
wrapper_depth: usize,
+ platform: DangerousCommandPlatform,
) -> Option<DangerousCommandMatch> {
let mut action_index = 1;
if command
@@ -158,7 +190,7 @@ fn dangerous_command_match_for_trap(
.get(action_index)
.filter(|action| !action.starts_with('-'))?;
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 {
@@ -278,11 +310,14 @@ mod tests {
if cfg!(windows) {
assert_eq!(
- dangerous_powershell_words_match(&command),
+ dangerous_powershell_words_match(&command, DangerousCommandPlatform::host()),
Some(DangerousCommandMatch::Other)
);
} else {
- assert_eq!(dangerous_powershell_words_match(&command), None);
+ assert_eq!(
+ dangerous_powershell_words_match(&command, DangerousCommandPlatform::host()),
+ None
+ );
}
}
}
diff --git a/codex-rs/shell-command/src/command_safety/windows_dangerous_commands.rs b/codex-rs/shell-command/src/command_safety/windows_dangerous_commands.rs
index 8bcaf76266..cc1ae671c8 100644
--- a/codex-rs/shell-command/src/command_safety/windows_dangerous_commands.rs
+++ b/codex-rs/shell-command/src/command_safety/windows_dangerous_commands.rs
@@ -1,5 +1,3 @@
-use std::path::Path;
-
use once_cell::sync::Lazy;
use regex::Regex;
use shlex::split as shlex_split;
@@ -335,10 +333,15 @@ fn looks_like_url(token: &str) -> bool {
}
fn executable_basename(exe: &str) -> Option<String> {
- Path::new(exe)
- .file_name()
- .and_then(|osstr| osstr.to_str())
- .map(str::to_ascii_lowercase)
+ let name = exe
+ .rsplit(['/', '\\'])
+ .next()
+ .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 {