mirror of
https://github.com/openai/codex.git
synced 2026-11-25 23:30:49 +00:00
Derive trusted PowerShell paths from Windows
This commit is contained in:
@@ -614,17 +614,14 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_powershell_full_path_is_safe() {
|
||||
if !cfg!(windows) {
|
||||
// Windows only because on Linux path splitting doesn't handle `/` separators properly
|
||||
return;
|
||||
}
|
||||
|
||||
let powershell = r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
|
||||
if !std::path::Path::new(powershell).is_file() {
|
||||
return;
|
||||
}
|
||||
let powershell = crate::command_safety::trusted_windows_powershell_invocation_path()
|
||||
.expect("Windows PowerShell must exist at the authoritative System known folder");
|
||||
let powershell = powershell
|
||||
.to_str()
|
||||
.expect("the Windows System known folder must be valid UTF-8");
|
||||
|
||||
assert!(is_known_safe_command(&vec_str(&[
|
||||
powershell,
|
||||
|
||||
@@ -4,4 +4,8 @@ pub mod is_dangerous_command;
|
||||
pub mod is_safe_command;
|
||||
#[cfg(windows)]
|
||||
pub(crate) mod windows_safe_commands;
|
||||
#[cfg(all(test, windows))]
|
||||
pub(crate) use powershell_parser::trusted_standard_pwsh_invocation_path;
|
||||
#[cfg(all(test, windows))]
|
||||
pub(crate) use powershell_parser::trusted_windows_powershell_invocation_path;
|
||||
pub(crate) use powershell_parser::try_parse_powershell_ast_commands;
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
|
||||
#[cfg(windows)]
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::collections::HashMap;
|
||||
#[cfg(windows)]
|
||||
use std::ffi::OsString;
|
||||
use std::io::BufRead;
|
||||
use std::io::BufReader;
|
||||
use std::io::ErrorKind;
|
||||
use std::io::Write;
|
||||
#[cfg(any(test, windows))]
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Child;
|
||||
use std::process::ChildStdin;
|
||||
use std::process::ChildStdout;
|
||||
@@ -20,9 +24,9 @@ use std::sync::PoisonError;
|
||||
|
||||
const POWERSHELL_PARSER_SCRIPT: &str = include_str!("powershell_parser.ps1");
|
||||
#[cfg(any(test, windows))]
|
||||
const WINDOWS_POWERSHELL_EXE: &str = r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
|
||||
const WINDOWS_POWERSHELL_SUFFIX: &str = r"WindowsPowerShell\v1.0\powershell.exe";
|
||||
#[cfg(any(test, windows))]
|
||||
const WINDOWS_PWSH_EXE: &str = r"C:\Program Files\PowerShell\7\pwsh.exe";
|
||||
const WINDOWS_PWSH_SUFFIX: &str = r"PowerShell\7\pwsh.exe";
|
||||
|
||||
/// Cache one long-lived parser process per executable path so repeated safety checks reuse
|
||||
/// PowerShell startup work while still consulting the real parser every time.
|
||||
@@ -30,8 +34,8 @@ const WINDOWS_PWSH_EXE: &str = r"C:\Program Files\PowerShell\7\pwsh.exe";
|
||||
/// We keep the cache behind one mutex because each child process speaks a simple
|
||||
/// request/response protocol over a single stdin/stdout pair, so callers targeting the same
|
||||
/// executable must serialize access anyway.
|
||||
fn parse_with_powershell_ast(executable: &str, script: &str) -> PowershellParseOutcome {
|
||||
static PARSER_PROCESSES: LazyLock<Mutex<HashMap<String, PowershellParserProcess>>> =
|
||||
fn parse_with_powershell_ast(executable: &Path, script: &str) -> PowershellParseOutcome {
|
||||
static PARSER_PROCESSES: LazyLock<Mutex<HashMap<PathBuf, PowershellParserProcess>>> =
|
||||
LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
let mut parser_processes = PARSER_PROCESSES
|
||||
@@ -45,7 +49,7 @@ pub(crate) fn try_parse_powershell_ast_commands(
|
||||
script: &str,
|
||||
) -> Option<Vec<Vec<String>>> {
|
||||
let parser_executable = trusted_powershell_parser_executable(executable)?;
|
||||
match parse_with_powershell_ast(parser_executable, script) {
|
||||
match parse_with_powershell_ast(&parser_executable, script) {
|
||||
PowershellParseOutcome::Commands(commands) => Some(commands),
|
||||
PowershellParseOutcome::Unsupported | PowershellParseOutcome::Failed => None,
|
||||
}
|
||||
@@ -55,12 +59,18 @@ pub(crate) fn try_parse_powershell_ast_commands(
|
||||
///
|
||||
/// The parser runs before the command approval and sandbox boundaries. Bare executable names and
|
||||
/// arbitrary paths are therefore not eligible: their eventual resolution can depend on the
|
||||
/// workspace, current directory, or `PATH`. Returning a fixed path also ensures the parser spawn
|
||||
/// never receives the command's attacker-controlled `argv[0]`.
|
||||
fn trusted_powershell_parser_executable(executable: &str) -> Option<&'static str> {
|
||||
/// workspace, current directory, or `PATH`. Returning a canonical executable derived from an
|
||||
/// authoritative Windows known folder also ensures the parser spawn never receives the command's
|
||||
/// attacker-controlled `argv[0]`.
|
||||
fn trusted_powershell_parser_executable(executable: &str) -> Option<PathBuf> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
resolve_trusted_powershell_parser_executable(executable, Path::is_file)
|
||||
resolve_trusted_powershell_parser_executable_with(
|
||||
executable,
|
||||
trusted_windows_root,
|
||||
canonicalize_trusted_windows_path,
|
||||
Path::is_file,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
@@ -70,21 +80,153 @@ fn trusted_powershell_parser_executable(executable: &str) -> Option<&'static str
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the authoritative Windows PowerShell invocation path only when the production trust
|
||||
/// resolver accepts that exact known-folder-derived path.
|
||||
#[cfg(all(test, windows))]
|
||||
pub(crate) fn trusted_windows_powershell_invocation_path() -> Option<PathBuf> {
|
||||
trusted_powershell_invocation_path(TrustedPowerShellRoot::System, WINDOWS_POWERSHELL_SUFFIX)
|
||||
}
|
||||
|
||||
/// Returns the standard machine-wide PowerShell 7 invocation path when it is installed and the
|
||||
/// production trust resolver accepts it.
|
||||
#[cfg(all(test, windows))]
|
||||
pub(crate) fn trusted_standard_pwsh_invocation_path() -> Option<PathBuf> {
|
||||
trusted_powershell_invocation_path(TrustedPowerShellRoot::ProgramFiles, WINDOWS_PWSH_SUFFIX)
|
||||
}
|
||||
|
||||
#[cfg(all(test, windows))]
|
||||
fn trusted_powershell_invocation_path(
|
||||
root_kind: TrustedPowerShellRoot,
|
||||
suffix: &str,
|
||||
) -> Option<PathBuf> {
|
||||
let root = trusted_windows_root(root_kind).ok()?;
|
||||
let invocation_path = join_windows_path(&root, suffix);
|
||||
let invocation_path_str = invocation_path.to_str()?;
|
||||
trusted_powershell_parser_executable(invocation_path_str)?;
|
||||
Some(invocation_path)
|
||||
}
|
||||
|
||||
#[cfg(any(test, windows))]
|
||||
fn resolve_trusted_powershell_parser_executable(
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum TrustedPowerShellRoot {
|
||||
System,
|
||||
ProgramFiles,
|
||||
}
|
||||
|
||||
#[cfg(any(test, windows))]
|
||||
fn resolve_trusted_powershell_parser_executable_with(
|
||||
executable: &str,
|
||||
resolve_root: impl Fn(TrustedPowerShellRoot) -> std::io::Result<PathBuf>,
|
||||
canonicalize: impl Fn(&Path) -> std::io::Result<PathBuf>,
|
||||
is_file: impl Fn(&Path) -> bool,
|
||||
) -> Option<&'static str> {
|
||||
let normalized_executable = executable
|
||||
.strip_prefix(r"\\?\")
|
||||
.unwrap_or(executable)
|
||||
.replace('/', "\\");
|
||||
) -> Option<PathBuf> {
|
||||
let normalized_executable = normalized_windows_path(executable);
|
||||
|
||||
let trusted_path = [WINDOWS_POWERSHELL_EXE, WINDOWS_PWSH_EXE]
|
||||
.into_iter()
|
||||
.find(|candidate| normalized_executable.eq_ignore_ascii_case(candidate))?;
|
||||
[
|
||||
(TrustedPowerShellRoot::System, WINDOWS_POWERSHELL_SUFFIX),
|
||||
(TrustedPowerShellRoot::ProgramFiles, WINDOWS_PWSH_SUFFIX),
|
||||
]
|
||||
.into_iter()
|
||||
.find_map(|(root_kind, suffix)| {
|
||||
let root = resolve_root(root_kind).ok()?;
|
||||
let candidate = join_windows_path(&root, suffix);
|
||||
let candidate_str = candidate.to_str()?;
|
||||
if !normalized_executable.eq_ignore_ascii_case(&normalized_windows_path(candidate_str)) {
|
||||
return None;
|
||||
}
|
||||
|
||||
is_file(Path::new(trusted_path)).then_some(trusted_path)
|
||||
let canonical_root = canonicalize(&root).ok()?;
|
||||
let canonical_candidate = canonicalize(&candidate).ok()?;
|
||||
let expected_candidate = join_windows_path(&canonical_root, suffix);
|
||||
if !normalized_windows_path(canonical_candidate.to_str()?)
|
||||
.eq_ignore_ascii_case(&normalized_windows_path(expected_candidate.to_str()?))
|
||||
|| !is_file(&canonical_candidate)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(canonical_candidate)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn join_windows_path(root: &Path, suffix: &str) -> PathBuf {
|
||||
root.join(suffix)
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(windows)))]
|
||||
fn join_windows_path(root: &Path, suffix: &str) -> PathBuf {
|
||||
let mut path = root
|
||||
.to_string_lossy()
|
||||
.trim_end_matches(['/', '\\'])
|
||||
.to_string();
|
||||
path.push('\\');
|
||||
path.push_str(suffix);
|
||||
PathBuf::from(path)
|
||||
}
|
||||
|
||||
#[cfg(any(test, windows))]
|
||||
fn normalized_windows_path(path: &str) -> String {
|
||||
path.strip_prefix(r"\\?\")
|
||||
.unwrap_or(path)
|
||||
.replace('/', "\\")
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn canonicalize_trusted_windows_path(path: &Path) -> std::io::Result<PathBuf> {
|
||||
AbsolutePathBuf::from_absolute_path_checked(path)?
|
||||
.canonicalize()
|
||||
.map(AbsolutePathBuf::into_path_buf)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn trusted_windows_root(root: TrustedPowerShellRoot) -> std::io::Result<PathBuf> {
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
use windows_sys::Win32::System::Com::CoTaskMemFree;
|
||||
use windows_sys::Win32::UI::Shell::FOLDERID_ProgramFiles;
|
||||
use windows_sys::Win32::UI::Shell::FOLDERID_System;
|
||||
use windows_sys::Win32::UI::Shell::KF_FLAG_DEFAULT;
|
||||
use windows_sys::Win32::UI::Shell::SHGetKnownFolderPath;
|
||||
|
||||
let folder_id = match root {
|
||||
TrustedPowerShellRoot::System => &FOLDERID_System,
|
||||
TrustedPowerShellRoot::ProgramFiles => &FOLDERID_ProgramFiles,
|
||||
};
|
||||
let mut path_ptr = std::ptr::null_mut::<u16>();
|
||||
let flags = u32::try_from(KF_FLAG_DEFAULT)
|
||||
.map_err(|_| std::io::Error::other("KF_FLAG_DEFAULT did not fit in u32"))?;
|
||||
// SAFETY: SHGetKnownFolderPath initializes path_ptr with a CoTaskMem-allocated,
|
||||
// null-terminated UTF-16 string on success.
|
||||
let hr = unsafe { SHGetKnownFolderPath(folder_id, flags, 0, &mut path_ptr) };
|
||||
if hr != 0 {
|
||||
if !path_ptr.is_null() {
|
||||
// SAFETY: Any non-null path returned by SHGetKnownFolderPath uses CoTaskMem.
|
||||
unsafe { CoTaskMemFree(path_ptr.cast()) };
|
||||
}
|
||||
return Err(std::io::Error::other(format!(
|
||||
"SHGetKnownFolderPath failed with HRESULT {hr:#010x}"
|
||||
)));
|
||||
}
|
||||
if path_ptr.is_null() {
|
||||
return Err(std::io::Error::other(
|
||||
"SHGetKnownFolderPath returned a null pointer",
|
||||
));
|
||||
}
|
||||
|
||||
// SAFETY: path_ptr is a valid null-terminated UTF-16 string allocated by
|
||||
// SHGetKnownFolderPath and is freed after copying.
|
||||
let path = unsafe {
|
||||
let mut len = 0usize;
|
||||
while *path_ptr.add(len) != 0 {
|
||||
len += 1;
|
||||
}
|
||||
let wide = std::slice::from_raw_parts(path_ptr, len);
|
||||
let path = PathBuf::from(OsString::from_wide(wide));
|
||||
CoTaskMemFree(path_ptr.cast());
|
||||
path
|
||||
};
|
||||
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
@@ -95,13 +237,13 @@ pub(super) enum PowershellParseOutcome {
|
||||
}
|
||||
|
||||
fn parse_with_cached_process(
|
||||
parser_processes: &mut HashMap<String, PowershellParserProcess>,
|
||||
executable: &str,
|
||||
parser_processes: &mut HashMap<PathBuf, PowershellParserProcess>,
|
||||
executable: &Path,
|
||||
script: &str,
|
||||
) -> PowershellParseOutcome {
|
||||
// `powershell.exe` and `pwsh.exe` do not accept the same language surface, so each
|
||||
// executable keeps its own parser process and request stream.
|
||||
let parser_key = executable.to_string();
|
||||
let parser_key = executable.to_path_buf();
|
||||
for attempt in 0..=1 {
|
||||
if !parser_processes.contains_key(&parser_key) {
|
||||
match PowershellParserProcess::spawn(executable) {
|
||||
@@ -155,7 +297,7 @@ struct PowershellParserProcess {
|
||||
}
|
||||
|
||||
impl PowershellParserProcess {
|
||||
fn spawn(executable: &str) -> std::io::Result<Self> {
|
||||
fn spawn(executable: &Path) -> std::io::Result<Self> {
|
||||
let mut child = Command::new(executable)
|
||||
.args([
|
||||
"-NoLogo",
|
||||
@@ -314,18 +456,19 @@ mod trust_tests;
|
||||
#[cfg(all(test, windows))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::powershell::try_find_powershell_executable_blocking;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn parser_process_handles_multiple_requests() {
|
||||
let Some(powershell) = try_find_powershell_executable_blocking() else {
|
||||
return;
|
||||
};
|
||||
let powershell = powershell.as_path().to_str().unwrap();
|
||||
let mut parser = PowershellParserProcess::spawn(powershell).unwrap();
|
||||
fn production_resolver_handles_multiple_windows_powershell_requests() {
|
||||
let powershell = trusted_windows_powershell_invocation_path()
|
||||
.expect("Windows PowerShell must exist at the authoritative System known folder");
|
||||
let powershell = powershell
|
||||
.to_str()
|
||||
.expect("the Windows System known folder must be valid UTF-8");
|
||||
|
||||
let first = parser.parse("Get-Content 'foo bar'").unwrap();
|
||||
let first = try_parse_powershell_ast_commands(powershell, "Get-Content 'foo bar'")
|
||||
.map(PowershellParseOutcome::Commands)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
first,
|
||||
PowershellParseOutcome::Commands(vec![vec![
|
||||
@@ -334,7 +477,10 @@ mod tests {
|
||||
]]),
|
||||
);
|
||||
|
||||
let second = parser.parse("Write-Output foo | Measure-Object").unwrap();
|
||||
let second =
|
||||
try_parse_powershell_ast_commands(powershell, "Write-Output foo | Measure-Object")
|
||||
.map(PowershellParseOutcome::Commands)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
second,
|
||||
PowershellParseOutcome::Commands(vec![
|
||||
@@ -345,12 +491,38 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parser_process_rejects_stop_parsing_forms() {
|
||||
let Some(powershell) = try_find_powershell_executable_blocking() else {
|
||||
fn production_resolver_uses_standard_machine_wide_pwsh_when_installed() {
|
||||
let Some(pwsh) = trusted_standard_pwsh_invocation_path() else {
|
||||
eprintln!(
|
||||
"skipping standard pwsh trust test because Program Files\\PowerShell\\7\\pwsh.exe is not installed"
|
||||
);
|
||||
return;
|
||||
};
|
||||
let powershell = powershell.as_path().to_str().unwrap();
|
||||
let mut parser = PowershellParserProcess::spawn(powershell).unwrap();
|
||||
let pwsh = pwsh
|
||||
.to_str()
|
||||
.expect("the Program Files known folder must be valid UTF-8");
|
||||
|
||||
assert_eq!(
|
||||
try_parse_powershell_ast_commands(pwsh, "pwd && ls"),
|
||||
Some(vec![vec!["pwd".to_string()], vec!["ls".to_string()]])
|
||||
);
|
||||
}
|
||||
|
||||
fn trusted_windows_powershell_parser() -> PathBuf {
|
||||
let invocation_path = trusted_windows_powershell_invocation_path()
|
||||
.expect("Windows PowerShell must exist at the authoritative System known folder");
|
||||
trusted_powershell_parser_executable(
|
||||
invocation_path
|
||||
.to_str()
|
||||
.expect("the Windows System known folder must be valid UTF-8"),
|
||||
)
|
||||
.expect("the production trust resolver must accept Windows PowerShell")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parser_process_rejects_stop_parsing_forms() {
|
||||
let powershell = trusted_windows_powershell_parser();
|
||||
let mut parser = PowershellParserProcess::spawn(&powershell).unwrap();
|
||||
|
||||
let parsed = parser
|
||||
.parse("git log --% HEAD --output=codex_poc.txt")
|
||||
@@ -360,11 +532,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn parser_process_rejects_param_blocks() {
|
||||
let Some(powershell) = try_find_powershell_executable_blocking() else {
|
||||
return;
|
||||
};
|
||||
let powershell = powershell.as_path().to_str().unwrap();
|
||||
let mut parser = PowershellParserProcess::spawn(powershell).unwrap();
|
||||
let powershell = trusted_windows_powershell_parser();
|
||||
let mut parser = PowershellParserProcess::spawn(&powershell).unwrap();
|
||||
|
||||
let parsed = parser
|
||||
.parse("param([string]$path = (Get-Location)) Write-Output test")
|
||||
@@ -374,11 +543,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn parser_process_rejects_named_blocks() {
|
||||
let Some(powershell) = try_find_powershell_executable_blocking() else {
|
||||
return;
|
||||
};
|
||||
let powershell = powershell.as_path().to_str().unwrap();
|
||||
let mut parser = PowershellParserProcess::spawn(powershell).unwrap();
|
||||
let powershell = trusted_windows_powershell_parser();
|
||||
let mut parser = PowershellParserProcess::spawn(&powershell).unwrap();
|
||||
|
||||
let parsed = parser
|
||||
.parse("begin { Set-Content codex_poc.txt pwned } end { Get-Content Cargo.toml }")
|
||||
@@ -388,11 +554,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn parser_process_rejects_using_statements() {
|
||||
let Some(powershell) = try_find_powershell_executable_blocking() else {
|
||||
return;
|
||||
};
|
||||
let powershell = powershell.as_path().to_str().unwrap();
|
||||
let mut parser = PowershellParserProcess::spawn(powershell).unwrap();
|
||||
let powershell = trusted_windows_powershell_parser();
|
||||
let mut parser = PowershellParserProcess::spawn(&powershell).unwrap();
|
||||
|
||||
let parsed = parser
|
||||
.parse("using module ./codex_poc.psm1\nGet-Content Cargo.toml")
|
||||
@@ -402,11 +565,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn parser_process_rejects_trap_blocks() {
|
||||
let Some(powershell) = try_find_powershell_executable_blocking() else {
|
||||
return;
|
||||
};
|
||||
let powershell = powershell.as_path().to_str().unwrap();
|
||||
let mut parser = PowershellParserProcess::spawn(powershell).unwrap();
|
||||
let powershell = trusted_windows_powershell_parser();
|
||||
let mut parser = PowershellParserProcess::spawn(&powershell).unwrap();
|
||||
|
||||
let parsed = parser
|
||||
.parse(
|
||||
|
||||
@@ -1,31 +1,85 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::io;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn resolve_existing(executable: &str) -> Option<&'static str> {
|
||||
resolve_trusted_powershell_parser_executable(executable, |_| true)
|
||||
const DEFAULT_SYSTEM_ROOT: &str = r"C:\Windows\System32";
|
||||
const DEFAULT_PROGRAM_FILES_ROOT: &str = r"C:\Program Files";
|
||||
const DEFAULT_WINDOWS_POWERSHELL_EXE: &str =
|
||||
r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
|
||||
const DEFAULT_WINDOWS_PWSH_EXE: &str = r"C:\Program Files\PowerShell\7\pwsh.exe";
|
||||
|
||||
fn default_root(root: TrustedPowerShellRoot) -> io::Result<PathBuf> {
|
||||
Ok(match root {
|
||||
TrustedPowerShellRoot::System => PathBuf::from(DEFAULT_SYSTEM_ROOT),
|
||||
TrustedPowerShellRoot::ProgramFiles => PathBuf::from(DEFAULT_PROGRAM_FILES_ROOT),
|
||||
})
|
||||
}
|
||||
|
||||
fn resolve_existing(executable: &str) -> Option<PathBuf> {
|
||||
resolve_trusted_powershell_parser_executable_with(
|
||||
executable,
|
||||
default_root,
|
||||
|path| Ok(path.to_path_buf()),
|
||||
|_| true,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_only_fixed_trusted_powershell_paths() {
|
||||
fn accepts_only_authoritative_powershell_paths() {
|
||||
assert_eq!(
|
||||
resolve_existing(WINDOWS_POWERSHELL_EXE),
|
||||
Some(WINDOWS_POWERSHELL_EXE),
|
||||
resolve_existing(DEFAULT_WINDOWS_POWERSHELL_EXE),
|
||||
Some(PathBuf::from(DEFAULT_WINDOWS_POWERSHELL_EXE)),
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_existing(r"c:/WINDOWS/System32/WindowsPowerShell/v1.0/POWERSHELL.EXE"),
|
||||
Some(WINDOWS_POWERSHELL_EXE),
|
||||
Some(PathBuf::from(DEFAULT_WINDOWS_POWERSHELL_EXE)),
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_existing(r"\\?\C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"),
|
||||
Some(WINDOWS_POWERSHELL_EXE),
|
||||
Some(PathBuf::from(DEFAULT_WINDOWS_POWERSHELL_EXE)),
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_existing(DEFAULT_WINDOWS_PWSH_EXE),
|
||||
Some(PathBuf::from(DEFAULT_WINDOWS_PWSH_EXE)),
|
||||
);
|
||||
assert_eq!(resolve_existing(WINDOWS_PWSH_EXE), Some(WINDOWS_PWSH_EXE));
|
||||
assert_eq!(
|
||||
resolve_existing(r"c:/program files/powershell/7/PWSH.EXE"),
|
||||
Some(WINDOWS_PWSH_EXE),
|
||||
Some(PathBuf::from(DEFAULT_WINDOWS_PWSH_EXE)),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derives_trust_from_non_c_known_folders() {
|
||||
let resolve_root = |root| {
|
||||
Ok(match root {
|
||||
TrustedPowerShellRoot::System => PathBuf::from(r"D:\Windows\System32"),
|
||||
TrustedPowerShellRoot::ProgramFiles => PathBuf::from(r"E:\Program Files"),
|
||||
})
|
||||
};
|
||||
let resolve = |executable| {
|
||||
resolve_trusted_powershell_parser_executable_with(
|
||||
executable,
|
||||
resolve_root,
|
||||
|path| Ok(path.to_path_buf()),
|
||||
|_| true,
|
||||
)
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
resolve(r"d:/WINDOWS/System32/WindowsPowerShell/v1.0/POWERSHELL.EXE"),
|
||||
Some(PathBuf::from(
|
||||
r"D:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
|
||||
)),
|
||||
);
|
||||
assert_eq!(
|
||||
resolve(r"E:\Program Files\PowerShell\7\pwsh.exe"),
|
||||
Some(PathBuf::from(r"E:\Program Files\PowerShell\7\pwsh.exe")),
|
||||
);
|
||||
assert_eq!(resolve(DEFAULT_WINDOWS_POWERSHELL_EXE), None);
|
||||
assert_eq!(resolve(DEFAULT_WINDOWS_PWSH_EXE), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_search_path_and_workspace_controlled_variants() {
|
||||
for executable in [
|
||||
@@ -72,13 +126,70 @@ fn rejects_command_wrappers_and_path_aliases() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fails_closed_when_the_trusted_install_is_missing() {
|
||||
fn fails_closed_when_a_known_folder_or_install_is_missing() {
|
||||
let resolve_root = |root| match root {
|
||||
TrustedPowerShellRoot::System => Err(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
"system root unavailable",
|
||||
)),
|
||||
TrustedPowerShellRoot::ProgramFiles => Ok(PathBuf::from(DEFAULT_PROGRAM_FILES_ROOT)),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
resolve_trusted_powershell_parser_executable(WINDOWS_POWERSHELL_EXE, |_| false),
|
||||
resolve_trusted_powershell_parser_executable_with(
|
||||
DEFAULT_WINDOWS_POWERSHELL_EXE,
|
||||
resolve_root,
|
||||
|path| Ok(path.to_path_buf()),
|
||||
|_| true,
|
||||
),
|
||||
None,
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_trusted_powershell_parser_executable(WINDOWS_PWSH_EXE, |_| false),
|
||||
resolve_trusted_powershell_parser_executable_with(
|
||||
DEFAULT_WINDOWS_PWSH_EXE,
|
||||
resolve_root,
|
||||
|path| Ok(path.to_path_buf()),
|
||||
|_| true,
|
||||
),
|
||||
Some(PathBuf::from(DEFAULT_WINDOWS_PWSH_EXE)),
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_trusted_powershell_parser_executable_with(
|
||||
DEFAULT_WINDOWS_PWSH_EXE,
|
||||
resolve_root,
|
||||
|path| Ok(path.to_path_buf()),
|
||||
|_| false,
|
||||
),
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_canonicalization_failures_and_reparse_escape() {
|
||||
assert_eq!(
|
||||
resolve_trusted_powershell_parser_executable_with(
|
||||
DEFAULT_WINDOWS_POWERSHELL_EXE,
|
||||
default_root,
|
||||
|_| Err(io::Error::other("canonicalization failed")),
|
||||
|_| true,
|
||||
),
|
||||
None,
|
||||
);
|
||||
|
||||
let escaped = resolve_trusted_powershell_parser_executable_with(
|
||||
DEFAULT_WINDOWS_POWERSHELL_EXE,
|
||||
default_root,
|
||||
|path| {
|
||||
if path
|
||||
.to_string_lossy()
|
||||
.ends_with(r"WindowsPowerShell\v1.0\powershell.exe")
|
||||
{
|
||||
Ok(PathBuf::from(r"C:\Users\attacker\powershell.exe"))
|
||||
} else {
|
||||
Ok(path.to_path_buf())
|
||||
}
|
||||
},
|
||||
|_| true,
|
||||
);
|
||||
assert_eq!(escaped, None);
|
||||
}
|
||||
|
||||
@@ -219,12 +219,29 @@ mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::string::ToString;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
const POWERSHELL_EXE: &str = r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
|
||||
const PWSH_EXE: &str = r"C:\Program Files\PowerShell\7\pwsh.exe";
|
||||
static WINDOWS_POWERSHELL_EXE: LazyLock<String> = LazyLock::new(|| {
|
||||
crate::command_safety::trusted_windows_powershell_invocation_path()
|
||||
.expect("Windows PowerShell must exist at the authoritative System known folder")
|
||||
.to_str()
|
||||
.expect("the Windows System known folder must be valid UTF-8")
|
||||
.to_string()
|
||||
});
|
||||
|
||||
fn installed_pwsh() -> Option<&'static str> {
|
||||
Path::new(PWSH_EXE).is_file().then_some(PWSH_EXE)
|
||||
static STANDARD_PWSH_EXE: LazyLock<Option<String>> = LazyLock::new(|| {
|
||||
crate::command_safety::trusted_standard_pwsh_invocation_path().map(|path| {
|
||||
path.to_str()
|
||||
.expect("the Program Files known folder must be valid UTF-8")
|
||||
.to_string()
|
||||
})
|
||||
});
|
||||
STANDARD_PWSH_EXE.as_deref()
|
||||
}
|
||||
|
||||
fn windows_powershell_exe() -> &'static str {
|
||||
WINDOWS_POWERSHELL_EXE.as_str()
|
||||
}
|
||||
|
||||
/// Converts a slice of string literals into owned `String`s for the tests.
|
||||
@@ -235,21 +252,21 @@ mod tests {
|
||||
#[test]
|
||||
fn recognizes_safe_powershell_wrappers() {
|
||||
assert!(is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-NoLogo",
|
||||
"-Command",
|
||||
"Get-ChildItem -Path .",
|
||||
])));
|
||||
|
||||
assert!(is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-NoProfile",
|
||||
"-Command",
|
||||
"git status",
|
||||
])));
|
||||
|
||||
assert!(is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"Get-Content",
|
||||
"Cargo.toml",
|
||||
])));
|
||||
@@ -282,7 +299,7 @@ mod tests {
|
||||
}
|
||||
|
||||
assert!(is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-Command",
|
||||
"Get-Content Cargo.toml",
|
||||
])));
|
||||
@@ -290,10 +307,6 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn rejects_workspace_controlled_powershell_binaries_before_parser_spawn() {
|
||||
if !Path::new(POWERSHELL_EXE).is_file() {
|
||||
return;
|
||||
}
|
||||
|
||||
let unique = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
@@ -306,8 +319,8 @@ mod tests {
|
||||
|
||||
let fake_powershell = test_dir.join("powershell.exe");
|
||||
let fake_pwsh = test_dir.join("pwsh.exe");
|
||||
std::fs::copy(POWERSHELL_EXE, &fake_powershell).unwrap();
|
||||
std::fs::copy(POWERSHELL_EXE, &fake_pwsh).unwrap();
|
||||
std::fs::copy(windows_powershell_exe(), &fake_powershell).unwrap();
|
||||
std::fs::copy(windows_powershell_exe(), &fake_pwsh).unwrap();
|
||||
|
||||
let results = [&fake_powershell, &fake_pwsh].map(|executable| {
|
||||
is_safe_command_windows(&vec_str(&[
|
||||
@@ -413,7 +426,7 @@ mod tests {
|
||||
(
|
||||
script,
|
||||
is_safe_command_windows(&[
|
||||
POWERSHELL_EXE.to_string(),
|
||||
windows_powershell_exe().to_string(),
|
||||
"-NoProfile".to_string(),
|
||||
"-Command".to_string(),
|
||||
script.to_string(),
|
||||
@@ -437,7 +450,7 @@ mod tests {
|
||||
#[test]
|
||||
fn rejects_stop_parsing_git_forms() {
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-NoProfile",
|
||||
"-Command",
|
||||
"git log --% HEAD --output=codex_poc.txt",
|
||||
@@ -447,7 +460,7 @@ mod tests {
|
||||
#[test]
|
||||
fn rejects_powershell_param_blocks() {
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-NoProfile",
|
||||
"-Command",
|
||||
"param([string]$path = (Get-Location)) Write-Output test",
|
||||
@@ -457,7 +470,7 @@ mod tests {
|
||||
#[test]
|
||||
fn rejects_powershell_named_blocks() {
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-NoProfile",
|
||||
"-Command",
|
||||
"begin { Set-Content codex_poc.txt pwned } end { Get-Content Cargo.toml }",
|
||||
@@ -467,7 +480,7 @@ mod tests {
|
||||
#[test]
|
||||
fn rejects_powershell_using_statements() {
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-NoProfile",
|
||||
"-Command",
|
||||
"using module ./codex_poc.psm1\nGet-Content Cargo.toml",
|
||||
@@ -477,7 +490,7 @@ mod tests {
|
||||
#[test]
|
||||
fn rejects_powershell_trap_blocks() {
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-NoProfile",
|
||||
"-Command",
|
||||
"trap { Set-Content codex_poc.txt pwned; continue } Get-Content missing -ErrorAction Stop",
|
||||
@@ -487,97 +500,97 @@ mod tests {
|
||||
#[test]
|
||||
fn rejects_powershell_commands_with_side_effects() {
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-NoLogo",
|
||||
"-Command",
|
||||
"Remove-Item foo.txt",
|
||||
])));
|
||||
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-NoProfile",
|
||||
"-Command",
|
||||
"rg --pre cat",
|
||||
])));
|
||||
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-Command",
|
||||
"Set-Content foo.txt 'hello'",
|
||||
])));
|
||||
|
||||
// Redirections are blocked
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-Command",
|
||||
"echo hi > out.txt",
|
||||
])));
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-Command",
|
||||
"Get-Content x | Out-File y",
|
||||
])));
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-Command",
|
||||
"Write-Output foo 2> err.txt",
|
||||
])));
|
||||
|
||||
// Call operator is blocked
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-Command",
|
||||
"& Remove-Item foo",
|
||||
])));
|
||||
|
||||
// Chained safe + unsafe must fail
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-Command",
|
||||
"Get-ChildItem; Remove-Item foo",
|
||||
])));
|
||||
// Nested unsafe cmdlet inside safe command must fail
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-Command",
|
||||
"Write-Output (Set-Content foo6.txt 'abc')",
|
||||
])));
|
||||
// Additional nested unsafe cmdlet examples must fail
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-Command",
|
||||
"Write-Host (Remove-Item foo.txt)",
|
||||
])));
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-Command",
|
||||
"Get-Content (New-Item bar.txt)",
|
||||
])));
|
||||
|
||||
// Unsafe @ expansion.
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-Command",
|
||||
"ls @(calc.exe)"
|
||||
])));
|
||||
|
||||
// Unsupported constructs that the AST parser refuses (no fallback to manual splitting).
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-Command",
|
||||
"ls && pwd"
|
||||
])));
|
||||
|
||||
// Sub-expressions are rejected even if they contain otherwise safe commands.
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-Command",
|
||||
"Write-Output $(Get-Content foo)"
|
||||
])));
|
||||
|
||||
// Empty words from the parser (e.g. '') are rejected.
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-Command",
|
||||
"''"
|
||||
])));
|
||||
@@ -586,13 +599,13 @@ mod tests {
|
||||
#[test]
|
||||
fn accepts_constant_expression_arguments() {
|
||||
assert!(is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-Command",
|
||||
"Get-Content 'foo bar'"
|
||||
])));
|
||||
|
||||
assert!(is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-Command",
|
||||
"Get-Content \"foo bar\""
|
||||
])));
|
||||
@@ -601,13 +614,13 @@ mod tests {
|
||||
#[test]
|
||||
fn rejects_dynamic_arguments() {
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-Command",
|
||||
"Get-Content $foo"
|
||||
])));
|
||||
|
||||
assert!(!is_safe_command_windows(&vec_str(&[
|
||||
POWERSHELL_EXE,
|
||||
windows_powershell_exe(),
|
||||
"-Command",
|
||||
"Write-Output \"foo $bar\""
|
||||
])));
|
||||
@@ -621,9 +634,12 @@ mod tests {
|
||||
|
||||
let chain = "pwd && ls";
|
||||
assert!(
|
||||
!is_safe_command_windows(&vec_str(
|
||||
&[POWERSHELL_EXE, "-NoProfile", "-Command", chain,]
|
||||
)),
|
||||
!is_safe_command_windows(&vec_str(&[
|
||||
windows_powershell_exe(),
|
||||
"-NoProfile",
|
||||
"-Command",
|
||||
chain,
|
||||
])),
|
||||
"`{chain}` is not recognized by powershell.exe"
|
||||
);
|
||||
|
||||
|
||||
@@ -159,8 +159,13 @@ mod tests {
|
||||
use super::prefix_powershell_script_with_utf8;
|
||||
|
||||
#[cfg(windows)]
|
||||
const WINDOWS_POWERSHELL_EXE: &str =
|
||||
r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
|
||||
fn trusted_windows_powershell_executable() -> String {
|
||||
crate::command_safety::trusted_windows_powershell_invocation_path()
|
||||
.expect("Windows PowerShell must exist at the authoritative System known folder")
|
||||
.to_str()
|
||||
.expect("the Windows System known folder must be valid UTF-8")
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extracts_basic_powershell_command() {
|
||||
@@ -187,11 +192,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn extracts_full_path_powershell_command() {
|
||||
let command = if cfg!(windows) {
|
||||
"C:\\windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe".to_string()
|
||||
} else {
|
||||
"/usr/local/bin/powershell.exe".to_string()
|
||||
};
|
||||
#[cfg(windows)]
|
||||
let command = trusted_windows_powershell_executable();
|
||||
#[cfg(not(windows))]
|
||||
let command = "/usr/local/bin/powershell.exe".to_string();
|
||||
let cmd = vec![command, "-Command".to_string(), "Write-Host hi".to_string()];
|
||||
let (_shell, script) = extract_powershell_command(&cmd).expect("extract");
|
||||
assert_eq!(script, "Write-Host hi");
|
||||
@@ -244,7 +248,7 @@ mod tests {
|
||||
#[test]
|
||||
fn parses_plain_powershell_commands() {
|
||||
let commands = parse_powershell_command_into_plain_commands(&[
|
||||
WINDOWS_POWERSHELL_EXE.to_string(),
|
||||
trusted_windows_powershell_executable(),
|
||||
"-NoProfile".to_string(),
|
||||
"-Command".to_string(),
|
||||
"echo hi".to_string(),
|
||||
@@ -258,7 +262,7 @@ mod tests {
|
||||
#[test]
|
||||
fn parses_multiple_plain_powershell_commands() {
|
||||
let commands = parse_powershell_command_into_plain_commands(&[
|
||||
WINDOWS_POWERSHELL_EXE.to_string(),
|
||||
trusted_windows_powershell_executable(),
|
||||
"-NoProfile".to_string(),
|
||||
"-Command".to_string(),
|
||||
"Write-Output foo | Measure-Object".to_string(),
|
||||
|
||||
Reference in New Issue
Block a user