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:
iceweasel-oai
2026-09-01 18:24:56 +00:00
committed by copyberry
parent c7c824dce4
commit 1f4c47343a
9 changed files with 259 additions and 113 deletions
@@ -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
);
}
}
}
@@ -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 {